Skip to content

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.

model-apps 2.14.0: Notes timeline, sub-grid placement, lookup and filter labels, generative-page safety, bundled SDK update, faster rebuilds (#722)

Akshay Maloobc35eeefce53
diff --git a/.github/workflows/model-apps-script-tests.yml b/.github/workflows/model-apps-script-tests.yml
index 4324c7fa1..e5b51da69 100644
--- a/.github/workflows/model-apps-script-tests.yml
+++ b/.github/workflows/model-apps-script-tests.yml
@@ -34,7 +34,7 @@ on:
permissions:
contents: read
-# A new push to the same PR supersedes the run in flight: without this, all seven jobs of the old run
+# A new push to the same PR supersedes the run in flight: without this, all eight jobs of the old run
# kept going to completion for a result nobody reads.
concurrency:
group: model-apps-script-tests-${{ github.event.pull_request.number || github.ref }}
@@ -131,3 +131,58 @@ jobs:
node evals/model-apps/genpage/run-layer-1.js
node evals/model-apps/genpage/run-layer-2.js
node evals/model-apps/app-builder/run-app-builder.js
+
+ # The source scanner that decides which `pageId: "PAGEREF_<key>"` literals are real navigation calls has
+ # no parser of its own, so its tests ask real parsers: a sweep puts generated pages in front of TypeScript
+ # (and Babel) and checks every token the lexer rewrites, and a differential runs the released lexer on the
+ # same valid pages to show that no page it resolved is refused now. Those tests skip themselves where the
+ # parsers are not installed — which is every job above — so a change that broke one of them would pass
+ # CI. This job installs them for the test run only, outside the plugin (which ships no dependencies), at
+ # exact versions, so a new parser release can never turn a green run red without a commit.
+ test-model-apps-lexer-oracles:
+ name: test-model-apps-lexer-oracles
+ runs-on: ubuntu-latest
+ # The sweeps and the differential take a few minutes on top of the suite.
+ timeout-minutes: 30
+ env:
+ POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: "1"
+ steps:
+ - name: checkout
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+
+ - name: setup-node
+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version: 20
+
+ # `--ignore-scripts` because neither package needs an install script, and `--prefix` under
+ # RUNNER_TEMP so that nothing lands in the plugin's tree. The version check fails the job if a
+ # range or a different package was installed, which would make the sweeps' counts mean something else.
+ - name: install-pinned-parsers
+ shell: bash
+ run: |
+ mkdir -p "$RUNNER_TEMP/parser-oracles"
+ npm install --prefix "$RUNNER_TEMP/parser-oracles" --no-save --ignore-scripts --no-audit --no-fund [email protected] @babel/[email protected]
+ test "$(node -p "require('$RUNNER_TEMP/parser-oracles/node_modules/typescript/package.json').version")" = "5.8.3"
+ test "$(node -p "require('$RUNNER_TEMP/parser-oracles/node_modules/@babel/parser/package.json').version")" = "7.29.7"
+ echo "TYPESCRIPT_ORACLE_PATH=$RUNNER_TEMP/parser-oracles/node_modules/typescript" >> "$GITHUB_ENV"
+ echo "BABEL_ORACLE_PATH=$RUNNER_TEMP/parser-oracles/node_modules/@babel/parser" >> "$GITHUB_ENV"
+
+ # The 2.13.0 release (the commit that released it), as a directory of its own: the lexer differential imports
+ # its lexer by path and compares the two on the same pages, and the data-model A/B runs its code and its SDK
+ # bundle over the same stub to show that a new table is created with the request 2.13.0 sent. The checkout is
+ # shallow, so the commit is fetched by its hash; only the plugin's scripts are extracted.
+ - name: fetch-released-scripts
+ shell: bash
+ run: |
+ git fetch --no-tags --depth=1 origin 5ef4e4f84c3c719d0db17a66e0cb349c63220639
+ mkdir -p "$RUNNER_TEMP/model-apps-2.13.0"
+ git archive FETCH_HEAD plugins/model-apps/scripts | tar -x -C "$RUNNER_TEMP/model-apps-2.13.0"
+ echo "BASE_LIB_PATH=$RUNNER_TEMP/model-apps-2.13.0/plugins/model-apps/scripts/lib" >> "$GITHUB_ENV"
+ echo "MODEL_APPS_RELEASED_SCRIPTS=$RUNNER_TEMP/model-apps-2.13.0/plugins/model-apps/scripts" >> "$GITHUB_ENV"
+
+ # The same command as the matrix job, with those paths set: the oracle and A/B tests run instead of skipping.
+ - name: run-model-apps-script-tests-with-parsers
+ shell: bash
+ working-directory: plugins/model-apps
+ run: node scripts/run-tests.js
diff --git a/evals/model-apps/app-builder/lib/facts.js b/evals/model-apps/app-builder/lib/facts.js
index af0d052de..69a9f5652 100644
--- a/evals/model-apps/app-builder/lib/facts.js
+++ b/evals/model-apps/app-builder/lib/facts.js
@@ -10,10 +10,12 @@ function pluginLib(name) { return require(path.join(__dirname, '..', '..', '..',
// helpers and performs no I/O at require time, so it is safe to load from the offline harness.
function pluginLib2(name) { return require(path.join(__dirname, '..', '..', '..', '..', 'plugins', 'model-apps', 'scripts', name)); }
-const { migrateAppSpec, validateAppSpec, lookupColumnsFor, normalizePageSource, SDK_ROLE_MARKER, FORM_TYPE_CODE } = pluginLib('app-spec.js');
+const { migrateAppSpec, validateAppSpec, lookupColumnsFor, normalizePageSource, SDK_ROLE_MARKER, FORM_TYPE_CODE, formLayoutNames, subgridRelationshipName } = pluginLib('app-spec.js');
const { lintAppSpec } = pluginLib('spec-lint.js');
const { planFor, PHASES, appDef, viewDef, chartDef, compileFormIntent, formFieldLogicals, defaultViewColumns, enrichesDefaultViews, subgridLabel, personaRoleSpecFor, businessRuleDef, bpfDef } = pluginLib('sdk-build.js');
const { subgridSectionIntent, isNonFieldControl } = pluginLib('artifact-intent.js');
+const { SUBGRID_CLASS_ID, splitSubgrids, columnItems } = pluginLib('form-subgrid-placement.js');
+const { TIMELINE_CLASS_ID, wantsTimeline } = pluginLib('form-timeline.js');
const { decodeXmlEntities } = pluginLib('sitemap-pages.js');
const { schemaFacts } = pluginLib('schema-facts.js');
const { verifySpec } = pluginLib('verify-spec.js');
@@ -435,24 +437,44 @@ function appFacts(spec) {
// and read-only / hidden state. A second derivation here drifted from it — an undeclared width rendered
// as 100% in every form-column, and no display flag at all. `columns` is emitted as the width RATIO
// string FormXML actually uses ("11" = two equal columns), not as a count.
+//
+// Two things the compiler does NOT emit are rendered here too, because verify asks the deployed form about them:
+// the Notes timeline in the shape the compiler writes (its fixed control id, the tall cell and the spacer rows
+// under it), and each sub-grid that says where it goes (`tab` / `column` / `after` / `before`), as the section the
+// build gives it, set where the spec places it. Without them a spec using either would fail verify offline on a
+// gap in this fixture, not on a finding about the spec.
function formXmlForAuthoredLayout(spec, form) {
const esc = (v) => String(v == null ? '' : v).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
const labels = (text) => `<labels><label description="${esc(text)}" languagecode="1033"/></labels>`;
const cellXml = (cell) => {
const control = cell.control || {};
const classId = control.classId && control.classId !== 'undefined' ? String(control.classId).replace(/[{}]/g, '') : '';
- return `<cell colspan="${cell.colspan || 1}" rowspan="${cell.rowspan || 1}"${cell.visible === false ? ' visible="false"' : ''}>`
- + `<control${control.fieldName ? ` datafieldname="${esc(control.fieldName)}"` : ''}${classId ? ` classid="{${esc(classId)}}"` : ''}`
- + `${control.isReadOnly ? ' disabled="true"' : ''} /></cell>`;
+ const auto = (((cell.bag && cell.bag.a) || []).find((pair) => pair[0] === 'auto') || [])[1];
+ const parameters = Object.entries(control.parameters || {});
+ return `<cell colspan="${cell.colspan || 1}" rowspan="${cell.rowspan || 1}"${cell.visible === false ? ' visible="false"' : ''}${auto === undefined ? '' : ` auto="${esc(auto)}"`}>`
+ + `<control${control.id ? ` id="${esc(control.id)}"` : ''}${control.fieldName ? ` datafieldname="${esc(control.fieldName)}"` : ''}${classId ? ` classid="{${esc(classId)}}"` : ''}`
+ + `${control.isReadOnly ? ' disabled="true"' : ''}`
+ + `${parameters.length ? `><parameters>${parameters.map(([key, value]) => `<${key}>${esc(value)}</${key}>`).join('')}</parameters></control>` : ' />'}</cell>`;
+ };
+ const sectionXml = (sec) => {
+ const width = Math.max(1, Math.min(4, Number(sec.columns) || 1));
+ const rowsXml = (sec.rows || []).map((r) => `<row>${(r.cells || []).map(cellXml).join('')}</row>`).join('');
+ return `<section name="${esc(sec.name)}" columns="${'1'.repeat(width)}" visible="${sec.visible !== false}" showlabel="${sec.showLabel !== false}">`
+ + `${labels(sec.label)}<rows>${rowsXml}</rows></section>`;
+ };
+ const layout = formLayoutNames(form);
+ const { placed } = splitSubgrids(layout, form.subgrids);
+ // A grid whose two tables have no relationship is one the build skips, so the deployed form has no section for it.
+ const gridSectionXml = (sg) => {
+ const relationshipName = subgridRelationshipName(spec, form.entity, sg.childEntity);
+ return relationshipName
+ ? sectionXml(subgridSectionIntent({ subgridClassId: SUBGRID_CLASS_ID, targetEntity: lc(sg.childEntity), relationshipName, viewId: 'v', label: subgridLabel(spec, sg) }))
+ : '';
};
- const tabsXml = (compileFormIntent(spec, form).tabs || []).map((t) => {
- const colsXml = (t.columns || []).map((col) => {
- const secsXml = (col.sections || []).map((sec) => {
- const width = Math.max(1, Math.min(4, Number(sec.columns) || 1));
- const rowsXml = (sec.rows || []).map((r) => `<row>${(r.cells || []).map(cellXml).join('')}</row>`).join('');
- return `<section name="${esc(sec.name)}" columns="${'1'.repeat(width)}" visible="${sec.visible !== false}" showlabel="${sec.showLabel !== false}">`
- + `${labels(sec.label)}<rows>${rowsXml}</rows></section>`;
- }).join('');
+ const tabsXml = (compileFormIntent(spec, form, { notesClassId: TIMELINE_CLASS_ID }).tabs || []).map((t, ti) => {
+ const colsXml = (t.columns || []).map((col, ci) => {
+ const secsXml = columnItems(layout, ti, ci, col.sections, placed)
+ .map((item) => (item.subgrid ? gridSectionXml(item.subgrid) : sectionXml(item.section))).join('');
return `<column width="${esc(col.width)}"><sections>${secsXml}</sections></column>`;
}).join('');
return `<tab name="${esc(t.name)}" expanded="${t.expanded !== false}" visible="${t.visible !== false}">${labels(t.label)}<columns>${colsXml}</columns></tab>`;
@@ -584,7 +606,10 @@ function makeAllPresentReader(spec, formEvidence = null) {
? (spec.forms || []).find((f) => isMainForm(f) && lc(f.entity) === lc(entityLogical) && mainFormName(f) === named[1])
: (spec.forms || []).find((f) => lc(f.entity) === lc(entityLogical) && Array.isArray(f.tabs) && f.tabs.length);
if (!form) return null;
- const layout = Array.isArray(form.tabs) && form.tabs.length ? formXmlForAuthoredLayout(spec, form) : '<form><tabs></tabs></form>';
+ // An auto layout declares no tabs, so it has nothing to render — unless the form asks for the Notes timeline
+ // or places a sub-grid, which verify checks on any layout.
+ const rendered = (Array.isArray(form.tabs) && form.tabs.length) || wantsTimeline(spec, form) || splitSubgrids(formLayoutNames(form), form.subgrids).placed.length > 0;
+ const layout = rendered ? formXmlForAuthoredLayout(spec, form) : '<form><tabs></tabs></form>';
return isMainForm(form) ? withOrder(layout, lc(entityLogical), form) : layout;
},
servedMainForms: async (entityLogical) => formEvidence
@@ -610,6 +635,9 @@ function requiredVerifyChecks(spec, reader) {
dashboard: (spec.dashboards || []).length,
'form-order': ordered.length,
'form-topology': (spec.forms || []).filter((f) => Array.isArray(f.tabs) && f.tabs.length).length,
+ 'form-timeline': (spec.forms || []).filter((f) => wantsTimeline(spec, f)).length,
+ 'form-subgrid': (spec.forms || []).reduce((n, f) => n + splitSubgrids(formLayoutNames(f), f.subgrids).placed
+ .filter((p) => subgridRelationshipName(spec, f.entity, p.sg.childEntity)).length, 0),
'form-order-served': typeof reader.servedMainForms === 'function' ? ordered.length : 0,
'business-rule': (spec.businessRules || []).length,
'business-process-flow': (spec.businessProcessFlows || []).length,
diff --git a/evals/model-apps/app-builder/tests/facts.test.js b/evals/model-apps/app-builder/tests/facts.test.js
index 9498d0575..bdadc4b0a 100644
--- a/evals/model-apps/app-builder/tests/facts.test.js
+++ b/evals/model-apps/app-builder/tests/facts.test.js
@@ -155,6 +155,104 @@ test('an unavailable optional served-form reader is a named skip, never a verifi
assert.strictEqual(check({ facts: broken }).status, 'fail');
});
+test('the all-present reader renders the Notes timeline and placed sub-grids, so verify proves them offline', async () => {
+ // Verify checks the timeline and a placed grid on any layout, and the reader has to answer with the form a matching
+ // environment holds — the timeline as the compiler writes it, each grid where the spec places it — or a spec that
+ // uses either fails offline on a gap in this fixture rather than on a finding about the spec.
+ const named = (schemaName, displayName, columns = []) => ({ schemaName, displayName, pluralName: `${displayName}s`, primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns });
+ const placedSpec = () => ({
+ schemaVersion: 2,
+ solution: { uniqueName: 'S', publisherPrefix: 'new' },
+ app: { name: 'T', description: '' },
+ entities: [
+ named('new_order', 'Order', [{ schemaName: 'new_status', displayName: 'Status', type: 'Text' }, { schemaName: 'new_remark', displayName: 'Remark', type: 'Memo' }]),
+ named('new_line', 'Line'),
+ named('new_part', 'Part'),
+ named('new_bin', 'Bin'),
+ ],
+ relationships: [
+ { type: 'OneToMany', referenced: 'new_order', referencing: 'new_line', lookup: { schemaName: 'new_orderid', displayName: 'Order' } },
+ { type: 'OneToMany', referenced: 'new_part', referencing: 'new_bin', lookup: { schemaName: 'new_partid', displayName: 'Part' } },
+ ],
+ forms: [
+ { entity: 'new_order', name: 'Order', notes: true, subgrids: [{ childEntity: 'new_line', after: 'sec_head' }],
+ tabs: [{ name: 'tab_main', label: 'Main', sections: [
+ { name: 'sec_head', label: 'Head', columns: 1, fields: ['new_name', 'new_status'] },
+ { name: 'sec_tail', label: 'Tail', columns: 1, fields: ['new_remark'] },
+ ] }] },
+ { entity: 'new_part', name: 'Part', notes: true, subgrids: [{ childEntity: 'new_bin', before: 'section_general' }] },
+ ],
+ appShell: { areas: [{ label: 'M', groups: [{ label: 'G', subAreas: [{ entity: 'new_order', title: 'Orders' }, { entity: 'new_part', title: 'Parts' }] }] }] },
+ });
+ const kindsOf = (facts, kind) => facts.verify.checks.filter((c) => c.kind === kind);
+
+ const placed = placedSpec();
+ const facts = await stageFacts(placed);
+ assert.strictEqual(facts.author.validate.ok, true, JSON.stringify(facts.author.validate.errors));
+ assert.strictEqual(facts.verify.ok, true, JSON.stringify(facts.verify.missing));
+ // An explicit layout and an auto layout both: the timeline and the grid are proven on each.
+ assert.strictEqual(kindsOf(facts, 'form-timeline').length, 2);
+ assert.strictEqual(kindsOf(facts, 'form-subgrid').length, 2);
+ assert.strictEqual(facts.verify.requiredChecks['form-timeline'], 2, 'the timeline check cannot silently stop running');
+ assert.strictEqual(facts.verify.requiredChecks['form-subgrid'], 2, 'the placement check cannot silently stop running');
+ const required = ASSERTIONS.get('verify: every required check kind actually ran');
+ assert.strictEqual(required({ facts }).status, 'pass');
+ const dropped = structuredClone(facts);
+ dropped.verify.checks = dropped.verify.checks.filter((c) => c.kind !== 'form-subgrid');
+ assert.strictEqual(required({ facts: dropped }).status, 'fail');
+
+ // The reader renders what the compiler writes, not a form that passes by construction: a form still carrying the
+ // timeline an older build wrote, or a grid left where it was appended, fails the same verify.
+ const stale = makeAllPresentReader(placed);
+ const render = stale.formTopology;
+ stale.formTopology = async (entity, id) => String(await render(entity, id))
+ .replace(/id="notescontrol"/g, 'id="0f0f0f0f-0000-4000-8000-000000000001"').replace(/rowspan="23"/g, 'rowspan="1"');
+ const oldTimeline = await stageFacts(placed, { verifyReader: stale });
+ assert.strictEqual(oldTimeline.verify.ok, false);
+ assert.strictEqual(kindsOf(oldTimeline, 'form-timeline').filter((c) => !c.present).length, 2);
+
+ const elsewhere = placedSpec();
+ elsewhere.forms[0].subgrids = [{ childEntity: 'new_line', after: 'sec_tail' }];
+ elsewhere.forms[1].subgrids = [{ childEntity: 'new_bin', after: 'section_general' }];
+ const moved = await stageFacts(placed, { verifyReader: makeAllPresentReader(elsewhere) });
+ assert.strictEqual(moved.verify.ok, false);
+ assert.strictEqual(kindsOf(moved, 'form-subgrid').filter((c) => !c.present).length, 2, JSON.stringify(kindsOf(moved, 'form-subgrid')));
+});
+
+test('the all-present reader keeps the Notes section the form asks for beside a layout section of the same name', async () => {
+ // A layout may declare a section named `section_notes` (a natural name for note fields) and the compiler's own Notes
+ // section carries that name too. The two are told apart by place in the column — a lookup by name would find the
+ // layout's for both and drop the compiler's whenever a grid is placed in that column, so verify would fail
+ // form-timeline offline on a gap in this fixture rather than on a finding about the spec.
+ const named = (schemaName, displayName, columns = []) => ({ schemaName, displayName, pluralName: `${displayName}s`, primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns });
+ const orderSpec = {
+ schemaVersion: 2,
+ solution: { uniqueName: 'S', publisherPrefix: 'new' },
+ app: { name: 'T', description: '' },
+ entities: [named('new_order', 'Order', [{ schemaName: 'new_remark', displayName: 'Remark', type: 'Memo' }]), named('new_line', 'Line')],
+ relationships: [{ type: 'OneToMany', referenced: 'new_order', referencing: 'new_line', lookup: { schemaName: 'new_orderid', displayName: 'Order' } }],
+ forms: [{ entity: 'new_order', name: 'Order', notes: true, subgrids: [{ childEntity: 'new_line', after: 'sec_head' }],
+ tabs: [{ name: 'tab_main', label: 'Main', sections: [
+ { name: 'sec_head', label: 'Head', columns: 1, fields: ['new_name'] },
+ { name: 'section_notes', label: 'Remarks', columns: 1, fields: ['new_remark'] },
+ ] }] }],
+ appShell: { areas: [{ label: 'M', groups: [{ label: 'G', subAreas: [{ entity: 'new_order', title: 'Orders' }] }] }] },
+ };
+ const facts = await stageFacts(orderSpec);
+ assert.strictEqual(facts.author.validate.ok, true, JSON.stringify(facts.author.validate.errors));
+ const timeline = facts.verify.checks.filter((c) => c.kind === 'form-timeline');
+ assert.deepStrictEqual(timeline.map((c) => c.present), [true], JSON.stringify(timeline));
+ assert.deepStrictEqual(facts.verify.checks.filter((c) => c.kind === 'form-subgrid').map((c) => c.present), [true]);
+ assert.strictEqual(facts.verify.ok, true, JSON.stringify(facts.verify.missing));
+
+ // The reader's form holds BOTH sections: the layout's, with its field, and the compiler's, with the timeline.
+ const xml = String(await makeAllPresentReader(orderSpec).formTopology('new_order', 'Order'));
+ const sections = xml.match(/<section\b[\s\S]*?<\/section>/g).filter((s) => /name="section_notes"/.test(s));
+ assert.strictEqual(sections.length, 2);
+ assert.ok(sections[0].includes('datafieldname="new_remark"') && !sections[0].includes('notescontrol'), 'the layout\u2019s section first');
+ assert.ok(sections[1].includes('id="notescontrol"') && !sections[1].includes('datafieldname'), 'then the Notes section the compiler adds');
+});
+
test('stageFacts.teardown plans a reverse-of-build delete ending at the solution, web resources after tables', async () => {
const f = await stageFacts(spec);
const kinds = f.teardown.kinds;
diff --git a/evals/model-apps/genpage/EVAL_GUIDE.md b/evals/model-apps/genpage/EVAL_GUIDE.md
index 39e1d3901..294e9c758 100644
--- a/evals/model-apps/genpage/EVAL_GUIDE.md
+++ b/evals/model-apps/genpage/EVAL_GUIDE.md
@@ -76,7 +76,7 @@ Layers 1 and 2 are automated. Layer 3 is human judgment by design — visual qua
- A divergence refusal (`no-base`, `deployed-changed`, `deployed-unreadable`) stops an update before PAC writes (`ok: false`, no PAC write, no forwarded args). `--overwrite-deployed` needs the `Choice:` line that upload command consumes to be exactly `Choice: Overwrite the deployed changes`. Each `genpage-upload.js` line consumes the pending choice, so one approval does not cover a later upload
- Custom API discovery/gates/bindings/runtime/update stages agree; optional packaging names every deployed page and preserves failures/read-back evidence
- Prefix discipline holds across plan, entity-creation log, and resolved names
-- Per-eval discovery, provisioning, schema and deployment expectations compare structured evidence read by `lib/expectation-evidence.js` — `list-tables`/`list-languages`/`generate-types`/upload flags and their recorded results, the plan's entity blocks, the entity-creation transactions, and the choice enums in the captured `RuntimeTypes.ts` — on either upload transport
+- Per-eval discovery, provisioning, schema and deployment expectations compare structured evidence read by `lib/expectation-evidence.js` — `list-tables`/`list-languages`/`generate-types`/upload flags and their recorded results (language discovery is `scripts/list-languages.js`, whose JSON `languages` are the evidence and whose failed read is none, or `pac model list-languages`, which the planner runs when the script cannot read the languages and which captures made before the script record; both are read), the plan's entity blocks, the entity-creation transactions, and the choice enums in the captured `RuntimeTypes.ts` — on either upload transport
**Runner:** `evals/model-apps/genpage/run-layer-1.js`
**Library:** `lib/assertions-layer-1.js` (one check function per assertion text)
diff --git a/evals/model-apps/genpage/evals.json b/evals/model-apps/genpage/evals.json
index cc99a1d6b..c797398b7 100644
--- a/evals/model-apps/genpage/evals.json
+++ b/evals/model-apps/genpage/evals.json
@@ -357,10 +357,10 @@
"specific_requirements": "Contact list display"
},
"app_selection": "user selects an existing app",
- "environment_state": "pac model list-languages returns multiple languages: English (1033), Arabic (1025), French (1036). This eval exercises the localization code path."
+ "environment_state": "The environment has English (1033), Arabic (1025) and French (1036) provisioned, which scripts/list-languages.js reports (or pac model list-languages, which the planner runs when that script cannot read them). This eval exercises the localization code path."
},
"expectations": [
- "Phase 1 (Planner): pac model list-languages output includes Arabic (1025) and French (1036) in addition to English",
+ "Phase 1 (Planner): language discovery output includes Arabic (1025) and French (1036) in addition to English",
"Phase 1 (Planner): Plan includes a Localization section listing detected languages",
"Phase 5 (Page Builder): Generated .tsx includes language detection boilerplate using Xrm.Utility.getGlobalContext().userSettings.languageId",
"Phase 5 (Page Builder): Generated .tsx has a translations dictionary with entries for en-US, ar-SA, and fr-FR",
diff --git a/evals/model-apps/genpage/fixtures/13-contact-localization/genpage-plan.md b/evals/model-apps/genpage/fixtures/13-contact-localization/genpage-plan.md
index 11dd6506a..f54c4a773 100644
--- a/evals/model-apps/genpage/fixtures/13-contact-localization/genpage-plan.md
+++ b/evals/model-apps/genpage/fixtures/13-contact-localization/genpage-plan.md
@@ -41,7 +41,7 @@ No connector bindings.
## Localization
-- Detected languages (from `pac model list-languages`):
+- Detected languages (from `scripts/list-languages.js`):
- English (United States) (1033, en-US)
- Arabic (Saudi Arabia) (1025, ar-SA) — RTL
- French (France) (1036, fr-FR)
diff --git a/evals/model-apps/genpage/fixtures/13-contact-localization/workflow-log.md b/evals/model-apps/genpage/fixtures/13-contact-localization/workflow-log.md
index b800dbe5c..44b0de7fb 100644
--- a/evals/model-apps/genpage/fixtures/13-contact-localization/workflow-log.md
+++ b/evals/model-apps/genpage/fixtures/13-contact-localization/workflow-log.md
@@ -18,7 +18,8 @@
- `pac model list-tables --search 'contact'` — contact entity exists
### Language discovery
-- `pac model list-languages` returned: English (United States) (1033, en-US), Arabic (Saudi Arabia) (1025, ar-SA), French (France) (1036, fr-FR)
+- `node "${PLUGIN_ROOT}/scripts/list-languages.js" --env 'https://contosobapenv0002.crm10.dynamics.com'`
+ Result: {"ok":true,"baseLanguage":{"lcid":1033,"code":"en-US","name":"English (United States)","rtl":false},"languages":[{"lcid":1033,"code":"en-US","name":"English (United States)","rtl":false},{"lcid":1025,"code":"ar-SA","name":"Arabic (Saudi Arabia)","rtl":true},{"lcid":1036,"code":"fr-FR","name":"French (France)","rtl":false}],"unmapped":[],"summary":["1033 en-US \u2014 RTL: No","1025 ar-SA \u2014 RTL: Yes","1036 fr-FR \u2014 RTL: No"]}
- Multiple non-English languages detected → planner activates localization code path
- Arabic detected as RTL language
diff --git a/evals/model-apps/genpage/lib/assertions-layer-1.js b/evals/model-apps/genpage/lib/assertions-layer-1.js
index 94e33e4e4..33dfccba7 100644
--- a/evals/model-apps/genpage/lib/assertions-layer-1.js
+++ b/evals/model-apps/genpage/lib/assertions-layer-1.js
@@ -2186,24 +2186,42 @@ PHASE_EXPECTATIONS.set(
// --- Eval 13 -----------------------------------------------------------------------------------
-// LCIDs in the recorded `pac model list-languages` output. Two shapes are captured:
-// 1033 English (United States) en-US No (the PAC table)
+// LCIDs in the recorded language-discovery output. Four shapes are captured:
+// {"ok":true,"baseLanguage":{…},"languages":[{"lcid":1033,"code":"en-US",…},…],…} (scripts/list-languages.js)
+// {"ok":false,"error":"…","code":"CONNECTION_ERROR"} (the same script failing — the planner then runs the next shape)
+// 1033 English (United States) en-US No (the PAC table: a capture made before that script, or the fallback after it)
// English (United States) (1033, en-US), Arabic (Saudi Arabia) (1025, ar-SA) (a summary)
-// An LCID counts only next to a language tag, so a version or row count never does.
+// A result that parses as the script's own JSON is read as data and as nothing else. Its `languages` are the
+// PROVISIONED languages — `baseLanguage`, `unmapped` and `summary` are not extra evidence — and a failure found nothing,
+// whatever its error text says: only the fallback after it can. A contract-2 event's result always parses, and so
+// does a log's `Result: {…}` line. Falling through to the text shapes for such a result would read an LCID out of the
+// JSON's own punctuation (`"unmapped":[1036],"summary":["1033 en-US …`) and out of an error message. In the text
+// shapes an LCID counts only next to a language tag, so a version or row count never does.
+const isLanguagesResult = (result) => Boolean(result)
+ && ((result.ok === true && Array.isArray(result.languages)) || (result.ok === false && typeof result.error === 'string'));
+
function detectedLanguages(fixture) {
const calls = commandCalls(fixture, LIST_LANGUAGES);
if (!calls.length) return null;
- const text = calls.map((c) => c.text).join('\n');
- return [...new Set([...text.matchAll(/\b(\d{4,5})\b[^\n]{0,60}?\b[a-z]{2,3}-[A-Z]{2,4}\b/g)].map((m) => Number(m[1])))];
+ const found = new Set();
+ for (const { call, text } of calls) {
+ const result = resultObject(call);
+ if (isLanguagesResult(result)) {
+ if (result.ok) for (const language of result.languages) if (Number.isInteger(language?.lcid)) found.add(language.lcid);
+ continue;
+ }
+ for (const m of text.matchAll(/\b(\d{4,5})\b[^\n]{0,60}?\b[a-z]{2,3}-[A-Z]{2,4}\b/g)) found.add(Number(m[1]));
+ }
+ return [...found];
}
PHASE_EXPECTATIONS.set(
- 'Phase 1 (Planner): pac model list-languages output includes Arabic (1025) and French (1036) in addition to English',
+ 'Phase 1 (Planner): language discovery output includes Arabic (1025) and French (1036) in addition to English',
({ fixture }) => {
const lcids = detectedLanguages(fixture);
- if (lcids === null) return fail('pac model list-languages was not run');
+ if (lcids === null) return fail('language discovery was not run (scripts/list-languages.js, or pac model list-languages as its fallback)');
const missing = [1033, 1025, 1036].filter((id) => !lcids.includes(id));
- return missing.length ? fail(`recorded list-languages output lacks LCID ${missing.join(', ')} (saw ${listText(lcids)})`) : pass();
+ return missing.length ? fail(`recorded language-discovery output lacks LCID ${missing.join(', ')} (saw ${listText(lcids)})`) : pass();
}
);
@@ -2212,7 +2230,10 @@ PHASE_EXPECTATIONS.set(
({ fixture }) => {
if (!fixture.genpagePlan) return fail('no genpage-plan.md');
const lcids = detectedLanguages(fixture);
- if (lcids === null) return fail('pac model list-languages was not run, so no languages were detected');
+ if (lcids === null) return fail('language discovery was not run, so no languages were detected');
+ // A script that failed and no fallback after it: the discovery ran and read nothing, so a Localization section has
+ // no detected language to be listing — it would otherwise pass for want of anything to compare.
+ if (lcids.length === 0) return fail('language discovery detected no languages (a failed read with no pac fallback after it), so the plan has none to list');
const section = headingSection(fixture.genpagePlan, /^#{2,3}\s+Localization\s*$/i);
if (section === null) return fail('plan has no Localization section');
const missing = lcids.filter((id) => !new RegExp(`\\b${id}\\b`).test(section));
diff --git a/evals/model-apps/genpage/lib/expectation-evidence.js b/evals/model-apps/genpage/lib/expectation-evidence.js
index 52e653dae..7ad5f1086 100644
--- a/evals/model-apps/genpage/lib/expectation-evidence.js
+++ b/evals/model-apps/genpage/lib/expectation-evidence.js
@@ -17,7 +17,10 @@ const { planSection, parseMarkdownRows } = require('./plan-evidence.js');
const PAC = String.raw`\bpac(?:\.exe|\.cmd)?\s+model\s+`;
const LIST_TABLES = new RegExp(`${PAC}list-tables\\b`);
-const LIST_LANGUAGES = new RegExp(`${PAC}list-languages\\b`);
+// Language discovery is the plugin's own `scripts/list-languages.js` or `pac model list-languages` — the command the
+// captures made before that script record, and the one the planner runs when the script cannot read the languages — so
+// either spelling is the planner having looked.
+const LIST_LANGUAGES = new RegExp(`${PAC}list-languages\\b|\\blist-languages\\.js\\b`);
const GENERATE_TYPES = new RegExp(`${PAC}genpage\\s+generate-types\\b`);
const GENPAGE_LIST = new RegExp(`${PAC}genpage\\s+list\\b`);
const PROVISION = /\bprovision-entities\.js\b/;
diff --git a/evals/model-apps/genpage/tests/phase-expectations.test.js b/evals/model-apps/genpage/tests/phase-expectations.test.js
index 14b95ff13..e1d073a32 100644
--- a/evals/model-apps/genpage/tests/phase-expectations.test.js
+++ b/evals/model-apps/genpage/tests/phase-expectations.test.js
@@ -434,19 +434,99 @@ test('eval 11: the Phase 8 summary lists every page with its deployed entities a
// --- Eval 13 -----------------------------------------------------------------------------------
-test('eval 13: list-languages output and the plan Localization section carry every detected LCID', () => {
- const output = 'Phase 1 (Planner): pac model list-languages output includes Arabic (1025) and French (1036) in addition to English';
- const section = 'Phase 1 (Planner): Plan includes a Localization section listing detected languages';
- assertPass(grade(output, committed('13-contact-localization')));
- assertPass(grade(section, committed('13-contact-localization')));
- assertFail(grade(output, mutated('13-contact-localization', 'workflowLog', ', French (France) (1036, fr-FR)', '')), /lacks LCID 1036/);
- // The PAC table shape is read too.
- const table = mutated('13-contact-localization', 'workflowLog', /- `pac model list-languages`[^\n]*/.exec(committed('13-contact-localization').workflowLog)[0],
- '`pac model list-languages`\nLCID Language Code RTL\n1033 English (United States) en-US No\n1025 Arabic (Saudi Arabia) ar-SA Yes\n1036 French (France) fr-FR No');
- assertPass(grade(output, table));
- assertFail(grade(section, mutated('13-contact-localization', 'genpagePlan', '## Localization', '## Notes')), /no Localization section/);
- assertFail(grade(section, mutated('13-contact-localization', 'genpagePlan', '(1036, fr-FR)', '(fr-FR)')), /does not list detected LCID 1036/);
- assertFail(grade(section, mutated('13-contact-localization', 'workflowLog', 'pac model list-languages', 'language discovery')), /list-languages was not run/);
+const E13 = '13-contact-localization';
+const LANGUAGES_OUTPUT = 'Phase 1 (Planner): language discovery output includes Arabic (1025) and French (1036) in addition to English';
+const LANGUAGES_SECTION = 'Phase 1 (Planner): Plan includes a Localization section listing detected languages';
+// The committed capture records scripts/list-languages.js and its JSON line — the command and its `Result:` — whose
+// `languages` are read as data.
+const scriptCall = () => /- `node "\$\{PLUGIN_ROOT\}\/scripts\/list-languages\.js"[^\n]*\n[^\n]*/.exec(committed(E13).workflowLog)[0];
+const FRENCH = ',{"lcid":1036,"code":"fr-FR","name":"French (France)","rtl":false}';
+// The same capture, edited as text, one replacement after another.
+const withLog = (...replacements) => replacements.reduce((fixture, [from, to]) => ({ ...fixture, workflowLog: edit(fixture.workflowLog, from, to) }), committed(E13));
+
+// What the script prints when it cannot read the languages (a missing Azure CLI), as the real script prints it, for the
+// environment the capture's own command names.
+const originOf13 = () => /--env '([^']+)'/.exec(scriptCall())[1];
+const failedRead = () => `{"ok":false,"error":"Transport failure reaching ${originOf13()}/api/data/v9.0/organizations?$select=languagecode: Could not get an Azure CLI token for ${originOf13()}: Azure CLI (\`az\`) is not on PATH. Install it from https://aka.ms/azure-cli and run \`az login\`.","code":"CONNECTION_ERROR"}`;
+// What `pac model list-languages` prints for the same environment.
+const PAC_ROWS = ['1033 English (United States) en-US No', '1025 Arabic (Saudi Arabia) ar-SA Yes', '1036 French (France) fr-FR No'];
+const pacTable = (rows = PAC_ROWS) => `\`pac model list-languages\`\nLCID Language Code RTL\n${rows.join('\n')}`;
+// The planner pins the fallback to the environment the script was given (`--environment '<envUrl>'`); to the grader that is the same command.
+const pinnedPacTable = (rows) => pacTable(rows).replace('`pac model list-languages`', `\`pac model list-languages --environment '${originOf13()}'\``);
+// The log of a run whose script failed, the way the planner records it: the script's command and result, then the
+// `pac` command and its table, each verbatim (agents/genpage-planner.md, "Detect Configured Languages").
+const failedScriptLog = () => `${scriptCall().split('\n')[0]}\n Result: ${failedRead()}`;
+const fellBackLog = ({ note = '', rows } = {}) => `${failedScriptLog()}\n${note}- ${pacTable(rows)}`;
+const SAID = '- Language detection used `pac model list-languages`: the languages script exited 1 (the Azure CLI is not on PATH)\n';
+
+test('eval 13: language-discovery output and the plan Localization section carry every detected LCID', () => {
+ assertPass(grade(LANGUAGES_OUTPUT, committed(E13)));
+ assertPass(grade(LANGUAGES_SECTION, committed(E13)));
+ assertFail(grade(LANGUAGES_OUTPUT, withLog([FRENCH, ''])), /lacks LCID 1036/);
+ // A language the script could not name is still a detected one — written the way the script writes it: the LCID stays,
+ // its code is null, it is listed in `unmapped` and its summary line says unknown.
+ const unnamed = withLog(
+ [FRENCH, ',{"lcid":1036,"code":null,"name":null,"rtl":null}'],
+ ['"unmapped":[]', '"unmapped":[1036]'],
+ ['"1036 fr-FR \\u2014 RTL: No"', '"1036 unknown \\u2014 RTL: unknown"']
+ );
+ assertPass(grade(LANGUAGES_OUTPUT, unnamed));
+ // The PAC table of a capture made before that script is read too.
+ assertPass(grade(LANGUAGES_OUTPUT, mutated(E13, 'workflowLog', scriptCall(), pacTable())));
+ assertFail(grade(LANGUAGES_SECTION, mutated(E13, 'genpagePlan', '## Localization', '## Notes')), /no Localization section/);
+ assertFail(grade(LANGUAGES_SECTION, mutated(E13, 'genpagePlan', '(1036, fr-FR)', '(fr-FR)')), /does not list detected LCID 1036/);
+ assertFail(grade(LANGUAGES_SECTION, mutated(E13, 'workflowLog', '/scripts/list-languages.js', '/scripts/language-discovery.js')), /language discovery was not run/);
+});
+
+test('eval 13: a result that parses as the script\u2019s own JSON is read as data and as nothing else', () => {
+ // Only `languages` — the PROVISIONED ones — count. Read as text, the JSON would give up LCIDs it merely mentions: the
+ // base language, a `summary` line, and any number within sixty characters of a language tag.
+ const notProvisioned = [FRENCH, ''];
+ assertFail(grade(LANGUAGES_OUTPUT, withLog(notProvisioned, ['"baseLanguage":{"lcid":1033,"code":"en-US"', '"baseLanguage":{"lcid":1036,"code":"fr-FR"'])), /lacks LCID 1036/);
+ assertFail(grade(LANGUAGES_OUTPUT, withLog(notProvisioned)), /lacks LCID 1036/);
+ assertFail(grade(LANGUAGES_OUTPUT, withLog(notProvisioned, ['"unmapped":[]', '"unmapped":[1036]'], ['"1036 fr-FR \\u2014 RTL: No"', '"1036 unknown \\u2014 RTL: unknown"'])), /lacks LCID 1036/);
+ // A failed read detected nothing, whatever its error text says — even text that names languages.
+ const error = '{"ok":false,"error":"HTTP 403 from https://contoso.crm.dynamics.com/api/data/v9.0/RetrieveProvisionedLanguages(): 1033 en-US, 1025 ar-SA and 1036 fr-FR cannot be read by this user","code":"CONNECTION_ERROR"}';
+ assertFail(grade(LANGUAGES_OUTPUT, mutated(E13, 'workflowLog', /Result: \{"ok":true[^\n]*/.exec(committed(E13).workflowLog)[0], `Result: ${error}`)), /saw none/);
+ // A `Result:` that is not the script's shape (an abbreviation) is not decisive: the text around it still is read.
+ assertPass(grade(LANGUAGES_OUTPUT, mutated(E13, 'workflowLog', /Result: \{"ok":true[^\n]*/.exec(committed(E13).workflowLog)[0], 'Result: { ok: true, ... }\n English (United States) (1033, en-US), Arabic (Saudi Arabia) (1025, ar-SA), French (France) (1036, fr-FR)')));
+});
+
+test('eval 13: when the script could not read the languages, the pac fallback after it is what detected them', () => {
+ // The planner falls back to `pac model list-languages` on any non-zero exit of the script and records both. The
+ // failed call found nothing, the fallback found all three, and the plan lists them.
+ const fellBack = mutated(E13, 'workflowLog', scriptCall(), fellBackLog());
+ assertPass(grade(LANGUAGES_OUTPUT, fellBack));
+ assertPass(grade(LANGUAGES_SECTION, fellBack));
+ // Saying so in a line of its own changes nothing.
+ const said = mutated(E13, 'workflowLog', scriptCall(), fellBackLog({ note: SAID }));
+ assertPass(grade(LANGUAGES_OUTPUT, said));
+ assertPass(grade(LANGUAGES_SECTION, said));
+ // The fallback as the planner runs it, pinned to the script's environment, is the same command to the grader — and its table is read the same way.
+ const pinned = mutated(E13, 'workflowLog', scriptCall(), `${failedScriptLog()}\n- ${pinnedPacTable()}`);
+ assertPass(grade(LANGUAGES_OUTPUT, pinned));
+ assertPass(grade(LANGUAGES_SECTION, pinned));
+ assertFail(grade(LANGUAGES_OUTPUT, mutated(E13, 'workflowLog', scriptCall(), `${failedScriptLog()}\n- ${pinnedPacTable(PAC_ROWS.slice(0, 2))}`)), /lacks LCID 1036/);
+ // A run that stopped at the failed script detected nothing: it is credited with no language it never read, and a
+ // plan that lists languages has none to be listing.
+ const stopped = mutated(E13, 'workflowLog', scriptCall(), failedScriptLog());
+ assertFail(grade(LANGUAGES_OUTPUT, stopped), /lacks LCID 1033, 1025, 1036 \(saw none\)/);
+ assertFail(grade(LANGUAGES_SECTION, stopped), /detected no languages/);
+ // A fallback that read fewer languages than the plan lists is caught the same way as a script that did.
+ assertFail(grade(LANGUAGES_OUTPUT, mutated(E13, 'workflowLog', scriptCall(), fellBackLog({ rows: PAC_ROWS.slice(0, 2) }))), /lacks LCID 1036/);
+});
+
+test('eval 13: the whole fixture still grades clean when its language discovery is the pac fallback', () => {
+ // Every common assertion and the eval's own expectations, as run-layer-1.js grades a fixture — not one check alone.
+ const fs = require('node:fs');
+ const { gradeFixture } = require('../run-layer-1.js');
+ const evalsData = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'evals.json'), 'utf8'));
+ const ev = evalsData.evals.find((e) => e.id === committed(E13).id);
+ const failures = (fixture) => gradeFixture(fixture, ev, evalsData).filter((r) => r.result.status === 'fail').map((r) => `${r.text}: ${r.result.reason}`);
+ assert.deepEqual(failures(committed(E13)), []);
+ assert.deepEqual(failures(mutated(E13, 'workflowLog', scriptCall(), fellBackLog())), []);
+ assert.deepEqual(failures(mutated(E13, 'workflowLog', scriptCall(), fellBackLog({ note: SAID }))), []);
+ assert.deepEqual(failures(mutated(E13, 'workflowLog', scriptCall(), `${failedScriptLog()}\n- ${pinnedPacTable()}`)), []);
});
test('eval 13: generated text carries no hardcoded currency symbols or date formats', () => {
diff --git a/evals/model-apps/genpage/tests/refusal-replay.test.js b/evals/model-apps/genpage/tests/refusal-replay.test.js
index 2a3abb9b5..913ea6b08 100644
--- a/evals/model-apps/genpage/tests/refusal-replay.test.js
+++ b/evals/model-apps/genpage/tests/refusal-replay.test.js
@@ -50,8 +50,11 @@ test('discovery distinguishes unreadable output from a genuine empty success and
events: [{ command: 'node list-connections.js https://contoso.crm.dynamics.com', rawOutput, result, userMessage: result.error }],
});
const empty = { ok: true, connections: [], connectionReferences: [] };
- assert.deepEqual(discoveryProblems(make('No connections found.\n', empty)), []);
- for (const raw of ['Warning: failed to retrieve connector metadata.\n', '----- -----\n', 'Unsupported header\n']) {
+ // `pac connection list` says an environment has no connections by printing the grid's header with no rows under it — one space between the names, because each column is as wide as its
+ // widest cell plus one space and there is no cell. That is a genuine empty success. No sentence is: PAC's `ConnectionNotFound` resource string is not printed by the command, and the other
+ // wording is one this module used to guess.
+ assert.deepEqual(discoveryProblems(make('Connected as [maker001]\r\nId Name API Id Status\r\n\r\n', empty)), []);
+ for (const raw of ['No connections were found in the passed environment.\n', 'No connections found.\n', 'Warning: failed to retrieve connector metadata.\n', '----- -----\n', 'Unsupported header\n']) {
assert.ok(discoveryProblems(make(raw, empty)).length, raw);
}
const connectorId = '/providers/Microsoft.PowerApps/apis/shared_sharepointonline';
diff --git a/evals/model-apps/routing/run-routing.js b/evals/model-apps/routing/run-routing.js
index 994b59932..d6beef600 100644
--- a/evals/model-apps/routing/run-routing.js
+++ b/evals/model-apps/routing/run-routing.js
@@ -214,8 +214,16 @@ function copilotSkillInventory({ bin, binArgs = [], pluginDir, env, cwd }) {
* 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:
+ * `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.
*/
-function spawnTrial({ bin, binArgs = [], args, env, prompt, cwd, timeoutMs, plugin, agent, loadedSkills = null, loadError = null }) {
+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 }) {
return new Promise((resolve) => {
const started = Date.now();
const parser = new TranscriptParser(agent, plugin);
@@ -246,7 +254,7 @@ function spawnTrial({ bin, binArgs = [], args, env, prompt, cwd, timeoutMs, plug
const finish = (extra = {}) => {
if (settled) return;
settled = true;
- clearTimeout(timer);
+ clock.clearTimeout(timer);
killTree(child);
let error = extra.error || null;
// "none" is a DECISION only when the run ended on its own without choosing a plugin skill.
@@ -285,7 +293,8 @@ function spawnTrial({ bin, binArgs = [], args, env, prompt, cwd, timeoutMs, plug
stdout,
});
};
- const timer = setTimeout(() => { timedOut = true; finish(); }, timeoutMs);
+ const timer = clock.setTimeout(() => { timedOut = true; finish(); }, timeoutMs);
+ if (onStart) onStart({ child, parser });
child.stdout.on('data', (chunk) => {
const s = chunk.toString('utf8');
stdout += s;
diff --git a/evals/model-apps/routing/tests/fake-agent.js b/evals/model-apps/routing/tests/fake-agent.js
index 054056b77..d58c33a2d 100644
--- a/evals/model-apps/routing/tests/fake-agent.js
+++ b/evals/model-apps/routing/tests/fake-agent.js
@@ -12,6 +12,11 @@
// copilot-answer Copilot-format successful text answer (exitCode 0), no skill call
// FAKE_AGENT_EXIT sets the process exit code for the *-failed modes (default 1), so a test can
// prove the failed RESULT alone is caught even when the process exits 0.
+// FAKE_AGENT_READY_FILE names a file `hang` writes once it has read the prompt and gone silent, so a
+// test can wait until the agent is really running before it ends the run, instead of guessing how
+// long a loaded machine takes to start Node.
+// FAKE_AGENT_START_DELAY_MS makes the agent sit idle that long before it reads the prompt — a machine
+// so loaded that Node needs seconds to get going, which a fixed test timeout must not be raced against.
const mode = process.env.FAKE_AGENT_MODE;
const out = (o) => process.stdout.write(`${JSON.stringify(o)}\n`);
const skills = ['model-apps:app-builder', 'model-apps:genpage', 'model-apps:report-issue', 'model-apps:telemetry'];
@@ -36,13 +41,19 @@ if (argv.includes('skill') && argv.includes('list')) {
}
let prompt = '';
+const startDelay = Number(process.env.FAKE_AGENT_START_DELAY_MS || 0);
+if (startDelay > 0) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, startDelay);
process.stdin.on('data', (c) => { prompt += c; });
process.stdin.on('end', () => {
if (mode === 'crash') {
process.stderr.write('Error: not signed in\n');
process.exit(3);
}
- if (mode === 'hang') { setInterval(() => {}, 1000); return; }
+ if (mode === 'hang') {
+ if (process.env.FAKE_AGENT_READY_FILE) require('node:fs').writeFileSync(process.env.FAKE_AGENT_READY_FILE, String(process.pid));
+ setInterval(() => {}, 1000);
+ return;
+ }
const failExit = Number(process.env.FAKE_AGENT_EXIT || 1);
if (mode === 'copilot-failed') {
out({ type: 'user.message', data: { content: prompt.trim() } });
diff --git a/evals/model-apps/routing/tests/run-routing.test.js b/evals/model-apps/routing/tests/run-routing.test.js
index f12f7815d..f098bd2a7 100644
--- a/evals/model-apps/routing/tests/run-routing.test.js
+++ b/evals/model-apps/routing/tests/run-routing.test.js
@@ -155,12 +155,66 @@ test('CLI --dry-run prints the isolated invocation and launches nothing', () =>
// ---------- spawnTrial against a fake agent (real process plumbing) ----------
-function fakeTrial(mode, { prompt = 'build me a page', timeoutMs = 20000, agent = 'claude', env = {}, loadedSkills, loadError } = {}) {
+const { setTimeout: sleep } = require('node:timers/promises');
+
+// How long a test waits for something that WILL happen: the fake agent to start, a killed process
+// to let go of its directory. The wait ends the moment the thing happens, so the bound adds no time
+// to a passing run — it turns a real hang into a failure that names what never happened.
+const WAIT_LIMIT_MS = 60000;
+
+async function until(condition, what) {
+ const deadline = Date.now() + WAIT_LIMIT_MS;
+ while (!condition()) {
+ if (Date.now() > deadline) assert.fail(`${what} did not happen within ${WAIT_LIMIT_MS}ms`);
+ await sleep(10);
+ }
+}
+
+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.
+async function removeWhenFree(dir) {
+ const deadline = Date.now() + WAIT_LIMIT_MS;
+ for (;;) {
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ return;
+ } catch (e) {
+ if (!['EBUSY', 'EPERM', 'ENOTEMPTY'].includes(e.code) || Date.now() > deadline) throw e;
+ await sleep(50);
+ }
+ }
+}
+
+// The deadline of a trial, in the test's hands: spawnTrial arms it with the configured `timeoutMs`, and
+// `fire()` is the moment that time would have passed. A real timer raced the agent's start-up — a timeout
+// "after output" needs the output first, and Node can take longer than any fixed timeout to print it.
+function manualClock() {
+ const clock = {
+ callback: null,
+ armedFor: null,
+ setTimeout(callback, ms) { clock.callback = callback; clock.armedFor = ms; return clock; },
+ clearTimeout() { clock.callback = null; },
+ get armed() { return clock.callback !== null; },
+ fire() {
+ const callback = clock.callback;
+ assert.ok(callback, 'the deadline is armed');
+ clock.callback = null;
+ callback();
+ },
+ };
+ return clock;
+}
+
+function fakeTrial(mode, { prompt = 'build me a page', timeoutMs = 20000, agent = 'claude', env = {}, loadedSkills, loadError, clock, onStart } = {}) {
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'routing-fake-'));
return spawnTrial({
agent, bin: process.execPath, binArgs: [FAKE], args: [], env: { FAKE_AGENT_MODE: mode, ...env },
- prompt, cwd, timeoutMs, plugin: PLUGIN, loadedSkills, loadError,
- }).finally(() => fs.rmSync(cwd, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
+ prompt, cwd, timeoutMs, plugin: PLUGIN, loadedSkills, loadError, clock, onStart,
+ }).finally(() => removeWhenFree(cwd));
}
test('spawnTrial: a FAILED terminal result is an error, never a "none" decision (both CLIs, any exit code)', async () => {
@@ -180,11 +234,17 @@ test('spawnTrial: a FAILED terminal result is an error, never a "none" decision
});
test('spawnTrial: prompt reaches the agent on stdin; a routed agent is killed at the decision', async () => {
- const t = await fakeTrial('route-then-hang', { prompt: 'make me an app' });
+ // The deadline is never fired here, so only the decision can end the run — however long this machine
+ // takes to start the agent. (A wall-clock bound on `durationMs` failed a slow run for being slow.)
+ const clock = manualClock();
+ let child;
+ const t = await fakeTrial('route-then-hang', { prompt: 'make me an app', clock, onStart: (s) => { child = s.child; } });
assert.equal(t.routedTo, 'app-builder', 'the fake routes on the prompt text, proving stdin delivery');
assert.equal(t.error, null);
assert.equal(t.timedOut, false);
- assert.ok(t.durationMs < 15000, `should stop at the decision, took ${t.durationMs}ms`);
+ assert.equal(clock.armed, false, 'the decision disarmed the deadline instead of leaving it running');
+ // `route-then-hang` never exits on its own, so it has gone only because the harness killed it.
+ await until(() => hasExited(child), 'the routed agent being killed');
});
test('spawnTrial: a text answer ends the run as a "none" decision', async () => {
@@ -206,20 +266,79 @@ test('spawnTrial: the plugin missing from the init skill list is an error, not a
test('spawnTrial: a silent agent is killed at the timeout and reported as an error, not a "none"', async () => {
// Graded as `none`, a hung CLI would pass every negative case — a harness failure must read
- // as a harness failure.
- const t = await fakeTrial('hang', { timeoutMs: 1500 });
- assert.equal(t.timedOut, true);
- assert.equal(t.routedTo, null);
- assert.match(t.error, /timed out with no transcript output/);
+ // as a harness failure. The deadline is fired by the test once the agent is really running and silent
+ // (it wrote its ready file), so nothing here depends on how long this machine takes to start Node.
+ const clock = manualClock();
+ const ready = path.join(os.tmpdir(), `routing-ready-${process.pid}-${Date.now()}`);
+ let child;
+ const trial = fakeTrial('hang', { timeoutMs: 1500, clock, env: { FAKE_AGENT_READY_FILE: ready }, onStart: (s) => { child = s.child; } });
+ try {
+ await until(() => fs.existsSync(ready), 'the silent agent starting');
+ assert.equal(clock.armedFor, 1500, 'the deadline is armed with the configured timeout');
+ clock.fire();
+ const t = await trial;
+ assert.equal(t.timedOut, true);
+ assert.equal(t.routedTo, null);
+ assert.match(t.error, /timed out with no transcript output/);
+ // `hang` never exits on its own, so it has gone only because the harness killed it at the deadline.
+ await until(() => hasExited(child), 'the silent agent being killed');
+ } finally {
+ // An assertion above must not leave a running agent holding the test process open.
+ if (clock.armed) clock.fire();
+ await trial.catch(() => {});
+ fs.rmSync(ready, { force: true });
+ }
});
test('spawnTrial: a timeout AFTER transcript output is still an error, never a "none" decision', async () => {
// The gap a silent-agent test alone misses: Claude always streams an init event (and Copilot
// message deltas) before deciding, so "any output" must not turn a cut-off run into "none".
- const t = await fakeTrial('init-then-hang', { timeoutMs: 1500 });
+ // The deadline is fired only after the parser has read the init event, so the event always comes
+ // BEFORE the timeout: a fixed 1.5 s timeout raced the agent's start-up and read "no transcript output"
+ // whenever Node took longer than that to print its first line.
+ const clock = manualClock();
+ let parser;
+ let child;
+ const trial = fakeTrial('init-then-hang', { timeoutMs: 1500, clock, onStart: (s) => { parser = s.parser; child = s.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.equal(t.routedTo, null);
+ assert.match(t.error, /timed out before routing \(1 transcript events, no decision\)/);
+ await until(() => hasExited(child), 'the cut-off agent being killed');
+ } finally {
+ if (clock.armed) clock.fire();
+ await trial.catch(() => {});
+ }
+});
+
+test('spawnTrial: an agent that starts slower than the configured timeout still gets its output before the deadline', async () => {
+ // The race itself, made to happen on purpose: the agent needs 1.7 s to get going and the configured
+ // timeout is 1.5 s. On a real timer the deadline would pass first and the trial would report "no
+ // transcript output"; on the test's clock it fires only after the init event was read.
+ const clock = manualClock();
+ let parser;
+ const trial = fakeTrial('init-then-hang', { timeoutMs: 1500, clock, env: { FAKE_AGENT_START_DELAY_MS: '1700' }, onStart: (s) => { parser = s.parser; } });
+ try {
+ await until(() => parser.eventCount >= 1, 'the slow agent printing its init event');
+ clock.fire();
+ const t = await trial;
+ assert.match(t.error, /timed out before routing \(1 transcript events, no decision\)/);
+ } finally {
+ if (clock.armed) clock.fire();
+ await trial.catch(() => {});
+ }
+});
+
+test('spawnTrial: with no injected clock the deadline is a real timer, and it ends a silent agent', async () => {
+ // This one runs on the real clock, and still cannot race: a silent agent prints nothing, so whether it
+ // had finished starting when the timer went off changes nothing about what the trial reports.
+ const t = await fakeTrial('hang', { timeoutMs: 300 });
assert.equal(t.timedOut, true);
assert.equal(t.routedTo, null);
- assert.match(t.error, /timed out before routing \(1 transcript events, no decision\)/);
+ assert.match(t.error, /timed out with no transcript output/);
});
test('spawnTrial: an absolute .cmd shim is launched through the shell (Windows)', { skip: process.platform !== 'win32' }, async () => {
@@ -237,8 +356,8 @@ test('spawnTrial: an absolute .cmd shim is launched through the shell (Windows)'
assert.equal(t.error, null);
assert.equal(t.routedTo, 'genpage');
} finally {
- fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
- fs.rmSync(cwd, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
+ await removeWhenFree(dir);
+ await removeWhenFree(cwd);
}
});
diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.json
index 79ad7fb80..9f95c6fee 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.13.0",
+ "version": "2.14.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.json
index 79ad7fb80..9f95c6fee 100644
--- a/plugins/model-apps/.plugin/plugin.json
+++ b/plugins/model-apps/.plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "model-apps",
- "version": "2.13.0",
+ "version": "2.14.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.md
index c6739670f..e4d32e7df 100644
--- a/plugins/model-apps/AGENTS.md
+++ b/plugins/model-apps/AGENTS.md
@@ -154,6 +154,127 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
Existing fields are not list-reordered. Verify checks form-wide cell/control ID uniqueness,
including auto forms, but not field order or anchor adjacency. See the
[form-layout contract](references/app-spec-schema.md).
+ **The Notes timeline** (#680, `lib/form-timeline.js` — one definition shared by the compiler, the
+ build's repair and verify) is written in the shape Dynamics renders: the fixed control id
+ `notescontrol` in a 23-row cell with `auto="false"` (its `auto`/spelled-out `showlabel`/`colspan`/
+ `rowspan` ride in the cell's bag), over the 22 empty spacer rows the cell spans. The old shape — a
+ generated control id in a one-row cell — is published and never rendered. What platform forms share is
+ the id, `showlabel="false"` and a cell of N rows followed by N−1 empty rows — N is 5, 20, 23 on different
+ forms, `auto="false"` is on some and not others, `colspan` is 1 or 2 — so the helpers take ANY N of two or
+ more as in shape: 23 and `auto` are what a NEW host is written with, never what an existing one is held to.
+ A rebuild repairs the engine's own host (the `section_notes` section holding the timeline control)
+ **in place** on every layout: one atomic rows write, same section, position and cell identity, and only
+ what is missing — the id, a span of one row, rows under the span (to the span the maker chose; extra rows
+ are never deleted); `auto` is written only with the conversion of an old cell, never alone. The repair
+ (`repairTimelineHost`) runs **last** of the passes that touch a form's fields — after the prune and the
+ `fieldOptions.after` moves — because it rewrites only the host's own rows and refuses a host that holds
+ another control: run first, it would refuse an old host whose stray field the same build then prunes, and
+ the form would stay old until a second build. The topology
+ pass does not narrow that host below its timeline's `colspan` (a widened timeline is the maker's width).
+ It never edits a maker's timeline elsewhere and never writes a second `notescontrol` — a form that
+ already has a control by that id gets no new host (the explicit-layout topology pass and the auto-layout
+ path share `timelineCreationBlocked`), and a host whose id cannot be renamed for that reason, or that
+ still holds another control once the prune and moves are done, is left whole and reported in
+ `skipped.layout`. That is one rule (`timelineRefusal`) applied to two different trees, not one decision
+ that both reach alike: the build judges the form as its field passes have left it, `--verify` the form as
+ published, BEFORE them. So verify predicts what the passes take out of the host (`notesHostInspector`
+ in `verify-spec.js`: a field an explicit layout declares in another section; one a `fieldOptions.after`
+ anchor places beside an anchor that is not in a section the build owns — an anchor that sits in the host
+ but is itself anchored is moved out first, because anchored fields are placed in dependency order, and
+ the field follows it; one an explicit layout with prune on does not list — `formRemovals`, the destructive
+ gate's own function) and hands the rule those cells as `leaving`. What a pass does is predicted only for
+ a field the form has ONE cell of. Each pass acts on a single cell of a field — the first it finds once the
+ topology pass has reordered tabs and sections (`planOrderMoves`), and the prune removes one cell of a
+ field per run — so for a field the form carries twice that a pass would act on (or one anchored, directly
+ or down a chain of anchors, to a field it carries twice with a cell in a section the build owns; the
+ reason names that field, not an anchor of one cell on the way to it) verify cannot know which cell a
+ build acts on. It says so (`unsure`), in every shape of its advice — the taken-id one included, since
+ freeing the id does not decide that cell: no promised repair (a full build repairs the timeline
+ *unless* it leaves the cell, which verify cannot tell), no certain refusal, and no sending the maker off
+ to do what the build may do itself. Only a pruned duplicate becomes predictable by itself (the prune
+ removes one cell per run, so verify is exact once one is left); one a declaration or an anchor places can
+ stay unpredictable build after build, since a build that acts on the cell already in place leaves the
+ others — the maker moves them, as the advice says. A field that no pass touches stays whichever cell is
+ acted on, one cell of it or several, so that is still said plainly. It is a prediction from the spec and the
+ published form, not the build: it also cannot see a removal that was not authorized or that the build
+ holds back, or a `fieldOptions` move skipped for a row-span or an overflowing row. Where it and a build
+ differ the build's report is the authority — the cases in `form-timeline-real-bundle.test.js` run both on
+ each shape, including forms whose published section order is not the build's, so a change to which
+ fields a pass takes out is made in the pass and the prediction together. An `auto` form that asks for
+ Notes and has no host gets one on rebuild (`addTimelineHost`, before the sub-grids: it has no topology
+ pass to add it). Fields never go into an
+ engine host: the no-section fallback skips hosts (`firstFieldSectionRowsPointer` — quick views use it
+ too), a `fieldOptions.after` anchor inside one is refused, and the narrowing re-flow never runs on one (it
+ would delete the spacer rows as "beyond the new count").
+ Verify's `form-timeline` check needs ONE timeline that renders (id `notescontrol`, a cell spanning
+ more than one row) on any form the spec gives Notes — and, for the engine's own host, the N−1 rows under
+ its span, since the build converges them; a maker's timeline is judged by id and span alone. So an
+ old-shape form fails it until rebuilt — and its detail says what a build WILL do about that form
+ (`timelineVerifyProblem`): "run a full build" where the build repairs or adds it, what the maker must do
+ first where it declines (another control holds `notescontrol`; the host holds a control no pass of the
+ build takes out — a maker's own control, or a field no rule of the spec moves or removes, which the maker
+ moves out of the section; on an `auto` layout, which declares no section for a field and prunes none,
+ that is any field already on the form that no `fieldOptions` anchor places). A field the build itself
+ prunes or places elsewhere is not the maker's to move:
+ the advice stays "run a full build" and names what the build takes out first, a removal with the
+ `--allow-destructive` it needs. A field it cannot predict is neither: where a full build would repair the
+ timeline the advice says it does so unless it leaves that field, which verify cannot tell; where the
+ advice is something else first (a control that stays, a taken id) it says verify cannot tell whether the
+ build takes the field out first — and, either way, what to do if the build's report says the timeline
+ was left as it is. Always a
+ FULL build: a `--changed-only` run of an unchanged spec is a no-op ("nothing to apply"), so a form an older
+ version left — which no change to the spec reaches — is never repaired by it.
+ Download does not reconstruct `forms[]` (see `hydrate-spec.js`), so `notes`/`hasNotes` are authored
+ and there is no form read-back to adapt.
+ **Where a sub-grid's section goes** (AB#6651699, `lib/form-subgrid-placement.js` — the pure rules the
+ spec gate, build, verify and wireframe all read): `forms[].subgrids[]` takes `after`/`before` (a
+ section of the declared layout), `tab`, `column`. An `after`/`before` grid sits in its anchor's tab and
+ form-column DIRECTLY beside it (`columnSequence` builds the order — grids that share an anchor keep
+ declared order, each directly beside the one declared before it — and `neighbourOf` names the token a
+ grid must touch); a `tab`(+`column`) grid is a question of MEMBERSHIP, created at the end of that column
+ and, once in it, left wherever it is within it. The names are what `formLayoutNames` (app-spec.js)
+ derives — an auto layout is `tab_general` holding `section_general`, pinned to the compiler by a test —
+ and `subgridPlacementProblems` is the one function behind both the spec gate and the lint (a key a
+ sub-grid entry does not read is only a warning — `subgridUnknownKeys` — because entries written before
+ the placement keys existed may carry extras the build never read). A form holds ONE grid per
+ relationship, so `subgridDuplicateProblems` (gate and lint, one function) refuses a relationship listed
+ twice when an entry places the grid — those keys are new, so no spec that built is turned away — and only
+ warns for a repeat that places nothing (the build has always ignored the extra entry); verify fails the
+ later entry rather than pass it. A grid with
+ NO key takes the original path exactly (end of the first tab's first column, never moved): a test
+ records its writes. The build (`addSubgrids` → `placeGridSection`) runs after the
+ topology pass, using the tab/section matches that pass recorded (`reconcileFormTopology` returns
+ `{ sectionTargets, tabIndexOf }`) — so an anchor matched by label under another name is still the
+ anchor. Grids with no anchor are appended first, in declared order, as they always were; the anchored
+ ones follow — `after` grids in declared order, `before` grids in reverse — each put directly beside the
+ nearest token toward its anchor already on the form (`anchoredPosition`), which is where a NEW form
+ puts it: a new grid is added there in one write, an existing one is MOVED (same section, one
+ `moveElement`, within a column or across form-columns), and one already directly beside it writes
+ nothing. ONLY THE GRID MOVES: `planOrderMoves`, the fewest-moves planner the topology pass uses, is
+ deliberately not used here — it moves whichever section is cheapest, and on the layout every released
+ build left behind (`notes: true` + a grid: the grid BEHIND the Notes section) that is an authored
+ section or the timeline, leaving the Notes section mid-form; a section in between (the Notes section, a
+ maker's own) is simply left behind the grid. Only the engine's own `section_grid_*` host is ever moved;
+ a grid a maker put in a section of their own is reported in `skipped.layout` — unless it is already
+ where the spec puts it, which is neither written nor reported — as is an anchor/tab the
+ deployed form lacks (the grid is then added at the end of the first tab, never lost). Adding or moving
+ a section shifts the indices of the sections behind it, so everything that holds a section across
+ `addSubgrids` is kept by what it is, not where it is: `shiftSectionTargets` corrects the topology pass's
+ recorded targets, and a field being ADDED is queued with its section's id and name
+ (`queuedSectionPointer` finds it again through `findSectionById`, then by name and place) — an index goes
+ stale when a grid section is inserted ahead of it or taken out of the column, and the field would land
+ in the grid's section or halt the forms phase on a pointer that addresses nothing; a section gone
+ altogether sends the field to the first field section, reported. Quick views go to the first FIELD
+ section too, never a grid's. Verify's
+ `form-subgrid` check judges each placed grid
+ against the DEPLOYED form with the same `neighbourOf` — directly beside its neighbour, anything between
+ them named — (`RelationshipName` is element text — `parseFormTopology` reads it), on explicit and auto
+ layouts; a failing detail says to run a full build where the build moves the grid, and what the maker
+ must do where it is in a maker's own section. The wireframe and the offline eval reader read a compiled
+ column by PLACE (`columnItems`; `columnSequence` tokens carry `at`), never by name — a layout may declare
+ a section named `section_notes` too. A grid is as wide as its form-column, so a full-width grid wants a
+ one-column tab (documented,
+ not engineered). Download does not reconstruct `forms[]`, so placement is authored too.
**Which form a table opens with** (AB#6736948, `lib/form-order.js`) is decided by the table's Main
Form Set order — each Main form's formxml `<DisplayConditions Order>` — not by `systemform.isdefault`
(measured: moving the flag reorders nothing, and a table's three new forms, all at the same order,
@@ -232,10 +353,81 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
download. Every `pageInput.data` key must also be produced by an incoming `navigatesTo[].data`
edge. See `references/app-spec-schema.md` → *the input contract*.
The build halts on safety violations (`pages-removed`, `pages-shared-across-apps`,
- identity conflicts, read failures). The cross-app shared-page scan (`fetchAppsForPages`) enumerates every app via the vendored SDK's
+ identity conflicts, read failures) and, before any page is created or updated, on a page that would ship a Griffel
+ shorthand (`pages-griffel-shorthand`: a page it creates, or one whose source changed since the last recorded apply — a page it
+ sends again as it is gets a warning; see "Griffel shorthands"). The cross-app shared-page scan (`fetchAppsForPages`) enumerates every app via the vendored SDK's
`@odata.nextLink` pagination (`queryRecords({ paginate:true })`), so it verifies EVERY app in the
environment rather than one 5000-row page; a pagination fault (the SDK's repeated-nextLink guard) still
- fails **closed** rather than scanning a partial list. Classic `dashboards[]` are opt-in.
+ fails **closed** rather than scanning a partial list. It reads each other app's PUBLISHED sitemap and also its
+ SAVED (current, unpublished) one: a page another app has saved into its navigation but not published still
+ halts the update (`pages-shared-across-apps`, naming the app `[saved, not published]`). The scan is a snapshot: another maker
+ can take a page into another app's navigation while the build runs, and nothing reaches far enough to stop it — the lease is
+ this workspace's, Dataverse offers no write conditional on another app's sitemap, and the update goes through `pac`, which
+ takes no precondition. So a build that writes pages in place takes the scan twice more, over the pages it began with and now
+ overwrites (one this run created, a navigation target included, was not there to share and is left out): right before the
+ first of them is written, where a page that became shared halts the build before any page it began with is updated in place
+ (`pages-shared-across-apps`, "became shared across apps while this build ran", `transient: false`); and after the last — or
+ after the loop stops early, since what it wrote is written — where a page taken in while the uploads ran is reported as a
+ warning naming the page and the app (one that only saved it shows the new content once that app is published; a scan that
+ fails there is a warning too: nothing is left to refuse). Each scan reads every other app's navigation (three requests per
+ other app, and three more), which is why it is not taken before every page. The saved layer of
+ every other app is **one** extra request — the `sitemap` collection's `RetrieveUnpublishedMultiple`, joined to each app by the
+ sitemap id its published read found, with the same current-row rule `navigationProof` uses — and it is fail-closed too: a
+ read that fails as a whole halts as `pages-shared-check-failed`, and an app whose saved row is missing, ambiguous or
+ malformed is listed unreadable. An app that was **never published** has no row in the published app list, so the scan lists those
+ as well — one request, the `appmodule` collection's `RetrieveUnpublishedMultiple` (`draftOnlyApps`) — and joins each one's saved
+ sitemap from the same saved-layer read, by the sitemap id its layer's sitemap component names (one more read per such app); it has
+ no published layer, so whatever it holds is saved only. That list is fail-closed like the others: a read that fails halts as
+ `pages-shared-check-failed`, and a never-published app whose layer, sitemap component or saved sitemap cannot be read is listed
+ unreadable. A never-published app whose component read **succeeds** and finds **no sitemap component** is not yet shown to have no navigation: the
+ vendored SDK links an app to its sitemap **by name** — it looks the sitemap up with `sitemapnameunique eq '<the app's unique name>'` and takes one for the app only
+ while that column holds the app's name, and `ensureSitemapInSolution` (sdk-build.js) resolves it the same way — so such an app may hold a sitemap, and pages in it, that no component row links to it.
+ The saved-layer read the scan makes anyway (it asks for `sitemapnameunique` too — no further request) shows whether it does: a sitemap of that name is joined
+ like any draft app's (case-insensitively, as Dataverse compares names), several sitemaps of the name leave the app unreadable, and **none** means the app has no
+ navigation at all and holds no page, so it is skipped — one draft app saved with only a name must not stop every page update in the environment (a read that
+ *fails*, or a component that names no sitemap, proves nothing and is still unreadable; so is a *published* app with no sitemap
+ component, which is not changed here). A single-app environment reads no other app's navigation: it pays the one small request for the list of
+ never-published apps, and nothing more when there are none (one saved-layer read as well when a never-published app has no sitemap component, to rule out a sitemap linked by
+ name). Classic `dashboards[]` are opt-in.
+ **Every `pac model genpage` call is time-bounded** (`lib/genpage-cli.js` `runPac`): 3 minutes to list or download and
+ 10 minutes to upload by default, or `POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS` (1 s to 60 min; one value sets all three). When
+ the time is up the whole process tree is ended — a page upload once stalled for 17 minutes with no CPU and no network — and the call is
+ reported as `timedOut`, which no exit code is. What happens next follows from what the call can have done. pac's upload writes the
+ page, records the prompt and the agent message (two more requests), prints `Page ID`, then publishes, so a stopped upload has done
+ anywhere from nothing to all but its last step. A timed-out list or download is read-only, so it is retried once. A timed-out
+ **update** is **not** retried, though it names a page that exists: a re-send can record the prompt a second time (a call stalled in the
+ publish has already written everything) and goes out minutes after the caller's own checks, so it can overwrite a change saved in
+ between. It is reported as one that *may have landed*, and what it sends you to look at depends on the caller (`upload()`'s `caller`):
+ the upload script's message names `genpage-base.js check` (the deployed page against the file and the base marker beside it), and a
+ re-run goes back through the script's own guards. The **build** keeps no base marker, so that check could only answer "unknown", and
+ every page's code file is a staging copy its cleanup deletes, so the command would fail on a missing file: the build's message
+ tells you to read the deployed page with `pac model genpage download` (the call the build already uses, for that page id — and to open the `page.tsx` in the folder named for the id, which pac writes in its own letter case) and then run
+ the build again, which sends the page once more to the same id — nothing new is created, but if the stalled send did land, the page's
+ history now records its prompt a second time, and anything saved to the page in Maker since is replaced by the app folder's version.
+ The error carries `transient: false`, so the build's own retry of transient halts never re-sends it. An **update** that **fails** — a non-zero exit, or an
+ exit 0 with no `Page ID` — is handled the same way, for the same reason (pac can fail in the publish, after everything else is written): it is **not** retried,
+ it is reported as one that *may have landed*, with what pac had printed (a `Page ID` means the page and its messages were written and the failure came in the
+ publish) and the same caller-specific check, and it carries `transient: false`. Only a non-zero exit that pac reports for its own arguments or input files
+ (`isDeterministic`) is an ordinary error, because pac checks those before it sends anything — and only when pac printed no `Page ID`:
+ after the Page ID its one remaining step is the publish, whose error carries the server's own text, so a Page ID proves the page
+ was written whatever the words. An update answered with another page's id also carries
+ `transient: false`. That covers the halt an upload causes; a transient halt *later* in the same run (a 503 on a later read or
+ write, say) still re-runs the whole build, which sends each page this run sent once more — as each rebuild does — so the page's
+ history then records the prompt once more. A timed-out **create** is an
+ uncertain create and is never run again, because a second create is how a duplicate is
+ made. A `Page ID` pac had already printed names the page it created, whether the call then stalled or **failed** (exited non-zero): it is reported as
+ *created as `<id>`, stalled (or failed) before publish or placement*, the create is **not** sent again however the environment's listing looks (the page need
+ not be in it yet), and the way on is to place it (`pac model genpage add`, or Maker) and then update it, or to delete it and re-run the
+ create — never "update it" outright (refused: not in the app's navigation) and never a bare re-run. With no id printed, the
+ env-wide id diff reports any page already visible — a create that failed and left a candidate gets the same way on, not "re-run it as an update with `--page-id`" — and a page that
+ is not visible *yet* proves nothing: a create that stalled with nothing visible, or whose listing cannot be read, is reported as uncertain with the advice to wait and list
+ `pac model genpage list --environment <envUrl> --include-unpublished` before anything is created again. **Every error that follows a create whose outcome is not known to be nothing carries
+ `transient: false`** (`neverRetriedError`) — a stall, a printed Page ID, a candidate in the listing, a listing that cannot be read: the build re-runs a phase when a halt reads as transient (`isTransientHalt`, build-model-app.js), and it reads the halt's *text* — which
+ quotes the page's name (a page called "SQL Timeouts" matched) and pac's own words ("… try again later") — so without the marker a re-run would be a second create and a
+ duplicate page, with the run reporting success. The page that was created but whose local receipt could not be saved (`pages-creation-receipt-failed`) carries it too. A create that
+ failed outright and left nothing in the listing, and a listing that fails *before* the create was sent, leave nothing to duplicate: both are still retried — by the upload (3 sends) and,
+ when the error's text reads as transient, by the build — as in 2.13.0. (`pac connection list` and
+ the auth probes have their own limits or none; this bound is the genpage calls'.)
**All of the build's Dataverse access is via the SDK** (see "Dataverse Access From Scripts" for the
sanctioned exceptions elsewhere), so metadata is persisted under
`<app-folder>/.maker-workspace/` for reuse/edits. The 16 phases
@@ -255,14 +447,73 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
exposes no created-model id to this caller, so same-name AI models are reported and kept.
Emits `[n/total]` events the orchestrator narrates + a `BuildHalt` it gates on. Dry-run by
default; `--apply` writes, `--sample-data` / `--publish` opt-in (`--publish` gates the final *bulk*
- publish; edit/finalize paths — reconciling an existing form/view, form events, quick-views,
- existing-app sitemap, page finalize — still publish their one artifact so the change takes effect).
- The bulk publish is ONE `PublishXml` envelope (`publishArtifacts`) for every table and the app, and
- with `--publish` the default-view enrichment defers its own publish to it. A build that halts before
- it hands what is still owed to the CLI, which keeps each attempt's debt across transient retries until
- a publish phase pays it, and settles the rest per target once no retry follows (`settleOwedPublishes`)
- — so a halted build leaves those views live, as it did before the batching. A default-view push
- refused by a concurrent edit fails the enrichment step, as any refused push does.
+ publish; without it the edit/finalize paths — reconciling an existing form/view, form events,
+ quick-views, existing-app sitemap, page finalize — still publish their one artifact so the change
+ takes effect, and with or without it the lookup-label repair publishes the tables whose columns it
+ relabelled). The bulk publish is ONE `PublishXml` envelope (`publishArtifacts`) for every table and
+ the app, and with `--publish` the default-view enrichment, the reconcile of an existing view or form,
+ form-event wiring and quick-view placement all defer their own publish to it: an entity publish ships
+ every pending customization on that table, so one per artifact only repeated it, at ~2-2.5 s each.
+ The tables the reconcile, form-event and quick-view paths touched are also published together once,
+ in one envelope at the start of the app step, before anything publishes the app
+ (`publishReconciledTables`). Measured live: a `PublishXml` naming only the app, sent after an existing
+ form's save and before its table's publish, leaves the form's label changes unpublished for good, while
+ the structure saved with them goes live. The enrichment's default views (columns only) wait for the
+ bulk publish. A table whose early publish the SDK refuses stops the build before the app is written
+ (`reconciled-publish-failed`), since the app's publish would strand its labels; the halt carries what
+ is owed, so the CLI's retry, or its settle once no retry follows, publishes the table without the app.
+ A deferred publish is recorded as owed, and a build that halts before the publish phase hands what is
+ still owed to the CLI, which keeps each attempt's debt across transient retries until a publish phase
+ pays it, and settles the rest per target once no retry follows (`settleOwedPublishes`) — so a halted
+ build leaves those views and forms live, as it did before the batching. The record also keeps the NAME
+ of every view and form deferred onto a table (`view Open Tickets`, `form Ticket events`; the CLI
+ unions them across attempts), and `default views of <table>` when that table's default-view
+ enrichment saved its generated Active/Inactive pair — whether the enrichment makes the record or joins
+ one an authored view's reconcile already made — because one artifact stands for its whole table in the
+ envelope: when that publish fails or cannot be confirmed, the warning names what is saved but not
+ live, as the per-artifact publish it replaced did, rather than the table's Main form. That warning
+ also names the views, forms and charts the run created on the table (and a chart whose description it
+ wrote), each name once: a first build creates them all and defers no publish for them, so its record
+ would otherwise name only the default views and the line would read as if only the generated pair
+ were not live. Those names are labels only and stay out of the owed record, which is what a halted
+ build publishes, so the warning after a halt names what was deferred. Settling covers
+ a halt the build THROWS. A process killed outright (Ctrl-C, a crash, a closed terminal) settles
+ nothing, so what a reconcile had saved stays saved but unpublished until the next build, which
+ publishes it (a clean workspace copy is still published, below): no marker outlives the process, the
+ default-view enrichment has the same exposure, and the app-builder skill's recovery guidance says to
+ re-run. A default-view push refused by a concurrent edit fails the enrichment step, as any refused
+ push does.
+ **An unchanged rebuild writes almost nothing, and no write is skipped on a guess.** An existing view
+ or form is pushed only when the SDK reports that its workspace copy differs from its last-synced
+ snapshot (`diffArtifact`, `lib/unsynced-edits.js`): an edit this run made, or one an interrupted run
+ left in the workspace — which a plain fetch keeps while the server has not moved, so comparing what
+ this run computed with what it fetched would call it unchanged and never push it. An SDK without the
+ method, or a diff that fails, pushes as before. A clean copy is the UNPUBLISHED layer, so it says
+ nothing about what is published: without `--publish` the reconcile still publishes its artifact even
+ when it skipped the push, since an earlier run may have saved and stopped. The reconcile of a reused
+ component also re-asserts its solution membership, and one read answers all of them
+ (`lib/solution-membership.js`: a single paginated `solutioncomponent` query for the component types
+ the build adds plus the solution's tables, made at first use, so a build that reuses nothing and
+ deploys no pages never makes it). A component the read proves present is not added again — views,
+ forms, charts, business rules, the process flow, the app, its sitemap, the page manifest and persona
+ roles. There are two proofs: a row of the component's own, or, for a view, chart or form ONLY, its
+ table being held by the solution with ALL its subcomponents (`rootcomponentbehavior` 0). A table the
+ build creates is held that way, and the platform does not list such a table's views, forms and
+ charts one by one — an explicit `AddSolutionComponent` for one leaves no row — so a rebuild that
+ looked only for rows sent those adds every time (measured live: 10 of the 19 an unchanged rebuild
+ sent). The table's MetadataId, which is the `objectid` of its row, is read once per table, only for a
+ component without a row and only when the solution holds some table that way, through the raw client
+ the build already uses for table metadata (`tableRefs`). A table held at 1 (its own metadata only) or
+ 2 (shell only) proves nothing, and neither does a row with no behavior: those components need rows of
+ their own, and are added without one. Anything the read does not prove (the read or the table lookup
+ failed, the solution is a built-in one) is added exactly as before. A component this run creates is
+ added directly, except the page manifest: it is persisted through the same check after every page
+ create and once more at the end, so a first build that deploys pages makes the read too — and still
+ adds the manifest, which the solution does not hold yet. What an unchanged rebuild still sends: the
+ phase-8 envelope; the SDK's own default-view enrichment (it pushes both generated views of each table
+ it enriches); the default-form promotion of a table the build owns (`isdefault`); the existing app's
+ sitemap push with its component pins and publish; the AI-feature setting writes; and each persona
+ role's privilege replace and app association.
**The modern ("new look") shell is opt-in via `app.newLook`.** It is a per-app SETTING
(`NewLookAlwaysOn`, written through the SDK's `saveSettingValue` scoped to app + solution), NOT an
app-module column — `navigationtype` is Single/Multi *session* and unrelated, which is the reason
@@ -377,6 +628,178 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
`app-spec.js`; `references/localization.md` is about generated **page** code, a separate concern.
Guarded by `scripts/tests/lcid-real-bundle.test.js`, which drives the REAL vendored bundle — a mock
would keep passing against a bundle that ignored the option.
+ **A label-bearing metadata read must not run ahead of a create that may carry a localized label**
+ (AB#6686428). Measured, order-controlled: a broad read that returns labels (`findTables`,
+ `findColumns`, `fetchEntityMetadata`) made right before `createTable` / `createColumn` /
+ `createRelationship` leaves Dataverse with only the base-language label of a multi-language one, with
+ no error. That is why the existence probes are narrow keyed reads without labels, and why a probe that
+ cannot answer halts, or assumes absent, instead of falling back to the broad read when a label is
+ localized (`findExistingTable`, `relationshipExists`). The view-filter **pre-flight**
+ (`preflightViewLabels`, `lib/sdk-build.js`) reads option labels and whole global choices before the
+ first write, and those reads were never measured to be exempt — so a spec that carries ANY localized
+ label (`localizedLabelLcidsInSpec`: a map on a table, primary column, column, inline option, alternate
+ key or lookup; which of them the environment lacks cannot be known without more reads) does not run it.
+ The views phase, which follows every create, makes the check instead, so a label that names no option
+ still stops the build before any view is written; what is lost is only the guarantee that nothing had
+ been written yet. Offline lint and validation, and the dry run (it creates nothing, so no create
+ follows its reads), are unchanged. Lookup labels keep the same discipline: the parent-label read sits
+ right before a single-language create, the relationships whose lookup label is localized are created
+ before any other (`relationshipsInCreateOrder`, `lib/entity-provision.js`) so that none follows such a
+ read whatever order the spec declares them in, and the repair's reads come after every create. Lifting
+ the skip needs a live measurement of these reads ahead of a localized create in a two-language environment.
+ The vendored SDK now sends `Consistency: Strong` on every metadata read (see "Newer SDK behaviors" below);
+ whether that changes this effect has not been measured, so every rule above stands until a live
+ two-language rebuild says otherwise.
+ **A lookup column's label defaults to the PARENT table's name** (ADO 6691205). An omitted
+ `relationships[].lookup.displayName` reached the SDK as `lookupDisplayName: undefined`, which the
+ vendored SDK fills with the referenced table's **logical name** (`label(opts.lookupDisplayName ??
+ opts.referencedEntity)`), so the column — and every form cell the SDK derives from it — read
+ `new_project`. One rule, `lookupLabelFor` (`lib/app-spec.js`), now serves the build, the form cell,
+ the previews, `app-spec-doc`, `schema-facts` and the download: the explicit label → the declared
+ parent's `displayName` (string or LCID map, kept as the map) → the display name the **environment**
+ reports for a parent the spec cannot name → a humanized table name. A parent the spec cannot name is a
+ table it does not declare, **or one it declares WITHOUT a `displayName` that the build did not create**
+ — `existing: true`, or found already there by the data-model phase — because the environment's name is
+ then the only one it has (an `existing: true` `incident` is "Case", `systemuser` "User", not a
+ humanized "Incident"/"Systemuser"). `lookupParentNeedsEnvironment` (`lib/app-spec.js`) decides who asks;
+ the read is `readTableLabel` (`lib/lookup-labels.js`), and a label that is only the table's own
+ identifier — what a build writes for a table with no `displayName` — is ignored. A parent that sets a
+ `displayName`, and one the build creates itself without one, are never read. Offline surfaces cannot read
+ the environment, so they show the humanized name wherever the build would read one — the plan adds "or the
+ label from the environment if `<parent>` is already there" for a declared parent with no `displayName`
+ that the build may find already present.
+ The build has no general column-label reconcile, so the **rebuild repair** is its own pass
+ (`reconcileLookupLabelsPass`, `lib/entity-provision.js`; opt-in through `reconcileLookupLabels`, which
+ only `sdk-build.js` sets, because `provision-entities.js` counts its own steps). It acts only when the
+ spec omits the label AND the live label is exactly the old default — for a **column**, the lower-case
+ logical name of the parent (what the SDK labels the column with; `isOldLookupColumnLabel`),
+ **case-sensitive** (a correct "Contact" is not one, so it costs no read and a maker's "Contact" is never
+ overwritten; neither is a column that carries the lookup's own name — no build ever wrote that on a
+ column) — in a single language that is the
+ **build's own** (an old default in another language is left alone, with a warning: the write would add
+ the build's language beside it, leaving two languages of which one is still an identifier, and every
+ later rebuild would skip the column) — and writes **one language** (the authoring LCID) through
+ `updateColumn`'s merge, never a map. It converges to the same label a fresh build writes, the
+ environment's name included. A column's label is part of its table's definition, which Microsoft documents as
+ reaching model-driven apps only once the table is published, so the pass then publishes every table it relabelled,
+ in one `<entities>` PublishXml, with or without `--publish` — in the data-model phase, before anything can publish
+ the app; a failed publish is a warning that names the tables. Nothing else in the build is sure to publish them:
+ its other table publishes follow from what the spec puts on a table (a form, view, chart or icon, or its enriched
+ default views), and a downloaded spec carries no forms, views, charts or table icons and marks every table
+ `existing: true`, whose default views the build leaves alone. No metadata read can confirm that publish: measured
+ live, `RetrieveEntity` returns the new label right after the PUT even with `RetrieveAsIfPublished=false`, so a
+ live check of it has to trace the request. The labels are read **once per child table**
+ (`Attributes?$select=LogicalName,DisplayName&$filter=LogicalName eq '…' or …`, the read the SDK itself makes for
+ column hints), for the lookups the run did not just create, and a failed read is warned about once per table.
+ `lib/lookup-cell-labels.js` applies the same rule to
+ the form cell that stored the old label (the SDK takes a cell's label from the column only when the
+ cell has none), whose old default is the parent's lower-case logical name **or the lookup's own** — what the
+ SDK labels a field with when it cannot resolve the column at push (`isOldLookupFieldLabel`); it is a separate
+ module so `entity-provision.js` and `artifact-intent.js` do not
+ require each other. A cell that still holds the old default follows the column's CURRENT label — the
+ repaired one, or a maker's. Every cell of the lookup is held to that rule on its own label: a form can hold a
+ field more than once (`findFieldCellLocations`), and a first cell that is right, or a maker's, says nothing
+ about a second one an older build left. A label-bearing metadata read immediately before a labelled create makes Dataverse
+ keep only the base-language label, which is why the existence probe stays narrow for a localized
+ label, the live parent-label read sits right before the plain create only (a localized lookup is created
+ before any relationship that needs one), and repair reads run
+ after every create. Download leaves `lookup.displayName` out when it equals what a rebuild would
+ write **or is the old default** (the parent's logical name): an explicit label is never repaired, so
+ writing the identifier out would carry the defect through download → edit → rebuild, where leaving it
+ out hands it to the repair. Any other label is written as it is. Pinned by
+ `scripts/tests/lookup-label-default.test.js` (its REAL BUNDLE tests drive the `createRelationship`
+ body, the `updateColumn` PUT and a pushed form cell through the vendored bundle) and
+ `scripts/tests/lookup-label-download.test.js`.
+ **Choice labels in view filters resolve against the ENVIRONMENT** (ADO 6691114,
+ `lib/view-filter-labels.js`). The spec alone (`choiceValueMap`, 100000000 + index) is right only for an
+ option set this build created. A view on a table the spec reuses without declaring the column
+ (`{ "schemaName": "account", "existing": true }` filtered on `industrycode`, a LOCAL option set — or a
+ column bound to a system global choice) sent the LABEL as the condition value; lint passed, and Dataverse
+ rejected the saved view MID-BUILD, after the tables and columns were written, leaving a half-built app.
+ A declared global choice that already existed with other values did too (`createGlobalOptionSet` REUSES an
+ existing set unchanged). A column bound to a global choice the spec does NOT declare is a lint ERROR
+ (`spec-lint.js`, "references unknown globalChoice") — the build would create it with no options — so it is
+ not a case the resolver serves, and lint adds no second word about it. (That check is lint's only:
+ `validateAppSpec`, which the build runs, does not repeat it.)
+ `readChoiceAttributes` reads a table's option sets (four narrow cast reads — Picklist,
+ MultiSelectPicklist, State, Status — expanding `OptionSet`, which a global-bound column fills as a local one
+ does) once per reader, and a build has up to two: one for the pre-flight and a fresh one for the views phase
+ (the data model has been written since), so a table is read **at most twice per build** — and not at all for
+ a table no label names — and a label matches in any language, an ambiguous alias refused. It is deliberately not
+ `fetchEntityMetadata`: that costs about eleven requests, WRITES the workspace (a dry run must not) and keeps
+ only the caller's language. The label is judged twice, on purpose:
+ - **Before the build writes anything** (`preflightViewLabels`, `lib/sdk-build.js`, run by any apply that
+ includes `solution` or `data-model` — so the staged flow's data run too — **unless the spec carries a
+ localized label**, see the AB#6686428 note above) through
+ `checkViewFilterLabelsBeforeBuild`. Before the build runs the environment cannot hold what the build is
+ about to create, so each label is judged by whichever side is AUTHORITATIVE and only a DEFINITE answer
+ halts: a column the environment already has (its options are final), or a column the spec declares and the
+ environment lacks (the spec's inline options — or, bound to a declared global choice, the environment's
+ copy when `readGlobalChoiceOptions` finds the set, since it is reused unchanged, else the spec's). A
+ status reason the build inserts, a table it creates, a read that failed or was partial, and a label that
+ the spec's own number stands in for (see the views phase) are NOT problems
+ here — a false halt would stop a good build — and are the views phase's to judge. What the environment
+ already held and resolved is handed on as final — a column's own options, and the values of the
+ existing global choice a column the build creates will be bound to — so a failed read in the views phase
+ cannot make it fall back to the spec's 100000000 + index.
+ - **In the views phase, once the data model exists** (`resolveViewLabelsOrHalt`, a fresh reader): the final
+ answer and the values. For a column bound to a declared global choice whose own options could not be read,
+ the **set itself** is read (`readGlobalChoiceOptions`), because that is what the column is bound to — which
+ is how a spec with a localized label, having no pre-flight to hand a value on, still resolves it. The spec's
+ own options answer only where the environment cannot (table not there yet, failed read), for a declared
+ Choice column — a FALLBACK, right only for an option set this build created, so the build **warns**
+ whenever it uses it. An undeclared column whose table cannot be read is used as written, with a warning.
+ **Where the spec numbers the options** — a column with inline `options[]`, or one bound to a global choice
+ that `globalChoices[]` declares — and the environment has options for the column (or the set) but none
+ labelled as the filter says (a maker renamed "Gold" to "Gold Tier", or a localized option's translation never
+ reached the environment), the spec's own number is used, **with a warning**, when the environment has an
+ option with that number (`specNumberStands`). That is what the build did before labels were resolved against
+ the environment, so halting the apps it built would be a regression — and for a declared global choice a
+ maker's rename would make `build --apply --verify` fail on every run with nobody having touched the spec.
+ That the option on the number is the one the label named is an ASSUMPTION, so the warning says so and says
+ how to take the choice out of the build's hands (use the option's integer value). It is **never made against
+ the environment's own evidence**: the number is refused, and the label is a problem — the build halts, before
+ it writes anything where the pre-flight can see it — when the environment has no option on the spec's number
+ (a set from another publisher's range has none, so it halts too), or when the option on it goes by the name of
+ another option of the spec (in any of its languages), or when the environment carries a label of this spec only
+ on other numbers **and that shows the numbering moved**: the label is the filter's own option's (any alias, in any
+ language), or it sits on a number the spec gives another option — options the author inserted or reordered after
+ the column was built, since a rebuild never changes an existing column's options; a column made elsewhere; a set
+ another app created in another order. A label on a number the spec does not use at all is an option a maker added
+ or re-made (one added in the Default solution takes another publisher's range, one deleted and re-created takes
+ the next free number): every number the spec has is where it was, so it is not held against the spec — a maker who
+ adds an option and renames another does not stop a build the numbers still serve, as they served 2.13.0. That
+ check compares labels without regard to case (a label still **resolves** by its exact text only), since an
+ environment that differs from the spec in case alone must not hide a different numbering. **A refusal says why**:
+ the problem line adds *The spec numbers "Gold" 100000001, but the environment shows another numbering ("Bronze" is
+ numbered 100000003 there, 100000002 in the spec), so that number is not used.* — in the halt, in the dry run's
+ reason, in `--verify`'s detail and in the line for a view that already exists. What the rule cannot see is the
+ residual: where nothing the environment carries contradicts the number — every option renamed, a column made
+ elsewhere in another order with options the spec lacks and the filtered option renamed, or options the author
+ removed from the spec so that later ones now sit past its numbers — the number is the one earlier builds used (so
+ never a different value than 2.13.0 sent), and the warning, which names the option the number landed on, is the
+ only trace; `--verify` passes such a view, as it did under 2.13.0. A label two options share resolves the same
+ way, to the one the spec numbers, when the spec's number is one of them.
+ Both halt with `BuildHalt` code `view-filter-label-unresolved` (phase `preflight` for the pre-flight's halt,
+ `views` for the views phase's, `recoverable: false`,
+ `transient = false`), naming each view, column and the valid labels, and only a view the build would CREATE
+ can halt it: `reconcileView` never reapplies an existing view's filters, so for one the build only says — as a
+ warning — that its filters are left as they are and verify will report the label. The dry run
+ (`annotateLivePlan`) asks the pre-flight's question and reports such a view as `? unknown` — with
+ `wouldHalt` on the plan item, so the summary counts it as "would stop the build" and not as "could not be
+ read", which it was not — and says (as a warning, once) what the apply will say: for a view it leaves as `create`
+ or `reuse` because the spec's number stands in for a renamed option, the assumption it will warn of; for an
+ existing view whose label names no option, which stays `reuse`, that its filters are left as they are and verify
+ will report it; `--verify`
+ expects the resolved value through the reader-gated `choiceAttributes` capability (`verify-model-app.js`),
+ and a label whose option metadata could not be READ is reported as **unresolved**, with the reason, never as
+ a missing filter — unless the deployed view has no condition on that column with that operator at all, which
+ is a missing filter whatever the options are (a deployed value equal to the build's fallback still verifies);
+ and `lint-app-spec` says offline that a label is "checked against the environment at build time" when the
+ spec alone cannot prove it. Sample-data labels still resolve from the spec alone. Pinned by
+ `scripts/tests/view-filter-labels.test.js`, which includes REAL BUNDLE reads of a global-bound column's
+ option set and of a global option set, a build test per gap, tests that no write precedes the
+ pre-flight's halt, and tests that no label-bearing read precedes a create of a localized spec.
`--verify` (opt-in) auto-runs the read-only reconcile after a successful apply and exits non-zero on a silent partial build (the same
check `verify-model-app.js` runs standalone). Recovery from a halted build is a full rerun (idempotent).
**`--changed-only`** (Preview, off by default) is a fail-closed SAFE partial apply: after a FRESH
@@ -405,7 +828,8 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
`entities[]`. `scripts/lib/app-components.js` is the one home for component inventory, pin/proof
and layer reads. It resolves `MetadataId,EntitySetName` before any app write, pins only missing
tables right after app identity exists on both create and reuse, then re-resolves the CURRENT
- layer and proves the rows. An SDK create already publishes, so a fresh app's new pins are
+ layer and proves the rows. An SDK create already publishes (the build keeps it that way — see
+ "Newer SDK behaviors" under `## Building & Testing`), so a fresh app's new pins are
published again even without `--publish`; an existing app's normal finalizer/publish includes
them. Dropping a table from the list never unpins it.
**`app.mainForms` is a name-based Main-form allow-list for sitemap Entity tables.** Names resolve
@@ -460,8 +884,8 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
deletion; names alone do not. Navigation is either layer: the published sitemap, and the saved but
unpublished one when the published layer leaves a page unproven (`navigationProof`, the layer a download reads);
when that saved layer cannot be read and a page stays unproven, the app is left intact for a re-run. The BUILD
- binds a page by its published navigation or a receipt only, because its shared-page scan reads other apps'
- published navigation; a page only in the saved layer halts with advice to publish the app first. The verified ownership set is persisted locally before app deletion,
+ binds a page by its published navigation or a receipt only; a page only in the saved layer halts with advice to
+ publish the app first (the build's shared-page scan reads OTHER apps' saved navigation as well — see above). The verified ownership set is persisted locally before app deletion,
so a page-less retry still has proof after the app is gone. Unreadable proof or a failed record write
leaves the app intact. Proven pages still undeleted, including dependency-blocked pages, keep the
manifest, solution and local teardown record and make the run fail. Records are consumed only for
@@ -480,7 +904,10 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
**`scripts/lib/sdk-http-client.js` must implement `postRaw`**: the SDK will not fall back to two
sequential deletes, so a transport without it fails every teardown with `APP_DELETE_NOT_ATOMIC` (see
that file for the wire contract, why a `$batch` is sent once unless its answer proves nothing in it
- ran — a SQL deadlock or a 429 — and why a conditional write that gets no answer is never re-sent).
+ ran — a SQL deadlock or a 429 for conditional deletes, a 429 for a change set that only creates columns — and why a conditional write that gets no answer is never re-sent).
+ The SDK re-sends an app delete itself when the platform's search-index insert race refuses it (HTTP
+ 400, SQL 547) — an answer this client never re-sends — so the two layers add and never multiply
+ (counts pinned in `scripts/tests/sdk-resend-layers.test.js`).
Pinned by
`scripts/tests/app-delete-real-bundle.test.js` against the real bundle — every other teardown test
drives a mock and would stay green through a regression here.
@@ -626,13 +1053,23 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
dropped and counted in `droppedSubareas`.
- **`scripts/verify-model-app.js` → `scripts/lib/verify-spec.js`** — read-only reconcile of the App Spec
against what actually deployed; exits non-zero and lists anything missing, catching silent partial
- builds. Checks **existence** (entities/columns/views/charts/forms + sitemap subareas + icons + pages by
+ builds. It works through a throwaway SDK workspace, never the folder's `.maker-workspace` (which belongs to
+ the environment it was first opened for): every read it makes goes to the server, so it verifies any
+ environment the app is deployed to and creates or binds nothing in the folder. It only READS the build's
+ baseline, `last-applied.json`, from `--workspace`, and only when that baseline describes this
+ environment. Checks **existence** (entities/columns/views/charts/forms + sitemap subareas + icons + pages by
id) AND, best-effort, **content** so an *unapplied edit* is caught (not just a missing artifact): a
view's **column set** (parsed from `layoutxml`; every spec column must be deployed — an extra deployed
column passes by design, so a column REMOVED from the spec, which the additive `reconcileView` leaves
in place, is not flagged), plus **relationship** and **command-bar existence** (previously unchecked).
Content checks are additive + reader-gated (they only fire when the reader supplies `layoutxml` /
- `entityRelationships` / `commandBar`), so existence-only callers are unaffected. **Dashboards** are
+ `entityRelationships` / `commandBar`), so existence-only callers are unaffected. A view filter's
+ Choice label is expected as the value the **environment** gives it, which needs the reader's
+ `choiceAttributes` (one memoized read per table per pass); without it the spec-only expectation
+ applies. A label whose option metadata could not be read is reported as **unresolved** with the
+ reason — never as a missing filter, which would call a correct view wrong because a read failed (a
+ deployed value equal to the build's own fallback still verifies) — unless the view has no condition on
+ that column with that operator at all: that filter is missing, and is said to be. **Dashboards** are
checked too (#586): each declared dashboard must exist. A name can also match another app's
dashboard, so when it matches several, verify checks the one the app's solution holds — the one the
build reuses (`dashboardsInSolution`, shared with the build and teardown) — and fails only when the
@@ -688,10 +1125,31 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
no AI features while reporting success. The build surfaces **every** non-success bucket as a `⊘` warning plus in the phase detail
— buckets are read off the result object, so one a future SDK adds is reported verbatim rather than
silently dropped — and `--verify` fails on any of them. **An app-scope setting WRITE is a no-op until
- the app is published** (live-measured: the write reports `notPersisted` and `appsettings` holds no row
- at all, while publishing and re-issuing the same call applies every feature). This is not read lag, so
+ the app is published** (live-measured: the write reported `notPersisted` and `appsettings` held no row
+ at all, while publishing and re-issuing the same call applied every feature). This is not read lag, so
re-*proving* after publish cannot fix it — the build **re-issues** the write after publish for anything
- the first attempt did not apply, `skipped` INCLUDED. On a fresh app nothing persists pre-publish, so
+ the first attempt did not apply, `skipped` INCLUDED. (The SDK now also proves a write against the app's
+ UNPUBLISHED layer — `appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()` — so a row it
+ saved but that is not published yet comes back `applied` with `pendingPublish` instead of
+ `notPersisted`. That is still not in force: `--verify` and the runtime read the published row. So
+ `rebucketPendingPublish` in `lib/ai-app-settings.js` moves it out of `applied` into a `pendingPublish`
+ bucket of the plugin's own, and the post-publish pass gives it the publish — not a second write, since
+ its row is already saved: with `--publish` the publish phase has put it in force and the pass only
+ PROVES it, otherwise the pass fetches and publishes the app first. A feature the SDK did not save at all
+ is still re-issued after that publish, and the re-issue's result is filed the same way: a publish that
+ failed, or could not be confirmed, leaves the row in the unpublished layer, and the SDK then answers
+ `applied` + `pendingPublish` again. Whatever the proof does not find in the published layer is reported
+ `NOT YET PUBLISHED` (and listed under `pendingPublish` in `--json`), never `applied`. That proof reads
+ an absent row up to three times, 500 ms apart — the budget `--verify` has (`AI_PROOF_BUDGET`, one value
+ in `lib/ai-app-settings.js`; `sdk-build.test.js` and `verify-spec.test.js` pin both sides) — because a
+ publish can answer before its row is readable, and a single read
+ reported that lag as `NOT YET PUBLISHED` in a run whose own `--verify` passed. A check that could not run
+ (the app, the definition or the row could not be read) says so first in the warning — "the check after
+ the publish could not run: …" — ahead of what the SDK said, so a failed read is never taken for a look that
+ found nothing. Without the move,
+ a build with no `--publish` would end with unpublished rows that `--verify` fails on. Pinned in
+ `ai-app-features-real-bundle.test.js`, `sdk-build.test.js` and `sdk-build-publish-batch.test.js` — the
+ batched publish tells the pass whether the app's own publish went through.) On a fresh app nothing persists pre-publish, so
the gate diagnosis fires for every feature that has one; abandoning those would leave `--verify`
failing on a row the build declined to write a second time, and a reported customer environment ran a
working app at `NLGridSearchSetting = 2` with `EnableNLGridSearch` off. Anything still `skipped` after
@@ -737,6 +1195,167 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
`findExistingColumns`, `relationshipExists`, `artifactIdentityQuery`) rather than a parallel
implementation, 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.
+- **Bounded parallelism in the read-heavy and publish-heavy paths.** Each item below has tests that count
+ requests 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),
+ and each keeps a one-at-a-time form (`concurrency: 1`, `inlineColumns: false`) that is the oracle its
+ output is compared with byte for byte. Every fan-out is
+ `mapLimit` (`lib/entity-provision.js`; its `firstInOrder` option makes the thrown error the
+ lowest-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
+ than 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
+ the buffers joined in listing order, so it is the same whichever read answers first; a failure stops
+ anything new from starting and the failure first in report order is the one thrown. A failed pass does
+ not wait for the page checks' early reads (a hung `pac` run would turn a fast failure into a hang): the
+ early read and the check that consumes it both stop waiting once a check listed BEFORE the page check has
+ failed. A failure in a check listed after it does not end the wait — the page check's own failure is the
+ lower-numbered one and must be the one thrown, as when the checks ran one at a time. A read the pass gave
+ up on is ended before the pass returns or throws: `verifySpec` calls the reader's `endPageReads()`, which
+ ends every `pac` run in flight with its whole process tree (`killProcessTree` — `pac` can be a `.cmd`
+ shim, and Node's own kill reaches only the `cmd.exe`), starts no new run — a listing paused between two
+ attempts included: the pac client's `abort()` makes every run of a call that began before it answer
+ "ended" without starting anything — and makes no download folder until the next pass begins, and waits
+ (bounded) for the downloads in flight to remove their `verify-page-*` folders — the verify CLI exits the
+ moment the pass does. Reads that several
+ checks share are single-flight: the root business unit (`resolveRoleBusinessUnit` caches the *lookup*
+ in flight — caching only its answer made every concurrent caller but the first report its role
+ missing), a table's and a role's privileges, the sitemap, the resolved Main forms. The reader sends the
+ first read of each table alone, so the SDK resolves its `EntitySetName` once instead of once per
+ overlapping read. The page checks' slow reads (the `pac` listing, the manifest) start with the pass,
+ and the code of every page whose navigation is checked comes from `readerFor().pageCodes`: one
+ `pac model genpage download --page-id a,b,c` per chunk of 25 ids instead of one run per page. A page the
+ batch cannot answer (a failed batch, an id with no directory in the output) is asked for by itself, so
+ one bad page costs its own miss, never its neighbours'.
+ - **check-auth** starts `az account show` and (with `--env`) the Dataverse token read together, and
+ WhoAmI as soon as the token is ready, so it overlaps the `pac` probe. The verdict order is unchanged
+ (account → token timeout → pac → no environment → WhoAmI), and an early verdict cancels the probes
+ still running — on Windows the token read's whole process tree (the `cmd.exe` that runs `az.cmd`, and
+ the Python process it starts), through `killProcessTree` in `lib/process-runner.js`, because Node's own
+ abort signals only the `cmd.exe` wrapper. The early WhoAmI is sent with `refreshOn401: false`: a 401
+ would otherwise refresh the token with a synchronous `az` call (seconds, with every other probe's timer
+ frozen), so a 401 on the early request is re-sent at WhoAmI's old place, after `pac`, where that refresh
+ costs nothing.
+ - **Download** overlaps each table's auxiliary reads (entity and attribute labels, the money
+ base-currency flags, option sets) and the per-table relationship reads, bounded at 4
+ (`runDownload({ concurrency })`; `1` is the sequential oracle), and merges them in the original fixed
+ order, so the written spec, pages and stderr are byte-identical. Tables themselves are still read one
+ at a time (the SDK's `fetchEntityMetadata` already fans out), and dashboards are not overlapped.
+ - **Teardown** saves the default-view resets with `publish: false` and publishes ONCE, in one
+ `publishArtifacts` envelope, at a barrier after the last reset and before the relationship deletes. A
+ failed envelope is retried table by table with `publishArtifact` (the SDK fails every target of an
+ envelope with one shared error), and a table that still cannot be published is named in a warning —
+ teardown does not fail on it. A single table keeps the one-table publish.
+ - **Data model** (`provisionDataModel`): a NEW table is created exactly as the previous release created it — one
+ request that carries only its primary name attribute — and its ordinary columns (Text, Memo, the number types,
+ Money, DateTime, Boolean, Choice and MultiChoice with inline options, AutoNumber; at most 25) then follow in ONE
+ atomic change set instead of one request each: the SDK's `createColumns`, an OData `$batch` of POSTs to the table's
+ `Attributes` collection. Dataverse runs the operations in order and, if one fails, rolls back the ones already done
+ ([change sets](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/execute-batch-operations-using-web-api#change-sets)),
+ so a refused change set has created nothing, and the build then creates the columns one by one as it always did,
+ with a warning that says why (the platform's own message when its answer carries one). The same fallback covers a
+ transport that cannot send a change set — the SDK refuses before sending anything when its HTTP client has no
+ `postRaw` (`DataverseClient.supportsAtomicBatch`; `lib/sdk-http-client.js` has it) — and a change set whose answer
+ was lost or could not be read (a transport failure, a server error, an unreadable success), which may have
+ committed: the table is read once, and when it has EVERY column the change set is taken as committed and its
+ columns are narrated as created, with their ids, after a warning that the answer was lost; otherwise each column
+ already there answers "already exists" and is skipped, so a lost answer costs requests, never a column or a
+ duplicate. A refusal (any 4xx) is not followed by that read. The HTTP client sends the change set again
+ only when its answer is a 429 — the platform refused it, so nothing in it committed (the change set is atomic), as it can while the table
+ just created is still held by its customization lock — on the schedule of any other throttled write (six attempts,
+ 1 s / 2 s / 4 s / 8 s / 8 s with jitter, longer when `Retry-After` asks, `isColumnCreateBatch` in
+ `lib/sdk-http-client.js`). It never sends it again after another transient status or a lost answer (a change set can
+ commit behind those), so such a refusal costs one request and then the per-column path's own 429 retries, never a
+ burst; 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
+ the table's own create request, which Dataverse also accepts (an `Attributes` array beside the primary name
+ attribute, [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
+ differently (see the next bullet). The SDK builds each operation's body with the same function `createColumn` uses,
+ so a column's body is its per-column body — `table-columns-in-create.test.js` compares them column by column and,
+ where `MODEL_APPS_RELEASED_SCRIPTS` names the `scripts` directory of the previous release (the CI job that installs
+ the parser oracles sets it), with the requests the
+ released code itself posts — and each operation carries the solution header (the one on the outer `$batch` request is
+ ignored by the platform). Customer, File, Image, Calculated, Rollup and global-choice columns, columns past 25, and
+ every column of a table that already exists, or that was found after its create (the answer to the create was lost,
+ so nothing shows what it holds), keep the one-request-per-column path. A column also stays out of the change set
+ when its name is one the platform would create twice — the primary name, `<table>id`, a companion of a column of the
+ table (a Money column's `<name>_base` twin, a Choice, MultiChoice or Boolean column's `<name>name` shadow, reserved
+ even when that column takes the per-column path itself), or a repeat of an earlier name in any case — because
+ Dataverse then refuses the WHOLE change set
+ ([0x80060304](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/web-service-error-codes),
+ "Attribute {0} already exists for entity {1}.") where the one-by-one path meets the collision in one
+ column's own request and skips it. A column whose name EXTENDS the name of a column that takes the
+ per-column path (Customer, File, Image, Calculated, Rollup, global-choice) stays out as well, and the
+ build does not try to list what the platform makes beside such a column: `<name>name`, `<name>yominame`
+ and `<name>idtype` beside a Customer column (measured), `<name>_name` beside a
+ [File column](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/file-column-data#file-name-column),
+ `<name>id`, `<name>_timestamp` and `<name>_url` beside an
+ [Image column](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/image-column-data#download-url),
+ `<name>_date` and `<name>_state` beside a
+ [rollup column](https://learn.microsoft.com/en-us/power-apps/maker/data-platform/define-rollup-fields).
+ Such a column is made AFTER the change set, so a twin inside it would be made before its owner and the
+ owner's own create would answer "already exists" — a skip — dropping the owner without a word, where one by
+ one the owner comes first and the twin is the skip. The twin is made in spec order after the change set, as
+ before; a longer name that merely starts like its neighbour's costs one request. The mirror rule keeps the order
+ the spec's for the columns that DO go in the change set: one by one the first column to name something creates
+ it and the next is skipped, so when a twin is listed BEFORE its owner the twin is the column kept — and the
+ change set, which runs before every per-column create, would reverse that. A column therefore stays out of the
+ change set when an earlier column has a name that extends its own — every name a column's creation can take
+ (a companion listed for it, or one the platform makes that the build does not know) is named after the column —
+ and is made after that column, in spec order; where an earlier column merely starts like a later one's name that costs one
+ request. One narrow
+ read of the table's `Attributes` (ids and names, no labels) then confirms the columns and returns the ids
+ `createColumn` would have (a change set answers none), keyed by the column object, never by its name: a second
+ column of exactly the same name is a repeat, skipped as already existing and never given the first one's id. A
+ column the read does not show — unreadable, lagging, or ignored by the platform — is created the per-column way,
+ where an already-exists answer is a skip. A table whose create answer was lost and that is found afterwards
+ is given no change set. Used only when the SDK has `createColumns` and a raw Dataverse client is there to read the
+ columns back (`inlineEnabled`); otherwise every column takes the per-column path.
+ - **Primary name column length.** Every table create sends the primary name attribute's `MaxLength` explicitly: the
+ spec's `primaryAttribute.maxLength` (a whole number from 1 to 850, one rule — `primaryNameLengthProblem` in
+ `lib/app-spec.js` — applied by `validateAppSpec` AND by the provision-entities input gate that `/genpage` and
+ `/app-builder` pass through), else 100 — what the previous release always sent (it is the SDK's own default for the
+ option), for a plain and an auto-numbered name column alike. So a spec without a length posts the previous release's
+ table request byte for byte and gets its result on every environment. What an environment makes of the length asked
+ of a create that carries only the primary name attribute was measured on two: one keeps it (100 → 100); the other
+ makes a plain text name column 850 characters long whatever length is asked (100 and 120 both came back 850) but
+ keeps the length asked of an auto-numbered one (100 → 100), and keeps the length asked in a create that also carries
+ other columns (120 → 120) — which is why the columns are not put in the table's create: no one length asked of such
+ a create matches the previous release on both environments. More than 850 is refused (HTTP 400, "The maximum length
+ of Primary attribute '…' is 4000. The maximum allowed limit is 850." — measured in a create that carried other
+ columns), and a PUT of the finished column — the SDK's `updateColumn`, with `MSCRM.MergeLabels: true` — is honored
+ (850 → 120 → 850). So when the spec gives a length and THIS build created the table, it reads the length back with
+ one typed `…/Attributes(LogicalName='…')/Microsoft.Dynamics.CRM.StringAttributeMetadata?$select=MaxLength` GET and
+ calls `updateColumn` only when it differs — LAST in the data-model phase, once every table, column, status reason,
+ alternate key and relationship has been created, and inside a `finally`, so that a phase that halts after creating a
+ table still sets that table's length (a re-run finds the table and leaves an existing table's name column alone; a
+ length that cannot be set while the phase is halting is warned about as one a re-run will not set either).
+ Last, because `updateColumn` starts by reading the column WITH its labels, and a label-bearing metadata read ahead of
+ a labelled create is what strips non-base languages (measured; see `findExistingColumns`): within one attempt, nothing
+ labelled is created after it. 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 has already set its length (the `finally` runs after a halt too), and
+ the retry finds the table and keeps its name column as it finds it, so the length is set once — but what the retry
+ creates comes after the first attempt's read, and the loss was measured only for a create straight after the read, so
+ whether it reaches across the pause between two attempts is not known (`table-columns-in-create.test.js` pins what
+ each attempt does). That is one narrated `primary column length` step, planned (after the relationships) and counted
+ only when the spec gives a length (`planFor`, and the provision-entities plan and total): `ok … -> N` when it set the
+ length, or a skip — `(already N)`, `(table exists — kept)` or `(table found after its create — kept at N, asked M)` —
+ or a FAILED step naming the table, the length asked and the length the platform made (for a read as well as an
+ update), with a warning, that never stops the build. There is no read for the default: a spec without a length
+ leaves the column as the environment made it, which is what the previous release did. A rebuild leaves an existing
+ table's name column alone, like every column's `maxLength`, because it must not shorten a column that may hold data
+ or undo a length widened in Maker. A table found after the answer to its create was lost (or that another maker
+ created first) is treated as not made by this build, since nothing shows that it was not made by someone else, so
+ its column is never written — but it is read, once, and a length that differs from the spec's, or cannot be read, is
+ a warning (`reportFoundPrimaryNameLength`). And a build that stops on `TABLE_METADATA_NOT_VISIBLE` out of the create
+ warns that the length asked may not have been applied (some environments make a name column created this way 850
+ characters long), since the re-run that follows treats the table as an existing one — except for an auto-numbered
+ name column, which keeps its length, and for 850, which the column comes out as either way. The
+ build reads only `schemaName`, `displayName`, `autoNumberFormat`, `required` and `maxLength` from
+ `primaryAttribute`; any other key inside it is still accepted and ignored (unlike the table level, it has
+ no key allow-list).
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
@@ -799,7 +1418,7 @@ scripts/
launch-playwright-mcp.js ← Playwright MCP server launcher (fullscreen; uses lib/detect-browser.js)
playwright-mcp-fullscreen.config.json ← Fullscreen browser config for the launcher
regenerate-verified-icons.js ← Regenerates references/verified-icons.txt from npm
- check-auth.js ← Pre-flight: az present + logged in, pac identity, WhoAmI, identity match (pac overlaps the az probes); a CLI too slow to answer is `az_timeout`/`pac_timeout`
+ check-auth.js ← Pre-flight: az present + logged in, pac identity, WhoAmI, identity match (the az probes, the token read + WhoAmI and pac overlap; the verdict order is fixed); a CLI too slow to answer is `az_timeout`/`pac_timeout`
check-version.js ← Skill-start update notice: compares the plugin clone with its origin/main (git runs in the plugin, never the user's repo)
resolve-interaction-mode.js ← Reports whether a human can answer in this run (unattended defaults)
lint-app-spec.js ← Validate + lint an App Spec without touching an environment
@@ -807,6 +1426,7 @@ scripts/
list-connections.js ← Connector discovery: PAC connections + Dataverse connection references
create-connection-reference.js ← Creates Dataverse connectionreference rows for connector bindings
list-custom-apis.js ← Discovers bindable Custom APIs (Global + entity-bound) + parameter kinds (custom-api gated)
+ list-languages.js ← /genpage planner: the environment's base language and each provisioned language (LCID, culture code, right-to-left) — the SDK's `getEnvironmentLanguages()` over the az-token client, three reads and no write, printed as one pure-ASCII JSON line. The planner's FIRST choice: when it exits non-zero, for any reason (most often the Azure CLI), the planner runs `pac model list-languages --environment '<envUrl>'` instead (as before the script existed, but pinned to the same environment), and says so
add-page-to-solution.js ← Adds GenPages and optional connection references to a solution
provision-entities.js ← CLI wrapper for entity provisioning (solution + data-model + sample-data; --language-code)
provision-solution.js ← Creates a Dataverse solution via the SDK
@@ -823,33 +1443,40 @@ scripts/
run-tests.js ← one-command plugin + SDK regression runner
smoke-eval.js ← scripted live smoke eval (build → assert → teardown)
generate-page-manifest.js ← Phase 0.5: writes working-dir package.json + genpage.d.ts
- genpage-upload.js ← /genpage: deploy one page via the shared wrapper (prompt passed BY FILE, never on a command line; an update must name the app the page is placed in, and keeps the page's name, model and bindings unless given; refuses no-base / deployed-changed / deployed-unreadable unless --overwrite-deployed)
+ genpage-upload.js ← /genpage: deploy one page via the shared wrapper (prompt passed BY FILE, never on a command line; an update must name the app the page is placed in, and keeps the page's name, model and bindings unless given; refuses a create whose `makeStyles` writes a Griffel shorthand (`griffel-shorthand`, before anything is read) and an update that ADDS one the deployed page did not already have — one it already had goes ahead with a warning — and, for an update, no-base / deployed-changed / deployed-unreadable unless --overwrite-deployed)
genpage-base.js ← /genpage: record or check the deployed-page base marker next to a page.tsx (#673)
genpage-plan-provenance.js ← /genpage: quarantine a stale plan before the planner writes, then verify the written plan targets the pages the approval named and, for an edit, carries the exact approved change list
check-page-files.js ← /genpage: pre-dispatch gate — the page file names of the plan's one ## Pages table are safe write targets (lib/page-file-targets.js)
genpage-worker-output.js ← /genpage: accept a parallel worker's page only if complete (default export, balanced, no elided code)
+ 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 runners
lib/
- entity-provision.js ← Shared entity-provisioning core (solution + data-model + sample-data)
- provision-input.js ← Input validation for entity provisioning
- dataverse-auth.js ← Shared auth + HTTP helpers (`az account get-access-token`, memoized per process and replaced on a 401; responses decoded as UTF-8 once; an environment URL is used only as a Dataverse https origin, `dataverseOrigin`), plus the CLI arg contract (parseArgs/validateFlags)
- 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)
- cli-failure.js ← how a CLI child failed (timeout / missing / failed) and the Azure CLI budget (60 s, `POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS`), so a slow `az` is never reported as missing or signed out
+ entity-provision.js ← Shared entity-provisioning core (solution + data-model + sample-data): a new table is created with only its primary name attribute and its ordinary columns follow in one atomic change set (`createColumns`), falling back to one request per column; the primary name column's length is always sent (100 unless the spec gives one) and, where the platform did not keep a length the spec gave, set last in the phase; and `mapLimit`, the bounded fan-out every parallel path reuses
+ provision-input.js ← Input validation for entity provisioning (the entry gate of `/genpage` and `/app-builder`; it applies `app-spec.js`'s own `primaryNameLengthProblem`, so a name-column length is refused here exactly as in `validateAppSpec`)
+ 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; 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`), plus the CLI arg contract (parseArgs/validateFlags) 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); `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
+ 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, and the budget of one `pac model genpage` call (3 min to list or download, 10 min to upload; `POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS`, 1 s to 60 min, sets all of them); `commandArg` writes an argument of a command a message tells you (or the agent) to paste so that, run from PowerShell (Windows PowerShell 5.1 or PowerShell 7) or a POSIX shell, the program gets it unchanged as one argument — bare when it is plain, single-quoted otherwise (a path from an untrusted checkout can hold `;`, `$(…)` or backticks) — or not at all when no spelling does that in every one of those shells: a quote or a line break, and the values Windows PowerShell changes on their way to a native program (a `"`, white space with a final `\`, the empty value) or both PowerShells read as the stop-parsing token (`--%`), all measured. `commandArgOrPlaceholder` then writes a placeholder and names the value outside the command
nearest-name.js ← pure single-edit "did you mean" matcher for closed vocabularies (CLI flags, FetchXML operators)
+ lcid-cultures.js ← pure: a Windows language id (LCID) → culture code and right-to-left, from a table of Windows' own culture data (what `pac` printed; the SDK reports numbers only, and no Intl API maps an LCID); a language id with no entry stays numeric and is reported, never guessed (`list-languages.js`)
supported-dependencies.js ← Single source of truth for runtime + dev deps versions
feature-flags.js ← Default-OFF feature flag probe + Custom API script backstop
sdk-build.js ← app-builder build engine (idempotent; incl. the pages phase)
app-components.js ← shared current/published app layers, component inventory, hidden-table pin/proof, Main-form resolution/membership and push directives
+ solution-membership.js ← one read of a solution's components (the types the build adds, plus its tables: a table held with all its subcomponents vouches for its views, forms and charts, which have no rows of their own), so a rebuild adds just what the solution is not PROVEN to hold; every doubt reads as "add"
+ unsynced-edits.js ← the SDK's own dirty tracking (`diffArtifact`) as the one proof that a reconcile has nothing to push; every doubt reads as "push"
stages.js ← stage→phase-range mapping + PHASES/STAGES constants
op-diff.js ← destructive-op diff + --allow-destructive / --non-interactive gating
artifact-intent.js ← pure App Spec → canonical SDK intent compiler (new form topology; no SDK calls)
form-occupancy.js ← pure row occupancy (own cells + columns reserved by row-spanning cells above), shared by build and verify
+ form-timeline.js ← pure: the shape Dynamics renders the Notes timeline in (control id, tall cell, spacer rows), what a deployed one lacks, and how to read it in the SDK tree and in published FormXML (shared by the compiler, the build's repair and verify)
+ form-subgrid-placement.js ← pure: where a form's sub-grid sections go (`tab`/`column`/`after`/`before`) — resolving a placement against the declared layout, the order of a column's sections and grids, finding a grid's section in either tree shape (shared by the spec gate, build, verify and the wireframe)
form-order.js ← the Main Form Set order: which Main form a table opens with, and which forms the build orders (shared by the spec gate, build and verify)
form-container-match.js ← how an authored tab/section is matched to a deployed one, and the moves that put them in the layout's order (shared by build and verify)
ai-app-settings.js ← single source of truth for the per-app AI feature contract
interaction-mode.js ← whether a human is reachable in this run (shared by both skills)
page-plan.js ← pure App Spec → plan-document projection used by write-page-plan.js
page-structure.js ← the one structural gate a generated page must pass (empty, truncated, prose, elided), shared by genpage-worker-output.js and promote-intent-pages.js
+ griffel-styles.js ← the ten shorthands Griffel's runtime drops, found as keys of a `makeStyles` style object (any depth, code only — the plugin's own lexer), with their longhands and where each sits (`within`: its slot, selectors and at-rules); shared by check-griffel-styles.js, `genpage-upload.js` (refuses a create, and an update's NEW keys — `griffelProblemsNotIn` tells them from the deployed page's) and the build's pages-phase scan (halts a new or changed page, warns for one it sends as it is), whose texts (`describeGriffelRefusal` / `describeGriffelWarning`) say what each way out does to the page; and the tests
page-file-targets.js ← the one page-filename rule (absolute/backslash/traversal/.tsx only/links/case collision, incl. with files already there), shared with check-page-files.js and the evals
app-source-path.js ← shared lexical + realpath confinement for app source reads/uploads and hashes
page-ownership-records.js ← local CREATE receipts and pre-delete ownership records, scoped to app/key/id
@@ -857,16 +1484,18 @@ scripts/
sdk-teardown.js ← app-builder teardown engine (planTeardown is pure)
sdk-http-client.js ← az-token HttpClient for the vendored SDK
spec-lint.js / app-spec.js ← App Spec guardrail lint + validation
+ lookup-labels.js ← a lookup column's default label, environment-facing half: the parent table's label read, the old-default repair's column-label read (one per child table) (the pure rule is `lookupLabelFor`, app-spec.js); `lookup-cell-labels.js` repairs the form cell
+ view-filter-labels.js ← resolves a view filter's Choice labels against the environment's option metadata; the build's pre-flight (skipped for a spec with a localized label) and views-phase gate, the dry run, verify and lint all use it
spec-shape.js ← shared structural normalization for both authoring gates
surface-resolver.js ← pure: resolve personas[].jobs[].surfaces[] to the spec artifacts that satisfy them
role-privileges.js ← pure: declared persona privileges + subset comparison against a deployed role
(also the oracle for `roleGrants[]`, which is additive rather than converged)
odata.js ← OData literal escaping helpers
- genpage-cli.js ← pac model genpage upload/list/download wrapper, plus a page's own name read from its row (pac stores `"` as `\"`; `unescapePacName`); an uncertain create reports its candidates and stops without adopting one as an UPDATE
+ genpage-cli.js ← pac model genpage upload/list/download wrapper, plus a page's own name read from its row (pac stores `"` as `\"`; `unescapePacName`); an uncertain create reports its candidates and stops without adopting one as an UPDATE. Every pac call is time-bounded (`runPac`: the process tree is ended when the budget runs out and the result is `{ status: null, timedOut: true }`); a timed-out list or download is retried once, a timed-out UPDATE is not (it may have landed, and a re-send can record the prompt twice or overwrite a later change: it is reported with the check to run — `genpage-base.js check` for the upload script, a `pac model genpage download` of the page and then a re-run of the build for the build, which keeps no base marker), nor is an UPDATE that failed (a non-zero exit, or an exit 0 with no Page ID: it too may have landed, and is reported the same way; only a refusal of pac's own arguments or input files is an ordinary error), and a timed-out CREATE is an uncertain create that is never run again (a Page ID pac had printed names the page it created, stalled before publish or placement; a create that fails after the Page ID is reported the same way and never sent again; every error that follows a create whose outcome is not known to be nothing carries `transient: false`, so the build's own retry of a halt that reads as transient cannot re-send it, while a create that failed outright and left nothing in the listing is retried, as in 2.13.0); `runPac` also takes an AbortSignal and the client's `abort()` ends the pac runs it has in flight, each with its whole process tree (through the same `killProcessTree` as a timeout), and keeps a call that is paused between two attempts from starting another (an attempt that was ended is not followed by another pause either, and an ended upload is never sent again; a verify pass ends the page reads it gave up on this way)
genpage-base.js ← base-marker hash, compare, and read/write (sibling dotfile of the code file; no environment URL)
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. Shared by genpage markers and later callers
hydrate-spec.js ← reconstruct an App Spec from a deployed app (edit flow)
- verify-spec.js ← spec-vs-deployed reconciliation core
+ 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 renderer
app-preview.js ← whole-app design renderer (data model + sitemap + forms + page-intents + design)
@@ -874,20 +1503,21 @@ scripts/
schema-facts.js ← pure data-model provisioning fact extractor for evals
pageref-resolver.js ← PAGEREF_<key> → GenPageId nav resolver
page-manifest.js ← durable <app>_pagemanifest read/write
- sitemap-pages.js ← pure GenPageId extractors + fail-closed fetchSitemap MEMBERSHIP reader + navigationProof (page ownership proof from either app layer) + cross-app scan
+ sitemap-pages.js ← pure GenPageId extractors + fail-closed fetchSitemap MEMBERSHIP reader + navigationProof (page ownership proof from either app layer) + 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)
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 make
- deployed-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
+ deployed-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
ai-prompt.js ← generates tailored Copilot row-summary prompts
_graph.js ← entity topological ordering (shared by build + teardown)
system-solutions.js ← built-in system solutions (Active/Default/Basic) — shared by download recovery + teardown skip
phase-diff.js ← pure spec-diff → changed build phases (advisory diff foundation)
- content-hash.js / hash.js ← content-aware phase diff: fold on-disk .tsx/contentPath byte hashes into the diff (changed-only)
+ 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 debt
apply-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
apply-snapshot-index.js ← changed-only: build result.created → snapshot artifact map
workspace-paths.js ← the `.maker-workspace` name + the guard that gates destructive --clear-workspace cleanup
+ workspace-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
changed-only-flow.js ← changed-only: --changed-only orchestration (decide fast/full, live identity, snapshot lifecycle)
projection.js ← changed-only: pure post-apply verifiers (form placement / sitemap / page dual-hash)
detect-browser.js ← System Chromium/Edge/Chrome detection (used by the launcher)
@@ -944,6 +1574,21 @@ Agents are invoked by skills via the `Task` tool — they are not user-invocable
Generative pages (genux) are React 17 + TypeScript single-file components that run inside model-driven Power Apps. They use Fluent UI V9 for styling and the DataAPI for Dataverse data access. Each page is a single `.tsx` file with `export default GeneratedComponent`.
+### Griffel shorthands
+
+Fluent UI V9 styles are Griffel's, and Griffel's runtime silently drops ten shorthands from a `makeStyles` style object — `all`, `borderColor`, `borderStyle`, `borderWidth`, `borderBlock`, `borderBlockStart`, `borderBlockEnd`, `borderInline`, `borderInlineStart`, `borderInlineEnd` (`UNSUPPORTED_CSS_PROPERTIES` in `@griffel/core`; it skips the key and logs a console error). A page that writes one type-checks, transpiles, deploys and renders without it (AB#6691124); the guard used to be a grep for `borderWidth`, one of the ten. `scripts/check-griffel-styles.js --file <page.tsx>` is the gate now (the rule is `lib/griffel-styles.js`): one JSON line, exit 0 clean / 3 problems / 1 usage or an unreadable file, each finding with its line, column and the longhands to write (and where it sits, `within`, and what it is set to, `value`, which `genpage-upload.js` compares with the deployed page).
+
+- **What it reads.** Every key of every slot's style object at any depth (`':hover'`, `'@media …'`, nested selectors; quoted, spaced, computed-from-a-string and escaped keys; `{ borderColor }` shorthand members; objects written inline in a spread), in code only — the plugin's own lexer (`source-literals.js`) masks strings, comments, templates, regexes and JSX text, so the same names there, and in an inline `style={{ … }}`, are not keys. Slot names are not properties, and an `animationName`'s keyframes are serialized as written, so neither is reported. `makeStyles` is found under its own name, an `import { makeStyles as ms }` alias and a `Fluent.makeStyles` namespace import from `@fluentui/react-components`, `@griffel/react` or `@griffel/core`.
+- **`makeResetStyles` is not checked, on purpose.** The work item names it, but `resolveStyleRules` is the only code that consults the unsupported set, and `makeResetStyles` goes through `resolveResetStyleRules`, which writes every key as given (`@griffel/core` 1.19 and 1.20: `makeStyles` drops `borderColor`, `makeResetStyles` emits `border-color:red;`). Refusing a page that works would be a false reject. To check it too, add `['makeResetStyles', { slots: false }]` to `STYLE_FUNCTIONS`.
+- **A style object the check cannot see is a problem, never a pass.** `makeStyles(styles)`, a slot or a selector given a variable (`root: base`, `':hover': hover`), and a spread of anything but an object written inline (`...base`, `...helper()`, `...(a || { … })`) are each `unread-style-object` — the keys behind them may be any of the ten — and the gates treat it as they treat a call the check cannot read: refused on a create or a change, warned for a page sent again as it is. So is a getter that runs, whatever key it defines (`get root() { return … }`, `get color() { … }`, with or without a space after `get`): Griffel calls it as it reads the key and a spread as it copies its object — even one whose value a later definition then replaces — and its body is code the check does not read, which may return anything and rewrite or delete what Griffel reads after it; a getter that never runs (replaced in its own object before anything reads it, or inherited under an own key) is not reported, and nor is one whose object never reaches Griffel (in a value a later definition replaces, in a prototype a spread does not copy, in an animation's keyframes), though a spread or Griffel may run it — its own object is all it can change there. Code that writes shared state (`Object.prototype.borderWidth = …`, a property of an import, a variable) changes what every object holds, as a statement anywhere else in the page could; no check of the style objects can see it, and this one does not follow it, wherever it runs (a getter's body, a Proxy's trap or a `toString` Griffel calls on a fallback value, a template's substitution) — the gate checks what a page asks Griffel for, not code written to get past it. So is a computed key the check cannot read as one string (`[key]`, `['border' + 'Width']`), which may name one of the ten or a selector — unless it is a template whose text before its first `${` no one of the ten begins with (`--${name}`, `& .${className}`, `@media (min-width: ${width}px)`), in which case its start tells what it is, and the object under one that starts as Griffel's nested keys do (`:`, `[`, `>`, `&`, `@`) is read. What a spread or a prototype (`__proto__: { … }`) brings into an object is read at that object's level — slots beside slots — and the object is resolved as JavaScript resolves it: a key's last definition is the property, own keys hide inherited ones, a spread copies only its object's own keys, and a key is the string JavaScript makes of it (a CR LF or a lone CR written in a template is one LF, however the file ends its lines; U+2028 and U+2029 stay as written), so a definition that provably never reaches Griffel is not checked, while one that may (a spread a condition chooses, a key computed at run time) is. A function member ends where its body closes, not at a comma of its type parameters or return type. Read in full: an object literal, or object literals chosen by a condition (`c && { … }`, `c ? { … } : { … }`), through parentheses, a non-null `!` and `as`/`satisfies` with a type the check reads — `as const`, or a type name with or without type arguments (no page wrote a cast in `makeStyles` at all); a keyword or literal type (`number`, `null`, `this`, …) ends at its word, so a `<` after it is a comparison; any other type leaves the value unread, so a type is never read as a value — for a slot, a selector, a spread and the call's own argument alike. Each `<` is matched to its `>` once per page (matchAngles), so a page of casts is read in linear time. Past 64 levels of nesting a value is unread and an object is reported as nested too deep, so a pathological page gets an answer rather than an exhausted stack. A number is read as a key (`{ 0: { … } }` is a slot), and a slot called `animationName` is a slot: only an `animationName` inside a style object holds keyframes. Spread without reading, alone or chosen by a condition, only as a value import from a Griffel module that the page never declares again (a read after `=` or `typeof` is not a declaration; an arrow parameter is), and only by the helper's own export names (`STYLE_HELPERS`: Griffel's 23 `shorthands` helpers and Fluent's 17 `typographyStyles` entries — never a name they inherit, since `shorthands.constructor(x)` is `Object(x)` and hands x back unexpanded; and `shorthands.transition` only where it builds its own array — any number of arguments but one, none of them a spread, or one array, string or number written in place — since given one array it returns what that array's own `reduce` returns): Fluent's `shorthands.*(…)` (it writes the longhands) and `typographyStyles.*` (font longhands only). Measured before the rule: no page among the samples, eval fixtures and pages generated on real environments (59 distinct) wrote a style object anywhere but inline, computed a key or wrote a getter, and the only spreads were `shorthands.*(…)`.
+- **Lexer uncertainty fails closed**, as in the navigation oracle: a call that reaches the first place the lexer guessed what a `/` or `<` is — or a `makeStyles(` in the text after it, which a wrong guess may have blanked — comes back as an `unverifiable-style-call` problem with the remedy; a call that never closes is `unbalanced-style-call`. No committed page hits a guess (`source-literals.test.js`), so this costs a realistic page nothing.
+- **What the gates hold a page to.** The check is held against what a run is about to *ship*. A page deployed by an earlier release of the plugin — whose only guard was a grep for `borderWidth`, so `borderColor` under `:hover` passed — can already carry a key Griffel drops, and it renders without it today. Sending the same bytes again ships nothing new, and refusing them would stop a rebuild (or a one-line edit) over a defect the maker did not touch, with only one way through: edit the page, and writing the longhands *changes how it renders* (those declarations never applied; deleting the key keeps today's look). So every refusal and warning says both: *deleting a key changes nothing on screen; writing the longhands makes the style start to render*.
+ - **The build** holds no copy of what is deployed (and never downloads a page just for this), so it decides from the page's standing, in the pre-write scan, for each page the run uploads. A page that does not exist yet (`keyToId` has no id for it: it is *created*) and a page that exists but whose source no longer hashes to the `__contentSha` that `last-applied.json` recorded for it at the last apply (*changed*) are held to the check — `pages-griffel-shorthand`, before anything is written. A page whose source hashes to that record (*unchanged*), or that has no record (*unrecorded*), is sent as it is, and the build warns (`opts.warn`) with file:line:column and both remedies. The record is `last-applied.json` read as `opts.baselineSpec` — written by every successful full or changed-only apply and by download, and returned only for this app **in this environment** (`readBaseline`; a snapshot written before it carried those stamps is no baseline), the same hashes the changed-only flow compares. For a page an apply sent, the hash recorded is of the source the pages phase *read and checked* (`created.pageSourceShas`), not of the file when the baseline is written as the build ends: a page a maker saved while the build ran reads as *changed* on the next build, where re-hashing the files would have recorded the edit as applied and let a new key through on a warning. What is sent is what was checked: every page, a navigation source or not, goes to pac from a staging copy of the bytes the scan read (`writeStagingFile`), never from its own file, so a save made after the check does not ship until a build has checked it. A page a changed-only run did not send keeps the record it had (with none, the hash of its file as it is). *Unrecorded* — a new, moved or cleared workspace, another environment, or an apply that predates the record — fails **open** on purpose: the release before this check built such pages with the CSS silently dropped, so refusing one now would regress a rebuild that used to complete. The cost is that an edit that adds a key to an unrecorded page is warned about, not stopped, until a build has recorded it; a page that does not exist is always held, record or not.
+ - **`genpage-upload.js`** has the deployed page in hand (an update downloads it for its base check), so it refuses only what that page did not already have. A create is refused outright. For an update each key is told from the deployed page's by `griffelProblemsNotIn`: the same key set to the same value in the same place (`within`: its slot, selectors and at-rules), or failing that the same key and value anywhere that nothing else has claimed — so a renamed slot or a moved rule is not new — and each deployed key is spent once, so a second `borderColor` where there was one is. A key given **another value** is new too: Griffel drops the new value as it dropped the old one, so the page would show none of the change the maker meant (a value is compared as written — a quoted string by its text, whichever quotes, anything else as its source text with the white space collapsed — and nothing is evaluated, so `tokens.colorBrandStroke1` is that text). A file that *is* the deployed page (a BOM or final CRLF aside) is a re-send, and none of it is new. A key the deployed page already had goes ahead, with a `warnings` entry in the result; a new one is refused, and `--overwrite-deployed` is no way past that (it is about edits made to the deployed page, not about what the file writes). The deployed page can be unreadable only under `--overwrite-deployed`; nothing then says what it had, so the update goes ahead with a warning, as an unrecorded build page does.
+ - **A call the checker cannot read** is not CSS Griffel drops, and is not said to be: the message says the check could not read the page's styles, quotes the call, and says what to change in the code (parenthesise the operand, end the statement, or move the call above it). It is never "already there" — what it hides cannot be compared with anything — unless the file is the deployed page itself. And the checker command a message suggests quotes a path that has white space.
+ - **`check-griffel-styles.js`** has no notion of what is deployed: it reports every key it finds, a page's old ones included. For a page that already had one, deleting it is the edit that preserves the page (`/genpage`'s edit flow says so).
+- **Who runs it.** Three places, so no path to an upload skips it. The orchestrators run it per page, before any transpile or upload, for quick feedback: `/genpage` (single page, multi-page, edit flow, and the §7.5 fix after a browser verify) and `/app-builder` (before `promote-intent-pages.js`, and for a page edited by hand before a rebuild). The page-builder worker has no shell, so its Step 2.6 gives it the rule and a Grep self-review instead. And the code **enforces** it where pages are uploaded, whatever the instructions did or did not get run: `genpage-upload.js` reads the code file first and refuses a create with `code: "griffel-shorthand"` (file, line, column, longhands and what each way out does in `error`, the same list in `problems`; before any listing or download; a file it cannot read is refused) and, for an update, any key the deployed page did not already have (above), and the build's pages phase halts as `pages-griffel-shorthand` in its pre-write scan, before any page is created or updated, for each page that run uploads that is new or changed (a changed-only run checks only the pages it selects; a full build checks every implemented page). Both send `pac` what they checked, never the file again: the upload script reads the code file once and uploads a copy of those bytes (an update lists the environment and downloads the deployed page first — seconds in which the file can be saved), and its base marker records their hash; the build sends every page from a staging copy of the bytes its scan read, and records their hash. `genpage-upload.js` refuses `--compiled-code-file`, since `pac` would deploy that JavaScript instead of the checked TypeScript. Both build their text with `describeGriffelRefusal` / `describeGriffelWarning`, so one defect has one wording. It is deliberately not part of `genpage-worker-output.js` / `promote-intent-pages.js`: their failure sends the page back for a full rewrite, and this one is fixed by a targeted edit. The one rule text is the same in `references/rules.md`, the genpage skill and edit flow, the page-builder agent and the app-builder skill, and `genpage-dispatch-contract.test.js` fails if any drops it or the command (and if `verify-flow.md` or the app-builder edit step drops the check).
+
### DataAPI
The DataAPI (`props.dataApi`) provides typed CRUD operations against Dataverse tables. It uses RuntimeTypes.ts (generated by `pac model genpage generate-types`) for type safety. Column names must be verified from the generated schema — never guessed.
@@ -1134,13 +1779,21 @@ rejected a complete page saved with CRLF endings.
generated page may use them, and they are accepted in one place only. A parenthesised **callee** must wrap
exactly the callee (`navigateTo` or a member chain ending in it: `(Xrm.Navigation.navigateTo)(…)`) AND its `(`
must follow a token on an **allowlist** — the start of the source; `;` `{` `(` `[` `,` `:`; a ternary `?`;
- an operator ending in `=` (`=` `==` `===` `!=` `!==` `+=` `<=` `>=` …); `=>`; `&&` `||` `??`. It is an
+ an operator ending in `=` (`=` `==` `===` `!=` `!==` `+=` `<=` `>=` …); `=>`; `&&` `||` `??`; and the keyword
+ `return` (`return (navigateTo)({ … })`) on the line of the `(` — a line break between them makes `return;` a
+ statement of its own — as the whole word (white space, the start of the source or one of `;` `{` `)` `:` right
+ before it, so no `xreturn` and no `\u0061return`; `}` is not one, because `\u{61}return` ends in it) and not
+ after a `.` (a member named `return`). It is an
allowlist because the tokens that END a callable operand are many and easy to miss — `!` (a non-null
assertion), `>` (a generic instantiation), a back-tick (a tagged template), `}` (a function expression, which
a block's `}` cannot be told from), a name or keyword, `)`, `]`, `.`, `?.`, `++` — and each makes
`(navigateTo)(…)` an argument list: `factory!(navigateTo)(…)`, `factory<unknown>(navigateTo)(…)`,
``tag`x`(navigateTo)(…)`` and `function () { return f; }(navigateTo)(…)` hand the object to whatever
- `factory`, `tag` or the function returns. (A denylist of those tokens missed four of them.) A callee group at
+ `factory`, `tag` or the function returns. (A denylist of those tokens missed four of them.) `await` and
+ `yield` are **not** on it, although `await (navigateTo)(…)` is a navigation in an async function: outside
+ one — and in an arrow that is not async, inside an async function — `await` is a name, and the object goes
+ to what `await(navigateTo)` returns; the lexer cannot tell where it stands (the oracle test
+ in `pageref-resolver.test.js` holds TypeScript's reading and the execution of both). A callee group at
the start of a template expression, after its opening back-tick, is refused for the same reason. A
parenthesised **argument** is closed straight after the object (type-only casts may precede the `)`), and the
argument must then end at a `,` or the call's `)`: `navigateTo(({ … }))` is a call;
@@ -1218,7 +1871,9 @@ rejected a complete page saved with CRLF endings.
`<T extends /` opens type parameters, whose constraint is read as an expression where it starts no type
(`parseTypeParameter`), here a regex — `let f: <T extends />;…[/]/>(a: T) => T` is a function type — and the lexer
does not always know which of the two it is in, so `extends` and a `/` is the guess `generic`, read as the element
- (`/=` is another token, and type parameters in both). A lexer that searched for a parameter list and a later `=>` took the
+ (`/=` is another token, and type parameters in both) — unless the regex that the `/` would begin does not end on its line,
+ which no type-parameter list has (TS1161: TypeScript's scanner ends a regex at a line break, `regexEnd`), so `<Flag extends />`
+ with no other `/` after it on the line is the element's for certain. A lexer that searched for a parameter list and a later `=>` took the
JSX text `(a): Title` in `isVisible(<div data-active={e}>(a): Title</div>) ? (() => /navigateTo(…)/.test(t)) : …`
for parameters, and read the regex after the next arrow as code: a call, whose token was rewritten. Three
things go beyond the three-token rule, and a test checks each against TypeScript's parser when
@@ -1358,6 +2013,20 @@ rejected a complete page saved with CRLF endings.
it reads no `/`, `<` or back-tick (no regex, no JSX, no template: every quote is a string and every parenthesis code), so `<span>(@username)</span>` and
`<p>(x = 5)</p>` are read as before; once it reads one, the expression may hold a `)` of its own — a regex's, JSX text's, a nested template's — and
with no arrow after the `)` it found, the list is the guess (`interface I { <T>(a = /[)]/); m: '</T>…' }` ended the list at the `)` in the regex's class).
+ Three things are read exactly instead, because TypeScript reads each one way (`initializerReading` and the scan's loop), and none of them needs a parser:
+ the first token of the first default, where it is a `/` — nothing is there to divide, so it begins a regex, which ends at its own `/` on its line (`(a = /x/)`,
+ `(a = /[)]/)`; a line break before the closing `/` is TS1161, and no program that parses has it) — or a `<` that the arrow rule above leaves an element, which is read to its
+ closing tag (`(a = <b>c</b>)`); a `/` after a name or a number, which divides in an expression (`(a = b/(c))`, `(score = 3/5)`), unless a `{` has been read, which may open a function body, where a
+ statement starts and a `/` after a `)` may begin a regex; and a template with no `${`, which holds only its own text. The `=` must be an initializer's, so no `<` stands before it (it may be a
+ type parameter's `=` default, where a `<` opens a function type); an `=` that `</` follows is no default in any signature or function type (TS1109, TS1110), so `(Tip: use <code>=</code>)` is the
+ element's alone. A second default, a regex or an element that is not a default's first token (`(a = f(/x/))`, `(a = <b>c</b> / 2)`), a `/` after a bracket, a `)` or a comment of either kind, and a template
+ with a `${` stay the guess. A comment is trivia to TypeScript, so after one the last token is the one before it, and a `/` after one is a regex or a division by that token: a block comment ends in a `/`, which is no
+ word (`1 + /* c */ /[)]/`), and a line comment ends in whatever its text does — a name, a number, a `$` — which is no operand: in `a = 1 + // fallback` and a line break, `/[)]/)` is a regex whose `)` is not the
+ one that ends the list, and a scan that took the `/` for a division ended the list there and read the string of the type after it as code. The scan of a list does not find its comments one by one, so a `/` after a comment of either
+ kind is the guess there (`slashFollowsAnOperand`); the reading of the text after a signature opens its comments itself and judges a `/` by the token before them (below) — the same misread hid the closing tag of
+ `interface I { <T>(x); m(a = 1 + // c` LF `/[</T>;navigateTo(…)//]/): void }` in a regex, and read what followed as code. The character before a line break is in a line
+ comment only if a `//` stands before it on its line (`lineMayEndInComment`), so a `/` after a name or a number on a line that holds no `//` still divides (on a line of its own after a comment's line, too); the `//` of a
+ string, which a line may begin inside of, is not told from a comment, nor is a line that begins beyond the window: each is the guess too, the safe side.
A list that can hold no parameters is
the element's alone, with a `:` after it or without: its first token a number, a string, a template, a `#` or an operator
(`<li>(1): First</li>`) is TS1003 in every signature and function type (`parameterListMayStart`; a character beyond ASCII and a
@@ -1374,7 +2043,11 @@ rejected a complete page saved with CRLF endings.
type after `is` is read the same way (`this field` fails, `this is string` does not); a type reference's first type argument is read the same way
(`see<a href` fails at `href`); a name after a generic function type's first type parameter is TS1005 unless the first word is a modifier, which
TypeScript parses there whatever it is (`<private x>`); and a type that is one name and a `,` lets the next parameter be read as the first was
- (`(Type: string, <a href="/x">docs</a>)` fails at the `<`). Tests measure the classes over every keyword TypeScript has, every keyword before every
+ (`(Type: string, <a href="/x">docs</a>)` fails at the `<`). Four more types fail at their own second token, each measured over every keyword after it: a number
+ literal and a name that is not a conditional's `extends` (`(Size: 10 MB max, <a href="/x">upgrade</a>)`: TS1005; the number may be negative or have a fraction, and white space or a comment follows it);
+ an object type whose first member is a name and then a `.` or an operator no member has (`(Name: {user.name}, <a href={profile}>edit</a>)`: TS1131, a line break and a comment
+ before it as well; a `.` and a digit is a numeric name, so it is no failure); `new`, which a `(` or a `<` must follow (`(Mode: new <a href="/x">beta</a>)`, and after the `<` the type parameters are read
+ as above); and `import`, which a `(` must follow (`(Hint: import <a href="/x">docs</a>)`). Tests measure the classes over every keyword TypeScript has, every keyword before every
other one, and every two-word type start and second parameter with the endings that could complete it. One place settles even those: **directly after the head of a type alias, `type Name =` at a
statement start** (after any `export` and `declare`), where `type Name` — two names side by side — cannot be
an expression, so a `<` is a function type's type parameters, for certain, whatever follows it
@@ -1394,7 +2067,14 @@ rejected a complete page saved with CRLF endings.
U+0085, U+00A0 or the like). Where anything else follows on the line — a name, a `<`, a `(`, a `{`, a comment with
no line break — no signature stands there and it is an element, for certain, and so it is where a closing tag
follows (`</` is one token in a `.tsx` file): `<b>(optional)</b>`, `<p>({t("label")})</p>`,
- `<span>(total: {count})</span>` are decided by that token alone. *Where the member may end there, the text after
+ `<span>(total: {count})</span>` are decided by that token alone. **Where no member of a type can begin at the head, there
+ is no signature at all**: right after an `=` or a compound assignment (`+=`, `||=`, …), an `=>`, a `(`, a `[` or a `:`
+ (`NO_MEMBER_BEFORE`) a call or construct signature, a method and an index signature cannot stand, and a function type needs the `=>` that
+ this shape lacks, so `<Name>(…)` that neither `=>` nor `:` follows is an element, for certain, whatever its text holds (`const help = <p>(optional);` and
+ a line break, then `foo( // note` and a line break, then `/docs</p>;`). After a `,`, a `;`, a `{`, a `}`, a `)`, a `?` or a keyword a member may begin — `return <T>(x)` is a method named `return`,
+ `m? <T>(x)` is a method with an optional mark, and TypeScript parses both, so neither a keyword nor a `?` is in the set — and the text is read as
+ follows. (The set was measured against TypeScript's parser over every place a token can stand: no program has type parameters with no
+ arrow and no `:` after a token of it, and a program has them after each token the rule reads that is left out: `source-literals.test.js`.) *Where the member may end there, the text after
`<Name>` is read as the children of an element up to its closing tag*, as (3) reads it up to an arrow (`readChildren`
with a closing name): the nested elements are followed, each closed by its own closing tag, a nested tag's attribute
containers and spreads are skipped, and an expression container that holds strings and balanced braces is skipped
@@ -1409,13 +2089,49 @@ rejected a complete page saved with CRLF endings.
reading too, no type reads `</` as code, and the element is the only reading: certain (`<b>(optional)</b>`, `<span>(total: {count})</span>`,
`<p>({t("label")})</p>`, nested children). What opens one: a back-tick (a template with a `${`, which opens code that is not read, may), a `//` or a `/*`,
a `/` that no word or number stands before and that so may start a regex (a keyword that an expression follows is no such word: `return`, `typeof`, and
- `implements`, whose heritage clause takes one, as in a computed name `[class C implements /…/ {}]`), and a quote that starts a string closing on its line and
+ `implements`, whose heritage clause takes one, as in a computed name `[class C implements /…/ {}]`; and a `/` after the comments that the text opened is judged by the token before them, which a type reads as trivia:
+ `b // c` and a line break, then `/d`, divides, and `1 + // c` and a line break, then `/[</T>…]/`, does not — and a `)` or `]` before the `/` divides, since a regex follows a `)` only after the head of a statement, which has a block, whose braces
+ are not read: `slashFollowsAnOperand`), and a quote that starts a string closing on its line and
covers the closing tag (a quote right after a word that is no keyword, an apostrophe or an inch mark, opens none; a keyword is a reserved word, a contextual one,
- or a modifier, which TypeScript takes before a quoted member name: `public'…'`). Where the text up to the first
- such opener cannot be the members of a type, though — two names on a line, a name and a `/`, a name and a quote (`<p>(a), see https://x.y</p>`: TS1005 in a type),
- a template or a regex where a member would begin (``<p>(a); `x ${y} </p>``: TS1131; after a member's colon a template is a type and stays possible) —
- no type holds the closing tag in anything, nothing that follows can hide it, and it is an element (`typeMembersFail`; a word that may be a modifier or any other
- character leaves it undecided). Where one is open at the closing tag, or the reading cannot say (a container or a tag it
+ or a modifier, which TypeScript takes before a quoted member name: `public'…'`). A nested tag is an element's or, to a type, something else: the type arguments of a name (`Array<b>`), a comparison (`a<b>c`), the type parameters of
+ a signature or of a method (`<b>(y): T`, `<U extends A>(y): T`, `m<b>(y)`), where the text after its `>` is code and what looks like its closing tag is inside a string, a template or a comment that the text opened before it. So a
+ string, a template or a comment that the text of a nested element opens — and the run of comments that a `/` is judged by — and that is still open at the closing tag of that element is read **both ways** (`scanChildren`, run
+ twice by `readChildren`): as an element, where it ends there and the code goes on after the closing tag (`m(a = <b>'x</b> + '</T>…')`: the string that holds the closing tag begins after the element; `m(a = <b>x // y</b> +` and a line
+ break, then `/[</T>…]/`: the regex does), and as code, where it goes on past it (`m: Array<b> = '</b>' + '</T>…'`, `<b>(y): '</b>'; q: '</T>…'`): the closing tag of the head is hidden if either reading hides it. A tag that no type has
+ (`tagMayBeCode`) is an element to every reading: there is only the first, the region is cut at its closing tag, and its text is JSX text, which opens nothing (`jsxText`: a URL, an apostrophe or a back-tick in the text of a link is
+ text). That is a tag in which every word has a value (`<a href="/x">`; and `<button type="button">`, `<label for="x">`, `<Link as="span">`, where the word that has a value is an attribute's even when it spells a keyword: the only `=`
+ in a list of type parameters is a default, which its name owns; and one whose attributes stand each on a line of their own, as a formatter lays a tag out, has every `=` on the line of its word), an attribute that `extends` does not introduce (`<b d>`), a dotted name with an attribute, and a fragment where no empty list can stand. **Every other tag may be code,
+ by the words in it**: a keyword of TypeScript's, other than `extends`, in a word that has no value is a modifier of a type parameter (`<public U>`, `<in out U>`, `<readonly U>`: `parseTypeParameter` takes them all, and only the checker
+ objects), an operator of a comparison or a tagged template with type arguments (`x <a in b> y`, `x <typeof U> …`, `x <new b> …`, `x <A.B as T> …`), or a type operator in type arguments (`Array<keyof X>`) — and so is a dotted or dashed word
+ that has one — **or by the lines it takes**: a line break between a word and its `=` (`href` and a line break, then `="/x"`), or before a `get` or a `set` that has a value (`get="/x"`). A line break ends a member of a type, so where the tag stands
+ in one, `m: A = x <a` ends its initializer at the break, `href` is a member of its own, and `="/x"> '</a>' + '</T>…'` is that member's initializer, with the string that holds the closing tag in it (a name and a `=` on one line are no member,
+ TS1131, but `get` and `set` begin one before the parser looks at what follows, so `get="/x"` on a line of its own is a property with an initializer: `isTypeMemberStart`). And a fragment is an empty list of type parameters or arguments right after a name,
+ a `)`, a `]`, a `}`, a `!`, a quote, a number or a `.` (`f(x)<> || …`, `a[0]<>`, `'s'<>`, `{}<>`, `1.<>`: the parser accepts an empty list there and the checker
+ rejects it) or right before a `(` or a back-tick (`<>(y)`, `m<>(y)`, `` x <>`t` ``), and after a line break when the line before it may end in a comment, whose last character may be any (`f // note:` and a line break, then `<> || …` is `f<> || …`:
+ `lineMayEndInComment`) (`fragmentMayBeList`); after a `,`, a `;`, an operator or nothing, on a line that has no comment before it, it is a fragment, for certain. The keywords are TypeScript's own list (`TS_KEYWORDS`), and the
+ sweeps draw their tags from every keyword it has, joined to names, dots, dashes and values, **including the tags the rule calls no code** — a rule that is wrong about a word can only be met that way (`nestedTagPages`; the sweep of
+ the valued keywords keeps the precision of the rest). A tag that a type may have and an element may too (`<b>`, `<U extends A>`, `<A.B>`, `<public U>`) is read both ways, and a tag that is not read leaves it possible; two such places
+ in one text are taken for hidden, as the second reading depends on the choice made at the first. A place is a region that the text of a nested element opened and that is still open at that element's closing tag, **told by where the region starts**,
+ not by where it ends: two `//` comments on one line, each opened in the text of an element of its own (`m(a = <b>//</b> - <i>//</i> ??` and a template that starts on the next line), end at the same line break and are two places (`skipFrom`; `nestedPairPages`). A tag inside a string, a template or a
+ comment that the type's own text opens is no element's to the type (`'a <b>' + \`</b>\` + '</T>…'` holds `<b>` and `</b>` in two literals): it opens and closes in the element reading and counts for nothing in the depth
+ that those rules use (a ghost, `realDepth`); and a tag inside a region that the text of a nested element opened is a ghost in the reading where that element is code, which pairs the quotes after it as a type does
+ (`m: Array<b> = '<>' + '</>' + '</b></T>…'`: the element reading cuts the second string at `</>`, the type reads three strings), so where one stands the text is read both ways too (`tagged`). Where the text up to such an opener cannot be the members of a type, though — two names on a line,
+ a name and a `/`, a sign, a `.` or a quote (`<p>(a), see https://x.y</p>`, `<p>(a); well-known // c </p>`, `<p>(a), it's // c </p>`: TS1005 in a type), a `:` after a type
+ (`Docs: https://x.y`), a `/` where a type must follow a `:` (`https://x.y` and a line break, then `/b`: TS1110), a template or a regex where a member would begin (``<p>(a); `x ${y} </p>``: TS1131;
+ after a member's colon a template is a type and stays possible) —
+ no type holds the closing tag in anything, nothing that follows can hide it, and it is an element (`typeMembersFail`, asked at each opener from where it stopped, through the comments between them). It is a small
+ reader of where a member is — its start, a name, a `:`, a type, an initializer; the next line of a name and the next line of a type are different places (`PROSE_*`) — and what it reads is TypeScript's: a number is one name by
+ the scanner's rule (`1e-5`, `.5`, `0x1F`; a hex, octal or binary literal ends at its last digit, so `0x1Fin` is `0x1F` and the operator `in`, where a word right after a decimal literal is TS1351), a keyword is a name where a member begins
+ unless it may be a modifier (which a `:` after it makes a name too), a word after a `.`, `typeof` or `infer` is a name, whatever it spells (`A.new`, `typeof new`, `infer keyof`; but `typeof import` is an import type, whose `(` has no line-break rule: `typeof import` and a line break, then `('./m')`, is a type, `typeofImport`), after `keyof`, `readonly` or `unique` it is a type, of which a
+ keyword is the name (`keyof new`), and a word that starts a type a word may follow (`asserts b`) is not read; a word written with an escape (`a\u0061b` is ONE name) is not read; a `(…)` or `[…]` that closes is one thing (a signature's parameters,
+ a computed name, a parenthesised type, an array), `<T>` is type parameters only where a parameter list follows, a type goes on with `.`, `|` and `&`, and two operands of an initializer side by side are an error unless a keyword is one
+ of them. A name or a keyword that a `(` follows opens a parameter list, whose first parameters are read as a head's are (`parameterListMayStart`, `parameterSyntaxFails`): a `/` right after the `(` and its comments is TS1138, a number,
+ a string or an operator there is TS1003, and two names are TS1005 — so `foo( // note` and a line break, then `/docs` is no type's, and neither is `m(see docs) // note` (the `(` of an import type is no parameter list, and is not read as one: `typeof import`). A name, a number, a string or a signature with a `=` right after it on its line
+ is no member (TS1131; TS1005 after a signature): the initializer that a property signature may have — the parser accepts it and the checker rejects it — follows a `?`, a type, a computed name, `get` or `set`, or a line break
+ (`m? = 1`, `m: A = 1`, `[m] = 1`), and `m = 1` is TS1131. A `[`, a name and a `,` or a `:` are an index signature for certain (`isUnambiguouslyIndexSignature`) — unless `get` or `set` stands before the `[`, which then begins an accessor's computed name,
+ an expression that a regex may hold (`get [a, /[</T>…]/]()`: `parseContextualModifier` takes the keyword first, whatever its line) — and neither a parameter nor a type starts with a `/` (TS1138, TS1110):
+ `[ a, // note` and a line break, then `/path` is no type's, where `[ // note` and a `/` is a computed name that a regex may follow, and neither is `Total: [ // note` and a line break, then `/docs`, where the `[` after a `:` opens a tuple. Each place has the characters that fail there, **measured over every ASCII character against TypeScript's parser**, and the sweeps in `tests/source-literals.test.js` put every claim back to TypeScript. What it cannot
+ follow — a `[` that nothing closes on its line, an initializer after a `?`, a type or a computed name, a conditional type, an expression, a decorator, a `{` — leaves the rest undecided, and the closing tag may be hidden there. Where one is open at the closing tag, or the reading cannot say (a container or a tag it
does not read, a window of 2,000 characters, a spent budget), both programs compile and the text up to the decision
is the same: the guess `generic`, and the element is read. A type of *k* signatures reads the rest of the type for
each, up to the window, so a pass has a budget of characters to read (`READING_BUDGET_PER_CHAR` for each character of
@@ -1438,7 +2154,7 @@ rejected a complete page saved with CRLF endings.
| `jsx-type-arguments` | a JSX element whose type arguments hold a string, template, object or function type: TypeScript's rules apply there and the tag is scanned by a JSX attribute's | `<Component<"quote\"\<LF>/*"> …/>` |
| `jsx-attribute` | a JSX attribute value whose quote does not follow its `=` at once (white space or a comment stands between them) and whose text holds a backslash: TypeScript scans it as a JavaScript string, with escapes, and other compilers as a JSX string, with none, so the two end it at different quotes and read different calls after it | `<C x= '\'/>;navigateTo(…);//' />` |
| `jsx-open` | a `<` where an element may start that is not read as one (a space after it, or a name beyond ASCII: in code, in JSX text and as an attribute's value), or a closing tag that holds anything but trivia, comments and a name (dotted, or namespaced) before its `>`, so that where it ends is not known | `< div>x</div>`, `<A x=< B/>>…</A>`, `<A></A b>` |
- | `generic` | `<Name>` and a parameter list followed by `:`, which is the call signature of a type or JSX text that starts with a parenthesis (both compile; a list that can hold no parameters, `<li>(1): First</li>`, is the element's alone); or one followed by no return type, where a string, a template, a comment or a regex after it could hold its closing tag, or its text cannot be read to the end of an element, or the pass's budget of readings is spent (a signature with no return type is otherwise code, for certain, and JSX text that starts with a parenthesis an element: `callSignatureOrElement`); or a parameter list too long to scan (2,000 characters), or one with no arrow after it in which something may start an expression (`expressionMayStart`: an `=`, a `[` other than `[]`, an `@`, `import`, `extends` before what starts no type, and `get` or `set` before an accessor's name) and a `/`, a `<` or a back-tick follows, or a template whose substitutions do not close or hold a `<` after an expression start (`templateSkipIsWhole`), or `<T extends` and a `/` (an element where an expression starts, type parameters with a regex constraint in a type) — except directly after `type Name =`, where it is certainly a type. A `=>` after the list is a generic function type for certain when the element reading of the text up to the arrow cannot parse (`elementFailsAt`: a `>` or `}` in the text, a container that starts with a name, a number or a quoted name and a colon, two names, a bracket, a call or a quoted name and a call and a colon, a `<` and a character that cannot start a tag, …), and a guess, read as a type, when it may: the arrow inside the attribute string of a nested tag (TypeScript scans a JSX attribute string with no escapes), a closing tag, a fragment, a spread, a comment, an attribute value that does not follow its `=` at once, a character beyond ASCII where a token could start or end in a tag, or a container that holds a brace, a quote, a back-tick, a `/`, a backslash or a `<` and none of the shapes `elementFailsAt` knows; a `<` followed by `await` or `yield`, which are identifiers or not by the function around them | `interface I { <T>(x: T): T }`, `interface I { <T>(x); m: '</T>' }`, `<span>(required): Name</span>`, `<p>(a), b/c</p>`, `const f: <T>({ a = {} }: P) => T = g`, `const f: <T>(x: { 'a'?(y: T): T }) => T = g`, `async function p() { <await extends X>t</await> }` |
+ | `generic` | `<Name>` and a parameter list followed by `:`, which is the call signature of a type or JSX text that starts with a parenthesis (both compile; a list that can hold no parameters, `<li>(1): First</li>`, is the element's alone); or one followed by no return type, where a string, a template, a comment or a regex after it could hold its closing tag, or its text cannot be read to the end of an element, or the pass's budget of readings is spent (a signature with no return type is otherwise code, for certain, and JSX text that starts with a parenthesis an element: `callSignatureOrElement`); or a parameter list too long to scan (2,000 characters), or one with no arrow after it in which something may start an expression (`expressionMayStart`: an `=`, a `[` other than `[]`, an `@`, `import`, `extends` before what starts no type, and `get` or `set` before an accessor's name) and a `/`, a `<` or a back-tick follows that the scan does not read exactly (a first default's regex or element, a `/` after a name or a number that is no line comment's last word, a template with no `${`: `initializerReading`), or a template whose substitutions do not close or hold a `<` after an expression start (`templateSkipIsWhole`), or `<T extends` and a `/` that begins a regex which its line ends (an element where an expression starts, type parameters with a regex constraint in a type) — except directly after `type Name =`, where it is certainly a type. A `=>` after the list is a generic function type for certain when the element reading of the text up to the arrow cannot parse (`elementFailsAt`: a `>` or `}` in the text, a container that starts with a name, a number or a quoted name and a colon, two names, a bracket, a call or a quoted name and a call and a colon, a `<` and a character that cannot start a tag, …), and a guess, read as a type, when it may: the arrow inside the attribute string of a nested tag (TypeScript scans a JSX attribute string with no escapes), a closing tag, a fragment, a spread, a comment, an attribute value that does not follow its `=` at once, a character beyond ASCII where a token could start or end in a tag, or a container that holds a brace, a quote, a back-tick, a `/`, a backslash or a `<` and none of the shapes `elementFailsAt` knows; a `<` followed by `await` or `yield`, which are identifiers or not by the function around them | `interface I { <T>(x: T): T }`, `interface I { <T>(x); m: '</T>' }`, `<span>(required): Name</span>`, `<p>(a), b/c</p>`, `const f: <T>({ a = {} }: P) => T = g`, `const f: <T>(x: { 'a'?(y: T): T }) => T = g`, `async function p() { <await extends X>t</await> }` |
| `fallback` | a quote with no closing quote on its line, read as an ordinary character; a `/` after a character that begins nothing in code | `const a = 'unterminated`, `# / 2 / 3` |
Names alone in a tag's type arguments (`<DataGridRow<Row>`, `<Select<string | number>`) are certain: the scan
@@ -1475,8 +2191,23 @@ rejected a complete page saved with CRLF endings.
with members or an element stands, followed by every ending that ends a member or goes on to another, and by a decoy —
a string, a template, a comment or a regex that holds the closing tag of its head and the text of a call, and a type that
holds the closing tag in a string as the text of a call signature's parameter, in a member name quoted after `public`, or in
- a regex after `implements`)
- — each read token by token against TypeScript's parser — and a differential fuzz
+ a regex after `implements`), a label and a list that no signature has (`(Size: 10 MB max, <a>…</a>)`, an object type that is none,
+ `new`, `import`, an `=` and a closing tag: TypeScript rejects each in a call signature, a construct signature and a function type,
+ and the element is certain) and a parameter list whose default is a regex, an element, a template or a division (read exactly where the
+ scan can say where the list ends, a guess for the rest, and never a misread token), a regex or a division after a line comment (one that ends in a name, a number, a `$`,
+ a letter beyond ASCII or a sign, and every line break TypeScript has, in the scan of a list, behind `>=`, `in` and the other tokens that leave a `<` undecided, and in the reading of the text after a signature), JSX text of several lines with a `//` in one and a
+ `/` at the start of a later one (a URL on a line of its own, a label and a URL, a name and a note, with `;`, `,` and a line break after the `)`: read for certain wherever no type has the text, and the lines of every class that no type has —
+ a bracket, a quote, a tag, an operator, a number, a modifier, a postfix, a line that goes on over a line break or after a type — are certain too; a closing tag in the comment, in an element and as the members of a type, a guess; and
+ the same lines in an expression of a type, where a regex after the comment may hold the closing tag), a member named by a number with a signed exponent (`1e-5` is one name), the text of a nested element in a default value or
+ a computed name (what it opens ends with it, unless the element may be code), a literal that holds the tags of an element (in one string, or `<b>` in one and `</b>` in the next), the text of a nested element drawn from quotes, back-ticks,
+ comment openers and tags, a nested tag that no element has (type arguments, a comparison, the type parameters of a signature or a method, in front of a string that holds its closing tag: read both ways, and
+ the closing tag of the head hidden) — drawn from every keyword TypeScript has, joined to names, dots, dashes and values, spread over lines (a line break of every kind before an `=` or a valued `get`; a formatter's layout), with fragments after every operand, after a comment of every ending and before a parenthesis, **the tags that the rule calls no code included**
+ (`nestedTagPages`) — two or three nested elements whose texts open regions that end at one place (`nestedPairPages`), a keyword that is the name of an attribute with a value (certain: nothing is refused),
+ strings and elements that hold fragments, tags with attributes and closing tags after such a tag (the quotes pair differently in the two readings), links and other tags with attributes in a
+ hint (certain: their text is text), and a parenthesised callee after `return`
+ — each read token by token against TypeScript's parser — and every claim of `typeMembersFail` that a text is no type's members, put to TypeScript's parser (every text of up to three tokens of a vocabulary of the pieces of a
+ member and what is rejected there, seeded draws of more, runs of valid members mutated at one or two places, every keyword of TypeScript in each place a word may stand, after each of the words that start a type or a member, after a `.`,
+ `typeof`, `infer`, `keyof`, `readonly` and `unique`, and a number of every spelling with a word, a quote or a `/` right after it, a `/` after every operand that ends in a bracket, import types and accessor names of every spelling, and tuples: `tests/helpers/type-member-texts.js`) — and a differential fuzz
(`tests/jsx-element-reading.test.js`; `JSX_FUZZ_SCALE` multiplies it) checks every verdict of the element
reading of a head and of a function type against it, and puts the text after a parameter list that neither an arrow
nor a colon follows into a type and into an element, where TypeScript says which parse: a type that parses is never
@@ -1496,8 +2227,15 @@ rejected a complete page saved with CRLF endings.
programs share the text up to the decision and compile differently, shown by a pair in the test — and a page
in no class, or a class that no page meets, fails it. Where `BASE_LIB_PATH` points at the `scripts/lib` of an
earlier lexer, the pages are read by that one too, and the test counts what each resolves and the data each
- rewrites. When a change makes the lexer refuse a shape it resolved, this is where it shows: add the shape to
- the generator, and either fix the rule or record the class with the pair that justifies it.
+ rewrites. What that asks of the base depends on it: one from before the lexer was hardened misreads shapes the
+ corpus holds, and the net must see at least 100 of its decoys rewritten (and none of this lexer's); the previous
+ release reads every page of the corpus right, so it rewrites none and nothing is demanded of its count — the
+ comparison is then the pages this lexer resolves and the base does not (at least 100), and the pages it refuses that
+ the base resolves, of which there must be none: a page that 2.13.0 resolved and this lexer refuses is a regression, and the test fails on it. When a change makes the lexer refuse a shape it resolved, this is where it shows: add the shape to
+ the generator, and fix the rule. **The oracle tests skip themselves where the variable is not set** (`TYPESCRIPT_ORACLE_PATH`, `BABEL_ORACLE_PATH`, `BASE_LIB_PATH`) **and fail where it is set and the package or the lexer cannot be loaded**
+ (`tests/helpers/typescript-oracle.js` throws), so a wrong path or a renamed file cannot turn the job green without running them. The CI job `test-model-apps-lexer-oracles` (`.github/workflows/model-apps-script-tests.yml`) installs
+ TypeScript 5.8.3 and `@babel/parser` 7.29.7 under `$RUNNER_TEMP` — outside the plugin, which ships no dependency, with `--ignore-scripts`, at exact versions — fetches the lexer of the 2.13.0 release by its commit hash, sets
+ the three variables, and runs `node scripts/run-tests.js`. A new TypeScript release can change what a sweep judges: raise the pin in the same change, and run the sweeps.
- **The residual net does not depend on the lexer, and has no exemption.** After forward resolution the
RESOLVED source is read again — the copy can read differently from the source, because each token became a
longer page id, which can move a `(` out of the look-behind — as plain text: any `PAGEREF_` token left in it
@@ -1592,7 +2330,11 @@ Residual limits, accepted deliberately:
the `<` and the `>` is a list of types); a generic call signature with a return type in an object type, which is JSX
text that starts with a parenthesis and a colon in an expression, a call signature with no return type whose type holds
its own closing tag in a string, a template or a comment, which is an element that ends there, and JSX text that starts with a parenthesis and then holds a `//`, a `/*` or a
- template after a separator, which is the comment or the template of a type's members that holds the closing tag (`generic`); and a `/` on a later line than its operand
+ template after a separator, which is the comment or the template of a type's members that holds the closing tag, and JSX text that starts with a parenthesis and holds a default whose
+ regex, element, division or template the scan does not read (`(a = f(/x/))`, `(a = <b>c</b> / 2)`, ``(a = `${b}`)``: the `)` it finds may be one of that expression's), and a `/` that a line comment stands before
+ (`(a = 1 + // c` and a line break, then `/[)]/)`: the comment may end in a word, and the regex is no division), and JSX text of lines with a `//` in one and a `/` at the
+ start of a later one, where the members of a type could hold the closing tag in the comment (the next bullet), and
+ `<T extends />` with another `/` after it on its line (`generic`); and a `/` on a later line than its operand
(`newline`). A `/` or `<` that follows a `/` is no class of its own: where the lexer read the regex (flags included), the element or
the division itself, it knows what ended there (`ends` in `lexInto`), and the page resolves — and so does a cast it proves (`castKeywordIsCertain`). What stays the `angle` guess among casts is a limit of the walk back over the type, not a place where two programs share
their text — TypeScript reads each of these one way: a type that begins with `keyof`, `typeof`, `unique` or `readonly`, or is parenthesised; a `>>` that touches a cast's closer (`x as A<B>> / 2`); a chain past `CAST_CHAIN_LIMIT`; and, as the `newline` guess, a line break after a cast type that ends in a name or a `]`.
@@ -1600,6 +2342,33 @@ Residual limits, accepted deliberately:
is the same kind of place (`operator`: `a >= <T extends X>(y: T): T</T>` is an element,
`let x: A<number>= <T extends X>(y: T): T => y` an arrow); no generated page has it, so a pair of programs stands
for it. Each says which it is and what to change in the report, and nearly every other page that compiles resolves.
+- **JSX text of lines, one with a `//` in it and a later one that starts with a `/`, is read for certain wherever no type has the text, and is a guess where the reading of a type's members cannot show it.** `<p>(a);` and a line break,
+ then `https://contoso.com`, a line break and `/docs`, is the text of an element, and the same text could be the members of a type — a name, a `:`, a comment, then a `/` where a type must be, which no type has (TS1110). The lexer
+ reads the text after a signature's `)` as those members (`typeMembersFail`, above), and a `/` after the comments that the text opened follows the token before them (`slashFollowsAnOperand`), so a URL, a label and a URL, a name
+ and a note, and every line of the classes below resolve: a line that begins with a bracket, a quote, a tag or an operator (`(x) // c`, `[x] https://x.y`, `'x': https://x.y`, `<b/> // c`, `|| // c`), has a number for its name
+ or ends in a postfix (`1.5 https://x.y`, `x! // c`, `f() // c`, `x = 1 https://x.y`), starts with a modifier (`readonly https://x.y`, `in // note`, `default // note`: where a member begins these are names, and a `/` after one is
+ TS1131), or goes on over a line break or after a type (`m` and a line break, then `&"x"`; `a: A.B, // c`). The base took the last word of the comment for the token before the `/`, which is right for these pages and wrong for others
+ (the misreads that this lexer refuses). **Where a member of a type may begin at the head, a few lines are still refused after the guess `generic`, though only the element compiles, and the base may have resolved them**: a line
+ whose last token before the `//` is a `[` that nothing closes on its line (`[ // note` and a line break, then `/path`), an initializer's `=` after a `?`, a type, a computed name or in a parameter list (`m? = // note`,
+ `m: A = // note`, `f(a = // note`, `[ x = // note`), or an operator in such an expression (`m: A = b + // note`). A regex may begin at the `/` of the next line, and the closing tag may be inside it; both programs compile
+ (the pairs of `valid-page-differential.test.js` are the proof), and 2.13.0 takes the word that ends the comment for the token before the `/`, which resolves the page of the element and rewrites the data of the other. Their
+ shape cannot be told apart without a parser: `return <p>(a);` and a line break, then `[ // note`, is the same text in an interface that has a method named `return` and in a function that returns an element, and `return <T>(x)` and
+ `m? <T>(x)` are why no place that a member may begin is excluded (above). A line that ends in a `[` after a `:` or a type is none of them, since a tuple's or an indexed access's first type is no `/` (`Total: [ // note`: TS1110), and is certain
+ in every place. A rule over the regex that the next line's `/` would open could win more of these pages back — where it ends at the closing tag's own `/` (or the regex does not close on its line) and what follows the tag cannot be an operand, only the element compiles — and no rule reads that
+ today. After an `=`, a `(`, a `[`, a `:` or an `=>` the same lines are certain (`NO_MEMBER_BEFORE`),
+ and these lines are certain in every place: a name, a keyword or a signature and a `(` that is not closed on its line (`foo( // note`, `if ( // c`, `m(see docs) // c`: TS1138 at the `/`, TS1003 or TS1005 in the list), and a name, a number, a
+ string or a signature with a `=` right after it on its line (`x = // note`, `1.5 = 1 // c`: TS1131). What the reading does not follow — a conditional type, an expression, a decorator, a `{` — leaves the type undecided, and the
+ page is refused only where an opener after it (a `/` after an operator or an open bracket, a quote, a back-tick) could hold the closing tag. `valid-page-differential.test.js` with `BASE_LIB_PATH` fails on a page of its corpus that
+ 2.13.0 resolves and this lexer refuses, and it reports how many pages of the member-position lines 2.13.0 resolves (they are not in that corpus: they are the class above). Put the call before the text, or write the line with one name before the `//`.
+- **Shapes of type parameters among a type's members are read as the element they are not, exactly as 2.13.0 reads them** (the same output in 2.13.0 and in this lexer, measured over every keyword TypeScript has): type parameters
+ that start with a modifier — a variance modifier (`<in U>(y): void`, `<out U>`, `<in out U>`, also with no return type) or one that only the checker rejects (`<public U>(y): void`, `private`, `protected`, `readonly`, `static`, `abstract`,
+ `async`, `declare`, `override`, `accessor`) — and an empty list (`<>(y): void`, `new <>(y)`), wherever a member of an interface or an object type begins (a page is refused at an earlier call signature that was guessed at; a `const` is refused too, a guess); and a method named by `delete`,
+ `typeof`, `void` or `instanceof` (`delete<U>(y): void`, `typeof<U>()`), where the other 79 keywords are refused. A `<` after a keyword, or a head that starts with a reserved word, a modifier or `>`, is the tag of an element to the lexer, and a type reads it
+ as type parameters. Where a string, a template or a comment later in the same type holds a closing tag with the name, a `;` and the text of a navigation call (`<in U>(y): void; a: '</U>;navigateTo(…);//'`), the element ends there and the call
+ in the string is read as code and rewritten. Where nothing closes the element, the rest of the page is its text, which is read as code where it has a container: a typed API interface (`interface Api { list<T>(): Promise<T[]>; delete<T>(url: string): Promise<T>; }`)
+ followed by a handler builds as it should, since the handler's container is code in the swallowed text, and a `{…navigateTo({ pageType: "generative", pageId: "PAGEREF_x" })…}` in a later comment or template literal is
+ rewritten, though it is data — so this is not a failure that is always loud. No page in the committed corpus has these shapes, and telling a type's members from an expression is what the lexer has no parser to do. (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`.)
- **A JSX attribute string after trivia is a guess when its text holds a backslash** (`jsx-attribute`): TypeScript
reads a quote that does not follow its `=` at once as a JavaScript string, with escapes, and Babel and esbuild
read a JSX string with none, so a page whose string ends at different quotes in the two does different things
@@ -1751,6 +2520,12 @@ component types, the temp-workspace cleanup) rather than regex-matching the sour
`Array`/`Object` prototypes, so every array the script builds would fail `assert.deepStrictEqual`
against a host array with "same structure but not reference-equal".
+**Testing a CLI in a real process:** what only a process shows — its exit status, the one line on stdout and
+that line's bytes — is tested by spawning the script. `scripts/tests/helpers/fake-org-languages-preload.js`
+(`node --require …`) swaps the az-token client for a fake Dataverse that answers the three language reads, so
+`list-languages.test.js` runs the real script, bundle and `emitResult` with no Azure CLI and no network; with
+the PATH emptied, the same test shows what a machine with no `az` gets.
+
## Dataverse Access From Scripts
**Default: go through the vendored SDK.** Anything the SDK models — tables, columns, relationships,
@@ -1893,6 +2668,41 @@ plugin must NOT precompute classId), sub-grid relationship/target/view serializa
`PushResult`** signal `requireSuccessfulPush` halts on. The mock-based `sdk-build.test.js` covers the
engine ORCHESTRATION (call order, idempotency, phase selection); this covers what a mock cannot.
+`scripts/tests/form-timeline-real-bundle.test.js` (with `form-timeline.test.js` for the pure helpers) — the
+**Notes timeline shape** against the real bundle: the exact FormXML a new host serializes to (control id
+`notescontrol`, a 23-row `auto="false"` cell, 22 empty rows, no duplicate control id), the engine's own
+create path, the in-place repair of an old-shape host on an explicit and an auto layout (same section,
+position and cell identity; ONE atomic write; a second rebuild mutates nothing), hosts of the heights and
+widths platform forms use (a 5-, 20- or 23-row cell, with or without `auto`, a widened timeline) that a
+rebuild leaves alone and verify accepts, a host that only lacks rows being topped up to its own height, the
+refusals (a maker's own timeline, a taken `notescontrol`, a host with a field added), the **order** of the
+repair (a field the layout dropped, or one a `fieldOptions` anchor moves, leaves the old host first so the
+SAME build repairs it), and what `--verify` reports — with the advice that follows from the reason — before
+the build as well as after it: for each way a field leaves the host or stays in it (including a chain of
+anchors, one anchored to another that is itself moved out, up to three links), the advice has to be what a
+real build then does (`verify before the build and the build itself agree about …`); for a field the form has
+twice (sections the build orders differently from the published form, a pruned field removed one cell per
+run, a chain of anchors that reaches one, a taken `notescontrol` beside one) verify says it cannot tell, and
+what the build then does is pinned both ways. `form-timeline.test.js` pins each rule of
+verify's `notesHostInspector` on its own, one inspector asked about every cell as `--verify` does. It shares
+`tests/helpers/form-store-harness.js` — the SDK over a stub HTTP client that stores one systemform row.
+
+`scripts/tests/form-subgrid-placement-real-bundle.test.js` (with `form-subgrid-placement.test.js` for the pure
+rules, the spec gate and lint parity, verify over hand-built FormXML, the wireframe and the plan) — **sub-grid
+placement** against the real bundle: where a new grid lands (between sections, before/after an anchor, in a tab
+or form-column, on an auto layout), a rebuild moving the grid an older build appended into place (one move OF
+THE GRID, the same section id, a second rebuild writes nothing), **the form the released builds deployed**
+(`notes: true` + a grid behind the Notes section, the old timeline: every placement ends in the order a new
+form gets, the timeline repaired in place, nothing but the grid moving), a section between a grid and its
+anchor left behind the grid, the refusals (a grid in a maker's section — reported only when it is NOT already
+in place — an anchor the deployed form lacks),
+the sweep of an emptied same-named section still resolving after a grid shifted the indices, **fields the
+build adds** landing in their own section whichever way a grid shifts the sections around it (an auto
+form, a section the spec adds, a grid added in front, leaving the column, moving down past it or up from
+behind it — each of which wrote the field into the grid's section or halted the forms phase when the field
+was queued by index — and a section that is gone altogether), and a recorded
+**regression guard** — a spec without placement keys writes exactly what it always did.
+
`scripts/tests/vendor-sdk-smoke.test.js` — the **behavior/return-shape** `CONTRACT:` tests (drive the
public `createMakerSdk` factory — the `MakerSdk`/`AppAdapter` classes are no longer bundle exports):
- **Raw OData filters pass through, single-encoded** — the skill builds raw `$filter` strings
@@ -1921,6 +2731,11 @@ artifacts, 2xx statuses, green build. The test therefore does two things: a **so
fails on any un-awaited `provision.*`/`sdk.*` call to those methods (annotate a deliberate one with
`sdk-async-ok`), and a **dynamic check** that the real bundle still returns Promises for exactly that
list — so if a future SDK makes one synchronous again, the scan can't go on enforcing a dead rule.
+The same file pins the **throwaway-workspace lifecycle**: a CLI that makes a temporary workspace must
+build its SDK behind a `try` whose own `catch` or `finally` removes it (`cleanup()`, `dispose()` or
+`rmSync`), or a failed construction strands the directory. The guard is read from the syntax tree — the
+first `try` after the `mkdtempSync`, in the same function — so a cleanup elsewhere in the file neither
+satisfies the check nor breaks it by changing shape.
`scripts/tests/workspace-projection-real-bundle.test.js` — the **upgrade** guard. The SDK refuses to
push a workspace copy stamped with another parser version (`ARTIFACT_PROJECTION_STALE`), so a
@@ -1942,6 +2757,238 @@ to look at the change in Maker and put into the spec what should stay, then make
re-download is no substitute: it captures no forms, views or charts, and an interrupted first build
can leave them before the app exists.)
+**Newer SDK behaviors the plugin adopts, and the options it leaves off.** Each is pinned against the
+real bundle, because a stub stays green through a change in the SDK's own rule.
+
+- **A workspace belongs to its environment** (`scripts/tests/workspace-binding.test.js`). The SDK
+ records the environment a workspace was first opened for in `manifest.json` and refuses an SDK for
+ another one (`WORKSPACE_ORG_MISMATCH`) before it reads or writes anything. Only `build-model-app.js
+ --apply` opens the app folder's workspace — a dry run, download, `ai-preflight`, the `provision-*`
+ scripts, teardown and the standalone verify use throwaway ones (verify reads only the build's
+ `last-applied.json` from the folder, so it verifies any environment the app is deployed to and never
+ binds a fresh folder). A **dry run** works in a temporary workspace inside the SDK's own temp dir and
+ creates nothing in the app folder: opening binds, a preview builds nothing, and a folder it bound to the
+ environment it only previewed would refuse the environment the operator meant (a preview against the wrong
+ environment followed by `--apply` against the right one would be told the folder's saved copies belong to
+ the wrong environment, though nothing was built there). Every read its live plan makes goes to the server, so it
+ needs nothing from the folder; the folder is only ASKED, read-only, which environment it belongs to
+ (`getManifest`: it parses `manifest.json` and no saved copy, and writes nothing), and the answer is a `⚠` note on stderr
+ (`workspaceBindingNote`) that an `--apply` would stop — the preview itself, its plan and its "No spec
+ changes since the last apply" advisory (read from the baseline file) are unchanged. The question is not
+ a listing of the app artifacts, which would check the environment just as well: listing also parses every
+ artifact's saved copy and its metadata (to flag unpushed edits), so a corrupt copy in a folder that belongs to
+ THIS environment would throw the very error a corrupt manifest does and be reported as one. A saved copy says
+ nothing about which environment a folder belongs to, so the preview reads none and says nothing about one (an
+ `--apply` opens such a folder; the SDK meets the copy when it first reads it). A link or a file where
+ the folder should be is still refused; a folder that is not there is just one with no workspace. So
+ `--apply` is the one entry point that turns the refusal into a halt (`lib/workspace-binding.js`) that
+ names both environments as normalized origins, never the manifest's own text, and offers the safe ways
+ forward: build against the environment the workspace belongs to, use a fresh app folder or `--workspace`,
+ or — only when that environment's copy of the app is no longer wanted — tear it down there with
+ `--clear-workspace`. The folder is printed on a line of its own and the teardown command takes it as
+ `--workspace <the folder printed above>`, never embedding it: teardown otherwise clears the folder beside
+ its spec, and no quoting of a path is right for every shell (inside double quotes PowerShell and POSIX
+ shells still expand `$name`, so a folder named `$work` would point the delete elsewhere; single quotes are
+ not quotes in cmd.exe), so the halt says to pass it quoted for the operator's shell. Teardown already keeps
+ the folder while a page-ownership receipt remains. A folder that holds **nothing a build saved** (the SDK's
+ manifest listing no artifact, and its empty folders, and nothing else — `holdsNothing`, which is
+ conservative: any other file, a link or an unreadable entry counts as saved work) was only ever opened —
+ by a preview of an earlier release, or a build that stopped at its start — so nothing was built in that
+ environment: the halt says so and offers neither `--env <that environment>` nor the teardown, only
+ deleting or moving the folder aside, or a fresh one. A manifest the JSON parser rejects would otherwise
+ surface the parser's own "Unterminated string in JSON at position N" (no path, no advice); it is
+ recognized by the error's name (enough, because opening a workspace and asking it for its manifest parse
+ `manifest.json` and no other file, so a corrupt saved copy is never mistaken for it), never echoed (newer
+ Node versions quote the file), and halts with
+ `WORKSPACE_MANIFEST_INVALID` as the folder with no usable environment does: move it aside — rename it, do
+ not delete it, it can hold page-ownership receipts and the baseline a new workspace does not get back.
+ The plugin never clears or re-binds a workspace for the operator — the SDK's own remedy,
+ `cleanWorkspace()`, discards its saved copies, metadata and baselines, a copy can hold an edit that was
+ never pushed, and the receipts and baseline beside them are the other environment's — and no script
+ calls it. Not even an empty folder is cleared automatically: the check and the act cannot be made atomic
+ against a build that starts in that folder in between.
+ The SDK compares the recorded URL as text (trimmed, lower-cased, trailing slashes dropped), and `--env`
+ takes an https origin and nothing more, so the one spelling of the SAME environment a run of this
+ plugin can meet is the `.api.` host (`<org>.api.crm.dynamics.com` against `<org>.crm.dynamics.com`).
+ The plugin does not fold the two — the baseline, the receipts, the token and the HTTP client's origin
+ guard all key on the host it was given — so the halt says it is the same environment (never "another"),
+ gives the host to re-run with, and offers no teardown, whose target would be the run's own
+ environment. A manifest another tool wrote with a path or port has no `--env` that matches it, and
+ gets a fresh folder only. Handing the SDK one canonical origin would prevent neither: it already
+ ignores case and trailing slashes, and the plugin does not treat the two hosts as one.
+- **`createRecovery: 'adoptExact'` on the SDK that creates forms** (`provisionSdk` in
+ `build-model-app.js`; `scripts/tests/form-create-recovery-real-bundle.test.js`). The HTTP client
+ re-sends a create whose answer never arrived, and the platform answers the re-send 412 because the SDK
+ mints the `formid`. The SDK then reads that row and adopts it only when it is exactly what was sent (a
+ Main form with the same XML, name, table and type). The push comes back `{ saved: false,
+ adoptedExisting: true }` having written nothing, so `pushFailed` (`lib/entity-provision.js`) does not
+ count it as a failure and `reportPartialPush` says it happened. An inexact row, a Quick Create form,
+ or an environment that answers a replayed create with 404 halts as before, now with the SDK's reason.
+ The header-carrying `sdk` does not get the option: it does no workspace I/O, so it never creates forms.
+- **An AI override saved but not yet published is `pendingPublish`** — see the AI features note above.
+- **A form or dashboard is read and written only as its own kind**
+ (`scripts/tests/form-kind-real-bundle.test.js`, `form-order-real-bundle.test.js`,
+ `sdk-resend-layers.test.js`). A fetch and a push decode the row's `type` from a read they already make — a
+ fetch's `RetrieveUnpublished()` selects it, a push's content-token read selects `formid,type` — so the check
+ costs no request; only a delete adds one, a `RetrieveUnpublished()?$select=type` before it, because it reads
+ nothing else first (forms are types 2, 6, 7 and 11, dashboards 0 and 10). The SDK refuses
+ another kind — or a row whose type it cannot read — with `SYSTEMFORM_KIND_MISMATCH`, naming the kind it
+ found; a push that would change an existing form's type is refused `FORM_TYPE_IMMUTABLE` (the plugin never
+ changes one). A fetch refused this way stores nothing, a push of a copy whose row has since become another
+ kind writes nothing, and teardown reports a refused delete as the step's failure in the SDK's own words,
+ never as "already gone". Download's dashboard read reports a sitemap dashboard subarea whose id is a form as
+ unreadable and leaves it out, so the usual gate stops the run. The plugin's own pin checks
+ (`resolveExistingFormId`, `findPinnedDashboard` — a type-0 dashboard only) refuse a wrong pin first, so this
+ is the second line. A fake Dataverse that stores a systemform must answer its `type` (a Main form is 2),
+ honour `$select` and leave a null column out, as the platform does; otherwise every form read in a
+ real-bundle test is refused.
+- **An app header write is never unconditional** (`scripts/tests/app-ai-description-real-bundle.test.js`). The
+ SDK 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`, `description` and,
+ when one is supplied, `aiappdescription`; the icon is written at create only). A header edit made while it
+ holds 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 has
+ just fetched, and only the routing description — every other header field is written at create — so the
+ build does not meet the refusal; a sitemap-only push needs no header token at all. If a push ever did meet
+ it, `pushAppHeader` resets the copy and the next run, whose fetch reads a token, saves the edit.
+- **Metadata reads ask for the latest definition** (`scripts/tests/sdk-uptake-contract.test.js`). The SDK
+ sends `Consistency: Strong` on every read of `/EntityDefinitions`, `/RelationshipDefinitions` and
+ `/GlobalOptionSetDefinitions` — about 10% more per read — and on no other path, so a read right after a
+ metadata write is not served the definition from before it, and a schema write drops the cached
+ definitions of the tables it changes. The plugin's HTTP client passes a caller's headers through, so the
+ header reaches the wire. The plugin still carries three waits for the metadata-read lag (`lib/entity-provision.js`),
+ and keeps them, because it is not measured whether `Consistency: Strong` leaves any lag: `readTextColumnLength`
+ asks a 404 on the attribute of a table created a moment ago again, twice; `confirmInlineColumns` re-reads the
+ attribute collection of a new table, up to three reads in all; and the relationship create, told that its
+ name is already used while no read shows the row, reads twice more (about 2 s, then 4 s) before it calls the
+ name unidentified. They are candidates for removal once a live run shows no lag. The `MetadataCache` 400 that
+ a form, view or chart lookup on a table that does not exist yet answers (`resolveExistingFormId`, the plan's
+ artifact probes) is the platform's answer to a read of a DATA table, which the header does not cover, so
+ that handling stays. See the localized-label note above for the one effect that is not measured.
+- **The environment's languages come from the SDK, with `pac` behind it** (`scripts/list-languages.js`,
+ `lib/lcid-cultures.js`; `scripts/tests/list-languages*.test.js`, `lcid-cultures.test.js`).
+ `getEnvironmentLanguages()` makes three reads — the organization's base language,
+ `RetrieveProvisionedLanguages()`, `RetrieveAvailableLanguages()` — and touches no workspace; it is strict, so
+ a response of an unexpected shape throws `ENVIRONMENT_LANGUAGES_UNREADABLE` and a failed read throws its own
+ error. The planner runs the script first: it prints one pure-ASCII JSON line with the base language and, for
+ each provisioned language, its LCID, culture code and whether it is right-to-left. The SDK returns numbers
+ only, so the host maps them with a table of Windows' own culture data; an LCID the table does not name stays
+ numeric (the base language's too), is reported in `unmapped` and on stderr, and is never given a guessed
+ code or direction. The script writes nothing and emits no telemetry of its own.
+ **The script is the preferred source, not the only one.** It reads through the `az` token, and `/genpage` has
+ never needed `az` for a page over existing entities or mock data (README). So when it exits non-zero — for
+ any reason; most often the Azure CLI is missing, signed out, slow or signed in to another tenant — the
+ planner runs `pac model list-languages --environment '<envUrl>'`, as before the script existed but pinned to the
+ environment the script was given (without the flag `pac` answers for the active organization of its auth
+ profile, which is not necessarily the environment the plan is for), records both in the log and says so,
+ and stops only when `pac` fails too. The rule is the exit status, on purpose: the SDK reports a missing
+ Azure CLI, a slow one, a token another tenant refuses and a dropped connection alike, as `CONNECTION_ERROR`
+ (`statusCode` 0, or the HTTP status of a refusal), so no code tells them apart, and a rule keyed on the
+ wording of the sign-in advice (`Run 'az login' first`) is met by a signed-out Azure CLI only. The planner's section
+ and README's promise are pinned (`list-languages.test.js`), and so is the eval grader's reading of a run
+ that fell back (`phase-expectations.test.js`). The plugin's own `readProvisionedLanguages` /
+ `readOrgLanguageCode` (`lib/dataverse-auth.js`) stay: they run before an SDK exists (it needs the language
+ at construction) and fail soft, where the SDK's read is strict.
+- **Two layers re-send, and for a delete they add** (`scripts/tests/sdk-resend-layers.test.js` pins every
+ count). The HTTP client re-sends a 429 or 5xx — except a record delete and a `$batch`, which it
+ re-sends only for a deadlock (SQL 1205) or a 429. The SDK re-sends a deadlock for reads, an app
+ create, `PublishXml`, a form create, a view create, a publisher create and each delete of a row-summary
+ removal (there a 400 quoting SQL's "chosen as the deadlock victim" counts too), and re-sends an app delete
+ that hits the platform's search-index insert race (HTTP 400, SQL 547). An app delete's two triggers are
+ different answers, so a race, then a deadlock, then success is three change sets, and a persistent one of
+ either is four — never four times four. A POST's deadlock is a 500 the client has already re-sent by
+ the time the SDK sees it, so one deadlock costs one re-send in all; only a deadlock that never
+ clears multiplies, bounded by the client's six attempts times the SDK's four (24 requests, measured
+ on a form create and on a view create). A row-summary delete is re-sent by both layers for a 500/1205
+ (one that clears costs one re-send; one that never clears at most 16, the client's four times the SDK's
+ four), and by the SDK alone for the 400 form.
+- **A row-summary removal settles each delete** (`sdk-resend-layers.test.js`). The skill row is deleted first
+ and alone, then the AI model — only when it is the one `configureRowSummary` made (named
+ `<table> row summary`, built from the row-summary template). A delete is re-sent while it loses a deadlock
+ and, when its answer is lost or odd, settled by reading the row back. A model another component still
+ uses is refused by the platform (HTTP 400, `0x8004f01f`) and KEPT, which is success — a removal that threw
+ there would fail the teardown step of every table whose model another component had adopted. What the SDK
+ cannot 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
+ still treats every failure as best-effort and does not surface these: 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 change
+ reaches one. `importSolution` now requires `overwriteUnmanagedCustomizations` and `publishWorkflows` (no
+ script calls it, and `sdk-surface-contract.test.js` fails on a new call until it is listed). An Active
+ business process flow is edited in one conditional change set and stays Active — it needs a client with
+ `postRaw`, which the plugin's has — where the build only creates a flow and toggles the state of one that
+ exists, never editing a definition.
+- **Changes in the same release that the plugin's paths DO reach, with the outcome unchanged** — re-test them
+ when one of these paths changes.
+ - *Commands.* A command push writes only its own table's bar, with every check before the first write. The
+ build's commands phase is a command push (`createArtifact('command')`, then `pushArtifact`), so the
+ anchoring, the table-id resolution and the write plan run on it; the requests are the same two as before
+ — one table-id read, one write — and a bar that exists is skipped (`command-real-bundle.test.js`).
+ - *The app-publish token bracket costs requests.* Every `publishArtifact('app')` — the app shell's rewrite of
+ an existing app, the pages finalizer, the AI re-confirm step, and phase 8's envelope when it carries the
+ app; a typical build makes two or three — now reads the app before the publish and again after it, to adopt
+ the tokens the publish rotated when its content is unchanged and its whole token vector was proven, so
+ that a header edit right after needs no fetch. That is about **10 more GETs per app publish** (probed over
+ a fake app after a fetch: none on the previous bundle, ten on this one). The adoption is of no use to the
+ plugin, which fetches before every header or sitemap write because a pages run changes the live app
+ between its first fetch and its finalize, and no step of it was a workaround for a token a publish
+ rotated. The bracket is best-effort: a failed or throttled read leaves the app un-rebaselined and never
+ fails the publish.
+ - *Component proofs.* An app create or update that pins tables reads the app's current layer at most once for
+ its component proofs — the table proof and, when the spec lists the Main forms of a table, the Main-form
+ proof — where each proof read it for itself (one read fewer when both run; the same requests when only the
+ table proof does). An ambiguous layer fails closed (`APP_COMPONENTS_UNVERIFIED`): a create unwinds, an
+ update reports a warning. The plugin's own component reader (`lib/app-components.js`) is separate.
+ - *Unchanged pushes.* A push of an unchanged artifact skips its artifact write and reads less from the
+ workspace. The plugin's own push-if-changed decision (`hasUnsyncedEdits`, which asks the SDK's
+ `diffArtifact`: the copy against its snapshot) is made before the push and is unaffected
+ (`rebuild-writes-real-bundle.test.js`).
+- **Left off: `readConcurrency`**, which overlaps a generative page's file downloads and
+ `fetchSolution`'s component reads. The plugin makes neither read — pages go through
+ `pac model genpage`, and no script fetches a solution — so the option would change nothing.
+ `scripts/tests/sdk-opt-ins.test.js` fails if a script starts to make one of those reads without
+ passing it.
+- **Left off: creating the app as a draft (`published: false`), so the final publish covers it.** A
+ draft is not in the published projection: a by-id read answers 404 and `findArtifact('app')` finds
+ nothing, and so does every other probe the build, verify and download make — the collision gate, the
+ sitemap and navigation reads of the pages phase, the app-shell "does it exist" check. A failed first
+ build would leave an app its own re-run cannot see, the pages phase right after the create would find
+ no sitemap, and a build without `--publish` would never publish it. The app is created published;
+ `scripts/tests/sdk-opt-ins.test.js` pins the SDK facts this rests on and that no script passes
+ `published: false`.
+
+
+`scripts/tests/rebuild-writes-real-bundle.test.js` — the **unchanged-rebuild write budget**, against the
+real bundle and a stateful fake Dataverse (`tests/helpers/fake-dataverse.js`), so what is asserted is
+what reaches the wire, not which SDK methods a mock saw. Every test name starts `rebuild writes:`. A
+first build followed by a rebuild of the same spec with `--publish` must send only the phase-8
+envelope; every change a reconcile makes (a view column or description, a form field, a form event
+handler) must still be pushed exactly once and end up published; an edit an interrupted run left in the
+workspace must still be pushed; an edit a maker made in Dataverse since the last build (a column
+removed from a view, a description changed, a field removed from a form) must be pushed back — the
+workspace copy is clean but the server has moved — and one made while the workspace also holds an
+interrupted run's edit must halt (`LOCAL_EDITS_WOULD_BE_LOST`) without writing; without `--publish`
+each reconcile must still publish its artifact; a build that halts after a reconcile must hand its
+caller the publish it owes; a phase-8 publish that fails or cannot be confirmed must name the views and
+forms it carried — the enriched default views of a table included — on the publish phase and on the halt
+path alike, and on the publish phase also the views, forms and charts the run created (a first
+build's, a rebuild's additions, a chart whose description it wrote), each once and never as a bare id,
+with the requests it sends unchanged, while a first build that halts owes nothing for what it merely
+created; a build killed between its reconcile and its publish must leave a re-run able to publish
+the edit without writing it again; and the membership read must happen once, follow paging, and fall
+back to adding everything when it fails. A table the solution holds with ALL its subcomponents must
+vouch for its views, forms and charts (which have no rows of their own, so the rebuild adds none of
+them), and nothing else: a table held at 1 or 2, another table's components, a failed table lookup and
+a table the maker has since re-segmented must all still get their adds. The fake models only views,
+charts, forms, solution components and `PublishXml` — it throws, naming the request, on anything else
+— and it answers the way the platform does: table rows carry the `rootcomponentbehavior` and the
+table's MetadataId, the subcomponents of a whole table get no row, and `$select` is honoured.
+`unpublished()` answers "was every saved change published?".
+`rebuild-writes-reuse-sites.test.js` and the `rebuild writes:` tests in `sdk-build.test.js` pin each
+reuse site (rule, flow, role, app, sitemap, page manifest) the same way; `solution-membership.test.js`
+and `unsynced-edits.test.js` pin the two helpers' contracts, every doubt of which reads as "add" and
+"push".
**Live end-to-end (app-builder — writes to a real Dataverse env; optional).** All build/verify/
teardown scripts are **dry-run by default**; add `--apply` to write.
diff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.md
index 7e0562eec..22acb5036 100644
--- a/plugins/model-apps/CHANGELOG.md
+++ b/plugins/model-apps/CHANGELOG.md
@@ -5,7 +5,161 @@ All notable changes to the **model-apps** plugin.
Entries are deliberately short: what changed and why it matters to you. The reasoning,
evidence and trade-offs behind a change live in its PR, in `docs/`, or in the linked issue.
-## [Unreleased] — 2.13.0
+## [2.14.0]
+
+The Notes timeline renders, a related-records grid can be placed where you want it, lookups are labelled with the table
+they point to, and view filters resolve choice labels against the environment. Generative pages are checked for style
+shorthands their styling engine drops, their `pac` calls are time-bounded, and more navigation-call shapes build while a
+few that were misread are now refused. The bundled SDK is current, an unchanged rebuild sends a fraction of the writes it
+used to, builds send fewer requests, and verify, download and `check-auth` do more of their work in parallel.
+
+### Added
+
+- **`subgrids[]` placement** (AB#6651699). An entry takes `tab`, `column`, `after` and `before`, to put a related-records
+ grid between sections, in a tab of its own, or in a form column. A rebuild moves a grid an earlier release appended
+ after the Notes section so it sits beside its section; only the grid moves, and fields the same build adds still land
+ in their own sections. `--verify` checks the placement, and the wireframe and the plan show it. Listing a table twice
+ in `subgrids[]` is an error when an entry places it, and a warning otherwise (only one grid per relationship is built).
+- **`primaryAttribute.maxLength`** (a whole number from 1 to 850) sets a new table's name column; it was ignored before.
+ Without it the table is created exactly as before, asking 100 characters for the name column, so the name column comes
+ out as it did before on every environment. An existing table's name column is never changed; a length the platform did
+ not apply is set as the last step of the data model, or reported as a failed step.
+
+### Changed
+
+- **The bundled cds-maker-sdk is current.** Through it:
+ - a Main form create whose answer was lost on the network is recognised when the retry is answered 412, and adopted
+ when it is exactly what the build sent, instead of halting with "already exists" until the workspace is reset (other
+ form types, and a retry answered otherwise, still halt as before);
+ - a form, publisher or view create that a database deadlock rolled back is re-sent by the SDK as well, beyond the
+ build's own re-sends, and so is an app delete that met the platform's search-index race;
+ - a form or dashboard id that belongs to the other kind of record is refused when it is read, written or deleted, with
+ a message that says what it found, and a push can no longer change a form's type;
+ - the routing description of an existing app is saved only on top of the version the build read, so a failed read can
+ no longer overwrite someone else's change (the app's name, description and icon are set when it is created);
+ - reads of tables, columns, relationships and choices ask Dataverse for its latest definition (`Consistency: Strong`),
+ which costs each such read about 10% more;
+ - removing a row summary whose AI model another component still uses keeps the model and succeeds.
+- **`/genpage` finds the environment's languages with a plugin script.** Instead of `pac model list-languages` it reads
+ the base language and every provisioned language with your Azure CLI sign-in and reports each language's code and
+ whether it is written right-to-left; a language the plugin does not recognise keeps its number and is flagged, never
+ guessed. Without a usable Azure CLI sign-in, `/genpage` falls back to `pac model list-languages`, now pinned to the
+ environment it plans for with `--environment` (2.13.0 asked pac's active environment), and says so.
+- **An app folder stays with the environment it was built against.** A build from a folder built against another
+ environment stops before writing anything, names both environments and lists the ways forward, including the folder a
+ teardown would clear. The same environment under its `.api.` host name is reported as such, with the host to run again
+ with. A dry run never takes over the folder, and verifying an app on its own (`verify-model-app.js`) no longer opens the
+ app folder's workspace, so it can check any environment the app is deployed to and leaves the folder untouched.
+- **AI features saved before the app is published** are published and then proved, instead of written twice; one still
+ not in force is reported `NOT YET PUBLISHED`, never applied.
+- **An unchanged rebuild sends far fewer writes.** Views and forms the spec authors are no longer re-sent when they have
+ not changed, the solution's membership is read once so only the components it lacks are added, and with `--publish` the
+ tables a rebuild touched are published together instead of once per view and form (on a sample app with every
+ artifact type: 25 writes instead of 59, 3 publishes instead of 10; the generated default views, the default form, app
+ settings, role privileges and the app's navigation are still written on every rebuild). The tables of the existing
+ views and forms a rebuild reconciles are published before the app is, because publishing the app first would leave
+ any new labels on them unpublished; if that publish is refused, the build stops before writing the app (and runs again
+ at once when the refusal is transient). When a publish fails or cannot be confirmed, the warning names the views,
+ forms and charts on each table that are saved but not live — the generated default views and what a first build
+ created included — instead of a bare form, view or chart id.
+- **Faster runs.** Verify runs its checks four at a time and downloads page code in one `pac` run per 25 pages;
+ `check-auth --env` runs its probes together; download reads each table's labels, option sets and relationships in
+ parallel (the files it writes are the ones a read of one table at a time writes); teardown publishes all default-view
+ resets once; a new table's ordinary columns (up to 25) are created in one request after the table instead of one
+ request each, column for column as before — if the platform refuses that request nothing is created by it and the
+ build creates them one by one, with a warning that says why; a request refused because the table is still busy (HTTP
+ 429) is sent again first, and one whose answer was lost is checked against the table before anything is created again.
+ A verify that fails ends any `pac` run it started and removes its temporary download folder.
+- **Generative-page `pac` calls are time-bounded, and a page upload whose outcome is unknown is not retried.** A `pac model genpage`
+ call (list, download, upload) that outlives its budget (`POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS`) is stopped together
+ with everything it started — on Linux and macOS each process only after its start time is read again, which makes ending an
+ unrelated process that took over the id of one that exited far less likely (not impossible). A timed-out update says it may
+ have landed and how to check; so does an update that fails, which is no longer retried — `pac` can fail while publishing,
+ after it has written the page and recorded its prompt, so a retry could record the prompt a second time — unless `pac`
+ refused its own arguments or files. A timed-out create says the page may exist, or that it was created as `<id>` when `pac`
+ printed the id, and how to finish it. A create whose outcome is not known to be nothing — it timed out, failed after
+ `pac` printed its id, or left a page in the listing — is never sent again, not even by the build's own retry of a
+ transient failure; a create that failed outright and left nothing behind is retried as before.
+- **Updating a generative page also checks the other apps' unpublished navigation** — each app's saved navigation and
+ apps that were never published, including a sitemap linked to an app by its name. A page one of them holds stops the
+ update and names the app; a never-published app with no navigation does not. The check runs again right before the
+ first page is written in place and once after the last: a page another app takes in while the build runs stops it
+ before any page it began with is updated in place, or, if it lands while the pages upload, is reported with the app that holds it.
+ A page the build itself created is left out of both.
+- **The record of what a build applied is the page source it read and checked**, so a page saved while a build runs is
+ checked by the next build instead of being found unchanged.
+- **More pages with a hint in parentheses resolve their navigation calls.** JSX text in parentheses that holds an `=`, a
+ `[` or an `@` followed by a `/`, a `<` or a back-tick — `<p>(a = b/c)</p>`, ``<p>(x = y, `code`)</p>``,
+ `<p>(@user/repo)</p>` — or that has a link on the next line, is read as the element it is in, so the navigation call
+ after it resolves where 2.13.0 refused the page; such text no longer needs the expression container 2.13.0 suggested.
+ `return (navigateTo)({ … })` builds too.
+- **A few pages that 2.13.0 resolved are now refused, naming the guess `generic`.** This happens where such a hint stands
+ where a member of a type could also begin — after `return`, `?` or another keyword, or after a separator — and one of
+ its lines ends unfinished before a `//` note (an open bracket, an `=` or an operator), with a later line that starts
+ with `/`: the text up to that `/` can also start a type whose regular expression holds the element's closing tag.
+ 2.13.0 took the end of the note for the token before the `/`; the build now refuses instead of guessing. Moving the
+ navigation call before the hint, or ending the line with a word before the `//`, avoids the refusal. The same applies
+ to an element whose text holds a nested element with a quote, a back-tick or `//`, followed by a string that holds the
+ element's closing tag.
+
+### Fixed
+
+- **The Notes timeline renders** ([#680]). It is written the way Dynamics shows it — control id `notescontrol` in a tall
+ cell over the empty rows it spans — instead of a one-row cell that published but never appeared. A full build (not
+ `--changed-only`) repairs an older Notes section in place, after taking out of it any field the layout removes or places
+ elsewhere; a timeline you resized is left alone, and a section still holding a control the build does not move is left
+ and reported. `--verify` fails a form whose timeline would not render and says what to do: run a full build where the
+ build takes the stray fields out itself, which control to move in the maker where it does not — and where it cannot
+ tell (a field placed on the form more than once, or anchored to one) it says so.
+- **Lookup columns are labelled with the parent table's display name** (AB#6691205). A relationship with no
+ `lookup.displayName` now labels the lookup column — and the form field that carries it — "Project" instead of the
+ logical name `new_project`: from the declared parent table, else from the environment (an `existing: true` `incident`
+ is "Case"), in every language the label is written in. A rebuild relabels a column or form field still carrying the old
+ default — each cell of a field the form holds more than once; it never changes a label you set. A download leaves out a
+ label equal to that default.
+- **View filters resolve choice labels against the environment** (AB#6691114), including a column of an existing table
+ the spec does not declare (`account.industrycode`) and a global choice that already existed, instead of being sent to
+ Dataverse as text or as the spec's own position number. A label that matches no option stops the build, listing the
+ valid ones, before any view is written (and before anything is written where the environment already shows it; a spec
+ with a localized label is checked after its tables and columns are written). An option a maker renamed still resolves
+ to the spec's number, as in 2.13.0, now with a warning; the build stops instead where the environment shows the options
+ are numbered otherwise — for example options inserted into the spec after the column was built, which 2.13.0 silently
+ bound to whichever option held that number — and says why. A view that already exists keeps its filters; where 2.13.0
+ built one on an option the environment numbers otherwise, `--verify` now reports it.
+- **Quick View sections stay one column**, as Quick Create sections already did. A field-heavy Quick View section got two
+ columns, which the platform refuses for this form type, and the build failed part-way.
+- **A page keyed like a Windows device name** (`con`, `nul`, `aux`, `com1`, …) is handed to `pac` as a file: the build's
+ copy of each page it uploads is named `page-<key>.tsx`, which Windows never reads as a device, where 2.13.0 named a
+ navigation page's copy `<key>.tsx`.
+- **Generative pages are checked for the style shorthands Griffel drops** (AB#6691124): `all`, `borderColor`,
+ `borderStyle`, `borderWidth`, `borderBlock*` and `borderInline*` in `makeStyles`, which deployed silently without their
+ style. A build stops before the pages phase writes anything for a page it creates or whose source changed since the
+ last recorded build, and only warns for a page it sends again unchanged; `/genpage` refuses a create, or an update that
+ adds such a key or changes its value. `node scripts/check-griffel-styles.js --file <page.tsx>` lists each key and the
+ longhands to write. A style object the check cannot see — passed in (`makeStyles(styles)`), given to a slot or a
+ selector as a variable, or spread in (`...base`) — is reported too, and so are a key computed from an expression
+ (`[key]: …`) and a getter that runs on a style object (`get color() { … }`), whose code the check does not read;
+ all are held like a call the check cannot read, and Fluent's own `shorthands.*(…)` helpers and
+ `typographyStyles.*` entries may be spread (`shorthands.transition` with one argument only as an array, a string or
+ a number written in place). What is uploaded is what was checked: the build sends every page from a copy of
+ the bytes it checked, and `genpage-upload.js` reads the page once and uploads a copy of those bytes, so a save to the
+ file while either runs is not sent unchecked. `genpage-upload.js` no longer takes `--compiled-code-file`, whose
+ JavaScript `pac` would deploy instead of the checked page.
+- **A `PAGEREF_` token in a string, template or regular expression of a page's types is no longer rewritten** in shapes
+ 2.13.0 misread: a nested element in a parameter default or a computed name whose text holds a quote, a back-tick or
+ `//` (two on one line included); a regular expression on the line after a `//` note that follows an open bracket, an
+ `=` or an operator in a type; and an accessor whose computed name holds one (`get [a, // note`, a line break, then
+ `/…/]()`). Such a page is now refused, naming the guess, instead of being deployed with the string changed.
+- **Connector discovery reads `pac connection list` as `pac` prints it**: an environment with no connections reads as
+ empty, and output the reader does not recognise is refused instead of being read as empty.
+- **`dataverse-request.js` keeps its path under the Web API root** ([#705]). A path whose `..` segments — written
+ plainly, percent-encoded or joined by an encoded slash — would leave `/api/data/v9.2/` is refused before a token is
+ read.
+
+[#680]: https://github.com/microsoft/power-platform-skills/issues/680
+[#705]: https://github.com/microsoft/power-platform-skills/issues/705
+
+## [2.13.0]
An app's hidden tables and its list of Main forms now survive a download and rebuild, and
relationships that share a name are caught. A generative page edited in the maker portal is no longer
diff --git a/plugins/model-apps/README.md b/plugins/model-apps/README.md
index 8cf88a507..b35d5eabe 100644
--- a/plugins/model-apps/README.md
+++ b/plugins/model-apps/README.md
@@ -27,13 +27,19 @@ claude --plugin-dir /path/to/power-platform-skills/plugins/model-apps
| [PAC CLI](https://learn.microsoft.com/en-us/power-platform/developer/cli/introduction) > 2.10.0 | Schema generation, app creation, table listing, deployment | `dotnet tool install -g Microsoft.PowerApps.CLI.Tool` |
| [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli) (`az`) | Dataverse Web API auth for entity creation | `winget install Microsoft.AzureCLI` |
-After installing `az`, run `az login` with the same identity as your active `pac auth list` profile. Without `az`, the `/genpage` skill still works for pages over existing entities or mock data — it only fails when entity creation is needed.
+After installing `az`, run `az login` with the same identity as your active `pac auth list` profile. Without `az`, the `/genpage` skill still works for pages over existing entities or mock data — it only fails when entity creation is needed. (Detecting the environment's languages uses `az` when it is signed in and falls back to `pac model list-languages --environment '<envUrl>'` when it is not.)
Each Azure CLI call (a token, `az account show`) may take up to **60 seconds** — a busy machine can
take most of that just to start `az`. A call that runs out of time is reported as a timeout (the
pre-flight's `az_timeout`), never as a missing or signed-out CLI. To allow longer, set
`POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS` in milliseconds (1000–900000), for example `120000`.
+Each `pac` call for generative pages is time-bounded too: **3 minutes** to list or download pages, **10 minutes** to
+upload one. A call that runs out of time is stopped together with everything it started, and the message says what to
+do; a page create whose outcome is unknown is never sent again. To allow longer, set
+`POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS` in milliseconds (1000–3600000); it applies to every `pac model genpage` call (list,
+download and upload).
+
## Feature flags (experimental & in-progress)
Some capabilities ship **OFF by default** while their cross-repo dependencies roll
diff --git a/plugins/model-apps/agents/genpage-page-builder.md b/plugins/model-apps/agents/genpage-page-builder.md
index 96d57d39d..380a76562 100644
--- a/plugins/model-apps/agents/genpage-page-builder.md
+++ b/plugins/model-apps/agents/genpage-page-builder.md
@@ -141,11 +141,34 @@ import has been Grep-validated against the verified list.
(a type error, or a reference to a column that does not exist, still transpiles
and writes JavaScript), and it does not execute `makeStyles`. A clean transpile is
therefore no proof that the page is type-safe, and unsupported Griffel shorthands
-can compile and then log runtime errors in the browser. Before returning, Grep the
-generated `.tsx` with the regex `['"]?borderWidth['"]?\s*:` so unquoted, quoted,
-and spaced property syntax are all caught. Replace every match with the four
-explicit longhands: `borderTopWidth`, `borderRightWidth`, `borderBottomWidth`, and
-`borderLeftWidth`. Do not return a file that still matches the regex.
+can compile and then log runtime errors in the browser. Before returning, review
+every `makeStyles` object you wrote against this rule:
+
+Griffel does not support ten CSS shorthands, and `makeStyles` drops them at
+runtime: the page type-checks, transpiles and deploys, then renders without the
+border, color or reset. They are `all`, `borderColor`, `borderStyle`,
+`borderWidth`, `borderBlock`, `borderBlockStart`, `borderBlockEnd`,
+`borderInline`, `borderInlineStart` and `borderInlineEnd`. Write longhands
+instead: `borderColor`, `borderStyle` and `borderWidth` become one longhand per
+side, `border` + `Top`, `Right`, `Bottom` or `Left` + `Color`, `Style` or `Width`
+(`borderWidth` → `borderTopWidth`, `borderRightWidth`, `borderBottomWidth`,
+`borderLeftWidth`); `borderBlock`, `borderInline` and their `Start` and `End`
+forms become the `Width`, `Style` and `Color` longhands of the sides they name
+(`borderBlockStart` → `borderBlockStartWidth`, `borderBlockStartStyle`,
+`borderBlockStartColor`; `borderBlock` → those and the three `borderBlockEnd…`
+ones); `all` has no longhands, so set the properties you need one by one. Every
+other shorthand (`padding`, `margin`, `border`, `borderRadius`, `gap`,
+`outline`) is supported, and an inline `style={{ … }}` is not Griffel at all.
+
+You have no shell, so you cannot run the checker: after you return, the
+orchestrator runs `${PLUGIN_ROOT}/scripts/check-griffel-styles.js` on your file and
+fixes anything it reports before the page is deployed. It reads the style objects
+written inline in the call, `makeStyles({ … })`, so write every one that way. To
+list the places to look, Grep the file with the regex
+`(^|[\s{,'"])(all|borderColor|borderStyle|borderWidth|borderBlock|borderBlockStart|borderBlockEnd|borderInline|borderInlineStart|borderInlineEnd)['"]?\]?\s*:`
+and look at each match: one inside a `makeStyles` object is the defect, and one in
+a string, a comment or an inline `style={{ … }}` is fine. Do not return a file that
+still has one in a `makeStyles` object.
## Step 3 — Read References and Samples
@@ -374,6 +397,7 @@ export default GeneratedComponent;
is not recognised, so the token in it halts the build as stray. **Write the plain form,
`navigateTo({ … })`** — a parenthesised callee, `(navigateTo)({ … })`, is read only at the start of a
statement or after `;` `{` `(` `[` `,` `:` a ternary `?`, an operator ending in `=`, `=>`, `&&`, `||` or `??`,
+ or the keyword `return` on the same line (`return (navigateTo)({ … })`; not `await` or `yield`),
and any other spelling (`factory!(navigateTo)({ … })`) halts as stray. A `PAGEREF_` token may appear
nowhere but that double-quoted `pageId` literal — **not in a comment of any kind**: a `//` comment, a
block comment, a trailing comment (`navigateTo({ … }); // PAGEREF_x`) and a JSX `{/* PAGEREF_x */}` all halt
diff --git a/plugins/model-apps/agents/genpage-planner.md b/plugins/model-apps/agents/genpage-planner.md
index beb4552e7..c33e3e5e4 100644
--- a/plugins/model-apps/agents/genpage-planner.md
+++ b/plugins/model-apps/agents/genpage-planner.md
@@ -75,7 +75,9 @@ section MUST record commands and structured calls verbatim — not just their
outcomes — because the eval harness greps the log for these tokens. Concretely:
- Every shell command invocation is recorded on its own line as
- `` `node --version` `` / `` `pac help` `` / `` `pac auth list` `` / `` `pac model list-tables --search '<term>'` ``. Include the literal flag values. Result goes on the next line.
+ `` `node --version` `` / `` `pac help` `` / `` `pac auth list` `` / `` `pac model list-tables --search '<term>'` `` /
+ `` `node "${PLUGIN_ROOT}/scripts/list-languages.js" --env '<envUrl>'` `` /
+ `` `pac model list-languages --environment '<envUrl>'` `` (the fallback below). Include the literal flag values. Result goes on the next line.
- Every question **the orchestrator asks on your behalf** is recorded as
`AskUserQuestion: <question text> → <selected option>`. The literal string
`AskUserQuestion` is required. You do not make that call — you return a
@@ -156,30 +158,84 @@ These questions are asked by the ORCHESTRATOR, one at a time. Return them as a
1. **"Create new page(s) or edit an existing one?"**
- If edit: return immediately with `{ "action": "edit" }` — the orchestrator
- handles edits inline, not through agents. **Do not run `list-languages` or
+ handles edits inline, not through agents. **Do not run `list-languages.js` or
continue further.**
- If new: continue to next question.
### Detect Configured Languages
-After confirming the user wants to create **new** pages, detect configured languages:
+After confirming the user wants to create **new** pages, detect the languages the
+environment has provisioned. Try the plugin's own script first: it reads them through the
+Dataverse Web API with the Azure CLI (`az`) token.
+
+```bash
+node "${PLUGIN_ROOT}/scripts/list-languages.js" --env '<envUrl>'
+```
+
+`<envUrl>` is the selected environment's `Environment Url` from the `pac auth list` table
+(Step 2; the `Org URL:` line of `pac org who` is the same address): the https origin only — no
+path, no trailing slash — as the `$ENV_URL` the Solution Selection query below passes to
+`dataverse-request.js`.
+
+**Exit 0** — stdout is one JSON line. Its non-ASCII characters (the dash in `summary`, an
+accented name) are written as `\uXXXX` escapes, so that no console code page can garble them:
+read the decoded strings.
+
+```json
+{"ok":true,"baseLanguage":{"lcid":1033,"code":"en-US","name":"English (United States)","rtl":false},"languages":[{"lcid":1033,"code":"en-US","name":"English (United States)","rtl":false},{"lcid":1025,"code":"ar-SA","name":"Arabic (Saudi Arabia)","rtl":true}],"unmapped":[],"summary":["1033 en-US \u2014 RTL: No","1025 ar-SA \u2014 RTL: Yes"]}
+```
+
+`languages` are the **provisioned** languages — the ones a page can be written in — in the
+server's order; `baseLanguage` is the environment's base language. If multiple languages are
+configured (or any non-English language), localization will be included in the generated
+code. Include the detected languages when reporting the environment to the user. Record each
+language's **LCID, Code and RTL** exactly as the script reports them — its `summary` lines
+are the form the plan carries, written with a real `—`, for example `1025 ar-SA — RTL: Yes`.
+
+The page builder takes text direction from that RTL value, never from a list of LCIDs it
+remembers (`references/localization.md` → *RTL Layout Support*).
+
+- **An LCID in `unmapped`** has no culture code in the plugin's table, so its `code`,
+ `name` and `rtl` are `null` and its summary line reads `<LCID> unknown — RTL: unknown`.
+ Record it that way and tell the user which LCID it is. Do not guess a code or a
+ direction: the page builder gives such a language no entry of its own.
+
+**Any non-zero exit — or no answer before your shell tool gives up — means the script could not
+read the languages; decide by the exit status, never by the wording of the message.** A failed read prints
+`{ "ok": false, "error": "…", "code": "…" }` on stdout (`code` only when the SDK gave one); a
+usage error, such as an `--env` that carries a path, prints nothing there and names the flag on
+stderr. The cause is most often the Azure CLI: not installed, not signed in, too slow to answer,
+or signed in to another tenant than the `pac` profile. `/genpage` has never needed `az` for a
+page over existing entities or mock data, so whatever the cause, do not stop and do not ask the
+user to run `az login`: fall back to the command that read the languages before this script,
+which signs in through `pac`:
```powershell
-pac model list-languages
+pac model list-languages --environment '<envUrl>'
```
-Note the output. If multiple languages are configured (or any non-English language),
-localization will be included in the generated code. Include the detected languages
-when reporting the environment to the user. Record each language's **LCID, Code and RTL**
-columns exactly as PAC prints them, for example:
+Pass the same `<envUrl>` the script was given: without `--environment`, `pac` answers for the
+active organization of its auth profile, which is not necessarily the environment this plan is
+for, and the plan would carry another environment's languages under this one's URL.
+
+Its table carries the same facts:
```
LCID Language Code RTL
1025 Arabic (Saudi Arabia) ar-SA Yes
```
-The page builder takes text direction from that RTL value, never from a list of LCIDs it
-remembers (`references/localization.md` → *RTL Layout Support*).
+Take each row's **LCID**, **Code** and **RTL** columns as the languages, and write the plan's
+lines from them as `<LCID> <Code> — RTL: Yes|No`. Then **say that you did**:
+
+- In `workflow-log.md`, record the script's command line with its result (its stdout, or its
+ stderr when stdout is empty), and then the `pac model list-languages` line with its table,
+ each verbatim.
+- In your report of the environment, say so: "Languages read with `pac model list-languages`:
+ the languages script could not read them (<its `error`, or its stderr>)."
+
+If `pac model list-languages` fails as well, report that and stop. Never assume the
+environment is English-only — the plan's localization decision depends on this answer.
### Continue Requirements Gathering
@@ -500,8 +556,9 @@ plan mode does not reach the user from a subagent.
- [solution unique name and prefix — always shown, "Default / new" for code-only flows]
### Localization
-- [each detected language as `<LCID> <Code> — RTL: Yes|No` from `pac model list-languages`
- (e.g. `1025 ar-SA — RTL: Yes`), or "English only — no localization needed"]
+- [each detected language as `<LCID> <Code> — RTL: Yes|No` — the `summary` lines of `list-languages.js`,
+ or the rows of `pac model list-languages` when you fell back to it (e.g. `1025 ar-SA — RTL: Yes`) —
+ or "English only — no localization needed"]
### Design
- [styling preferences, features, accessibility notes from requirements]
diff --git a/plugins/model-apps/docs/app-builder-capabilities.md b/plugins/model-apps/docs/app-builder-capabilities.md
index 74ce0728d..f2dda02bb 100644
--- a/plugins/model-apps/docs/app-builder-capabilities.md
+++ b/plugins/model-apps/docs/app-builder-capabilities.md
@@ -22,13 +22,13 @@ 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. `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` — 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).
+- 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 reconciles touched 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) instead of once per view and form, 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` — 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.
- Guardrail lint (`spec-lint.js`) + hard validator (`app-spec.js`). 🧪 full `node:test` suite + the vendored SDK's Jest suite green (`node scripts/run-tests.js --with-sdk <ppux>`).
### Data model (Tier 1) — ✅ verified live
- All column types: Text · Memo · Choice · MultiChoice · Boolean · Money · DateTime · Integer · BigInt · Decimal · Double · File · Image · AutoNumber · Customer (with per-type options), incl. AutoNumber primary columns.
- Global option sets, status reasons (idempotent, deterministic pinned values), alternate keys (idempotent).
-- Relationships: OneToMany (lookup) **and** ManyToMany; Customer (polymorphic) columns.
+- Relationships: OneToMany (lookup) **and** ManyToMany; Customer (polymorphic) columns. An omitted `lookup.displayName` defaults to the parent table's display name (the declared table's; else the environment's, for a table the spec does not declare or declares without a `displayName` that the build did not create — `incident` is "Case"; else a humanized name); a rebuild relabels only the old logical-name default, in the build's own language, never a maker's label, and download leaves out a label equal to the default or to the old default. Live-verified in a single-language environment: lookups labelled with their parent's logical name (a custom table and `contact`) were repaired on the column and on the form's auto-layout field, a form field labelled with the lookup's own logical name was repaired while a label a maker set on another field was kept, an unchanged rebuild wrote no label update, a fresh build labelled the column at creation (with the parent's display name), and a label a maker set through the SDK survived a rebuild, with a field still on the old default then following it; a lookup to a declared `existing: true` table (`systemuser`) was labelled "User" from the environment, on a fresh build and as a repair of the old default; and on an environment with two languages (English and Spanish), a new lookup was labelled with its parent's name in both ("Area" / "Zona"), where 2.13.0 wrote the parent's logical name in English only. ⚠ **Not live-verified**: a repair in a second language, and download leaving a label out.
- Sample data: Choice/MultiChoice label→int resolution (inline **and** global choices), `$parent`/`$parents` lookup binds (incl. junction rows with both sides), custom status reasons; resolve-by-name idempotency via the SDK's `seedRecordGraph`.
- ⚠ Calculated / Rollup formula columns — `source` + `formula` plumbed through, **not live-verified**.
- **Per-column write permissions** (`isValidForCreate` / `isValidForUpdate` / `isValidForRead`) —
@@ -94,7 +94,7 @@ apart deliberately.
authored columns.
### Forms, views & charts — ✅ verified live
-- Adaptive main forms (auto + explicit tabs/sections), related-record sub-grids (1:N **and** N:N), Notes/timeline section.
+- Adaptive main forms (auto + explicit tabs/sections), related-record sub-grids (1:N **and** N:N, placed with `tab` / `column` / `after` / `before`), Notes/timeline section.
Explicit edits order tabs and sections, **not existing fields**. New listed fields and relative
`fieldOptions[x].after` placement are occupancy-safe; a full row may split, and an unsafe move is
skipped with a warning. Stored overflow repair, idempotent rebuilds and middle insertion are
@@ -114,7 +114,7 @@ apart deliberately.
`<DisplayConditions Order="2">` on the restricted form, `<Everyone />` on its unrestricted sibling.
(AB#6648526)
- Form JS event handlers (`onload`/`onsave`/`onchange`) wired via web resources.
-- Views with rich filters (`eq-userid`/`this-week`/`in`/`not-in`/… + Choice-label resolution); default Active/Inactive view **column enrichment** via the SDK's `enrichDefaultViews`.
+- Views with rich filters (`eq-userid`/`this-week`/`in`/`not-in`/… + Choice-label resolution against the environment's own option metadata — a label no option answers to stops the build before any view is written, and before anything is written where the environment already shows it (where the spec numbers a column's options — inline, or a declared global choice — an option a maker renamed still resolves to the spec's own number, with a warning that says it is an assumption, unless the environment shows the options are numbered otherwise, as when options were added after the column was built); a spec with a localized label is checked in the views phase only, so no label-bearing read runs ahead of creating a multi-language label); default Active/Inactive view **column enrichment** via the SDK's `enrichDefaultViews`. Live-verified: `account.industrycode` "Accounting" resolved to its option value on create, the dry run marked a view with a mistyped label `? unknown` and listed the valid labels, a typo halted the build before anything was written (no solution, publisher or table), and an inline option a maker renamed still resolved to the spec's own number, with a warning, and `--verify` passed; an option renamed in a declared global choice did the same (a new view got the spec's number, and `--verify` passed on a view 2.13.0 had built), and an option inserted into the spec's list after the column was built stopped the build before any view was written, where 2.13.0 bound the wrong option, silently; an option a maker added (at the next free number, or in another publisher's range) or deleted and re-created, together with a rename of the filtered option, was bound to the spec's own number with a warning, and `--verify` passed; so was an option renamed only in case; options renamed only in case on a column whose spec has since numbered them otherwise stopped the build before the view was written, naming the option; and the dry run marked every existing view `= reuse` with the same warnings the build gives, including one whose filter label no longer names an option. ⚠ **Not live-verified**: a column bound to a system global choice or to a declared one that already existed with other values, MultiChoice and status-reason labels, the global option set read, `--verify` on those columns, and the localized-spec deferral.
- **Editing an existing view is additive.** A rebuild appends spec columns the view lacks and keeps
every column already there, so a column a maker added in the designer survives — and a column
removed from the spec, or a new order, does not apply. Filters and sort are not re-applied either
diff --git a/plugins/model-apps/docs/app-builder-design.md b/plugins/model-apps/docs/app-builder-design.md
index 114265c5b..46aa663a9 100644
--- a/plugins/model-apps/docs/app-builder-design.md
+++ b/plugins/model-apps/docs/app-builder-design.md
@@ -242,7 +242,8 @@ persistence is therefore **foundational**, and the mechanism is **decided** (not
dataSources, navigatesTo, pageInput }], design }` — not just id/name, so the round-trip below
actually restores purpose/navigation/design. It travels inside the solution and survives download.
- **Lifecycle is explicit.** On first build the manifest web resource is created; its **solution
- membership is re-asserted every run** (idempotent add, not only on first creation); on rebuild its
+ membership is re-asserted every run** (an idempotent add, not only on first creation — skipped only
+ when the build's one read of the solution proves it is already a member); on rebuild its
content is **updated in place** via `updateWebResource` (`MakerSdk.ts:529-543`) — the engine today
reuses an existing web resource *without* updating its content (`sdk-build.js:565-580`), so the
manifest needs the update path, not plain reuse. `planTeardown` removes it (it currently deletes
diff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.md
index bb720fcf6..cb6424559 100644
--- a/plugins/model-apps/references/app-spec-schema.md
+++ b/plugins/model-apps/references/app-spec-schema.md
@@ -404,6 +404,8 @@ spec with its last snapshot, not with the deployed row, so it does not notice).
"primaryAttribute": { "schemaName": "new_subject", "displayName": "Subject" },
// primary can be auto-numbered (the number IS the record identity — recommended for orders/cases):
// "primaryAttribute": { "schemaName": "new_ordernumber", "displayName": "Order Number", "autoNumberFormat": "WO-{SEQNUM:5}" },
+ // and its length can be set (1–850 characters; when omitted the build asks for 100, as before) — see "Primary column length" below:
+ // "primaryAttribute": { "schemaName": "new_subject", "displayName": "Subject", "maxLength": 120 },
"columns": [
{ "schemaName": "new_priority", "displayName": "Priority", "type": "Choice", "options": ["Low","High"],
"description": "How urgently the ticket needs attention." }, // RECOMMENDED — see below
@@ -457,6 +459,32 @@ spec with its last snapshot, not with the deployed row, so it does not notice).
(see `globalChoices` below). **Customer** is a polymorphic account/contact lookup.
- **AutoNumber** can also be the **primary** column — put `autoNumberFormat` on `primaryAttribute`
(above) instead of adding a separate column, so the generated number is the record identity.
+- **Primary column length — `primaryAttribute.maxLength`** (optional; a whole number from 1 to 850, the
+ most Dataverse allows for a table's name column — more is refused by Dataverse, so
+ anything else is rejected at validation, for `/genpage` and `/app-builder` input as well). Without it
+ the build asks for **100** characters, the length it has always asked for, whether the name column is
+ text or auto-numbered (`autoNumberFormat`). The table is created as before, with its name column alone
+ (its other columns follow in a request of their own), and what an environment makes of the 100 asked can
+ differ — some keep it, and some make a plain text name column 850 characters long whatever length is asked
+ (100 and 120 both came back 850) while keeping the length asked of an auto-numbered one — and the build
+ leaves a name column without `maxLength` as the environment made it, as before. A length you give is
+ applied **when the table is created**: once everything else in the data model has been created (or as far as
+ a build that stops got), the build
+ reads the name column back and, where the environment did not keep the length, updates it to the value you
+ gave.
+ The length is fixed at that point: a rebuild never changes the name column of a table that already exists —
+ neither to this value nor back to the default — because shortening a column that holds data can fail or
+ lose text, and a rebuild must not undo a length someone widened in Maker. Like every column's
+ `maxLength`, it is not reconciled afterwards; to change it on an existing table, change it in Maker. If
+ the length cannot be set after the create, the build reports a failed `primary column length` step that
+ names the table, the length asked and the length the platform made, and goes on — or, when the data model
+ stopped first, says so, and that a re-run leaves the column as it is. One exception to
+ "applied when the table is created": a table the build finds **after** its create — the answer to the
+ create was lost, or another maker created the table first — is not written to, because nothing shows that
+ this build made it. The build reads its name column's length once instead, and warns when it is not the
+ length the spec asks for (or cannot be read). A build that stops because the table was created but cannot
+ be read back yet (`TABLE_METADATA_NOT_VISIBLE`) warns that the length may not have been applied, since a
+ re-run leaves an existing table's name column alone.
### `visualization` — custom grid rendering (optional, PREVIEW)
@@ -551,6 +579,38 @@ list with "reach for it when…" guidance.
"lookup": { "schemaName": "new_CustomerId", "displayName": "Customer" } }
```
- `referenced` = the "one" (parent); `referencing` = the "many" (child, gets the lookup column).
+- **`lookup.displayName`** labels the lookup column — in the table's column list, in views, and on the
+ form field that carries it. Omit it and the lookup is labelled like the table it points at, as the
+ maker portal does ("Project" for a lookup to `new_project`), in this order:
+ 1. the `displayName` you set — a plain string, or a language-code map — which always wins;
+ 2. the referenced table's own `displayName` when `entities[]` declares it. A language-code map
+ stays a map, so the column carries one label per language;
+ 3. for a parent whose name the spec cannot give — a table it does not declare (`account`, `contact`,
+ `systemuser`…), or one it declares **without** a `displayName` that the build did not create (an
+ `"existing": true` `incident` is "Case", not "Incident"): the display name the environment reports for
+ it, read when the lookup is created;
+ 4. a humanized form of the table's name (`contoso_ProjectPhase` → "Project Phase"), only when
+ nothing above applies — an offline surface, a read that failed, or a table the spec declares
+ with no `displayName` and the build creates.
+
+ Offline surfaces (the plan, the previews, `app-spec.md`) never ask the environment, so wherever
+ step 3 applies they show step 4; the column itself is labelled by step 3. Where the build may find a
+ declared parent that has no `displayName` already there, the plan says so ("`Project`, or the label from
+ the environment if `new_project` is already there"). Relationships whose lookup label is a language-code map
+ are created before the others, in the order the plan lists them.
+- **A rebuild repairs only the old default.** Builds used to label an omitted `lookup.displayName`
+ with the parent's *logical name* (`new_project`), and a form field the SDK could not resolve the
+ column for with the lookup's own logical name (`new_projectid`). A rebuild relabels such a lookup column — and
+ the form field the build's auto layout labelled with it — to the default above only when the spec omits
+ `lookup.displayName` **and** the deployed label is exactly the old default (case counts, so a correct
+ "Contact" is never mistaken for one): for the column, the parent's lower-case logical name in a single
+ language, which is the one the build writes; for a form field, that name or the lookup's own lower-case
+ logical name. A column labelled with the lookup's own name was labelled by a person, so it is kept. An old
+ default in
+ another language is left alone, with a warning: a write in the build's language would leave two, one
+ of them still the identifier. A label a maker chose in the designer is never touched, and neither
+ is one the spec sets explicitly. A form field that still holds the old default follows the column's
+ current label, whatever that is.
- The relationship's schema name defaults to `<referenced>_<referencing>` and **must differ**
from `lookup.schemaName` (Dataverse rejects a collision — `lintAppSpec` flags this, so
`scripts/lint-app-spec.js` catches it before you deploy; note the build itself does **not**
@@ -580,7 +640,10 @@ run the lint, so an unlinted spec hits the failure at build time instead).
**What a download reconstructs.** `download-model-app.js` rebuilds `relationships[]` from live
metadata, keeping the lookup's deployed casing (`new_CustomerId`, not `new_customerid`) and its
-label. It emits an explicit `schemaName` whenever the deployed name is not the one this
+label. The label is left out when it is the default a rebuild would write (the parent
+table's display name) or the old default an earlier build left on it (the parent's logical name, which
+a rebuild repairs — an explicit label is never repaired, so writing the identifier out would keep it for
+good), so a downloaded spec stays minimal; a label that differs is written out as it is. It emits an explicit `schemaName` whenever the deployed name is not the one this
solution's prefix would generate, including a name that uses another publisher's prefix. Omitting
that name would make a rebuild into the **same** environment create under a different name and
fail on the lookup that already exists. A foreign-prefix name is a lint warning: a new environment
@@ -613,7 +676,7 @@ why they need naming here at all.
// optional rich filters (beyond the default active-records condition):
"filters": [
{ "attr": "ownerid", "op": "eq-userid" }, // "my" records — no value
- { "attr": "new_priority", "op": "not-in", "values": ["Low"] }, // multi-value (Choice labels resolve to ints)
+ { "attr": "new_priority", "op": "not-in", "values": ["Low"] }, // multi-value (Choice labels resolve to option values)
{ "attr": "new_duedate", "op": "this-week" } // relative-date — no value
] }
```
@@ -626,9 +689,83 @@ why they need naming here at all.
- `activeOnly` (default `true`) adds `statecode eq 0`. `filters[]` add conditions: `op` is any
FetchXML operator — `eq`/`ne`/`lt`/`le`/`gt`/`ge`/`like`, no-value ops (`eq-userid`, `null`,
`not-null`, `this-week`/`this-month`/`today`/…), and multi-value `in`/`not-in` (use `values[]`).
- Choice **labels** in `value`/`values` resolve to option ints. This is what "My Open Orders"
+ Choice **labels** in `value`/`values` resolve to option values, as described next. This is what "My Open Orders"
(`ownerid eq-userid` + `new_status not-in [Completed, Cancelled]`) and "Completed This Week"
(`new_status eq Completed` + `modifiedon this-week`) need — no post-build FetchXML patching.
+- **A Choice label in a filter is resolved against the environment, not guessed.** `value` (or `values[]`)
+ of `eq`/`ne`/`neq`/`in`/`not-in`, and of `contain-values`/`not-contain-values` on a multi-select,
+ may name an option by its label — in any language the option has — or by its integer value. Only
+ the environment knows the numbers. A filter on a column of a table you reuse (`account.industrycode`, a
+ local option set — or a column bound to a system global choice) needs no column declared for it: the label
+ is resolved from the environment, where an unresolved label used to reach Dataverse as text and be rejected
+ part-way through the build. A declared global choice that already existed with other values than the spec
+ lists holds the environment's numbers too. (A column bound to a global choice that `globalChoices[]` does
+ not declare is a lint error, and stays one.) So the build reads the column's options from the environment
+ (a table is read at most twice per build — once before anything is written, once in the views phase, see
+ below) and resolves the label there. Only where the environment cannot say — the
+ table is not there yet, or the read failed — does a declared Choice column fall back to the options the spec
+ declares (inline, or a declared `globalChoices[]`, numbered from 100000000), and the build then warns, since
+ that numbering is right only for an option set this build created. (A column bound to a declared global
+ choice is first resolved from the global choice itself, which the build reads by name; the spec's numbering
+ is the last resort.) The rules:
+ - an **integer** — or a comma-separated list of integers, the form a multi-select takes — is an option
+ value and is used as written, with no read;
+ - a label that matches **no option stops the build**, naming the view, the column and the valid labels (the
+ first 25, then a count). It is never sent as a value. Every unresolved label of every view is reported in
+ the one halt. The one exception is a column whose options **your spec numbers** — `options[]` on the
+ column, or a global choice that `globalChoices[]` declares (100000000 + index): where the environment has
+ no option with that label but has an option on the number your spec gives it — a maker renamed "Gold" to
+ "Gold Tier", or a translation never reached the environment — the build uses that number and warns that
+ it is taking that option to be the one you meant. It never does so where the environment shows the
+ numbering is not yours: an option on that number that goes by the name of another option of yours, or a
+ label of your spec that the environment carries only on other numbers *and that shows the numbering moved* —
+ the label is one of the labels of the option you filter on (in any language), or it sits on a number your spec gives
+ another option (you inserted or reordered options after the column was built — a rebuild does not change an
+ existing column's options — or another app created the column or the global choice in another order). A label
+ on a number your spec does not use at all is an option a maker added or re-made elsewhere, and does not count
+ against your numbers. Those, and any label with no option on its number, still stop the build, and the
+ message says why your number was not used (*The spec numbers "Gold" 100000001, but the environment shows
+ another numbering ("Bronze" is numbered 100000003 there, 100000002 in the spec), so that number is not
+ used.*). That check ignores the case of a label; resolving a label still takes its exact text. Where
+ nothing the environment carries contradicts your number — every option renamed, say — the build uses it,
+ as it always did, and the warning is the only trace: use the option's integer value to take the choice out of
+ the build's hands;
+ - a label that names **more than one option** (the same text on two options, in different languages) stops
+ the build too — use the integer of the one you mean — unless the number your spec gives that label is
+ one of those options (a maker added a second option with the same text): the build then uses that one
+ and warns;
+ - on a column the spec does not declare that the environment says is not a Choice column (a text filter),
+ the value is used as written; if the environment cannot be read, the value is used as written with a
+ warning, since it cannot be told apart;
+ - a view that already exists keeps its filters (below), so an unresolvable label on it does not stop
+ the build — `verify-model-app` reports it.
+- **It stops before the build writes anything, where it can.** An apply that writes the solution or the data
+ model first checks every label the environment can already answer, so a typo is reported while nothing has
+ been written — not after the tables and columns have been. That covers a column the environment already has
+ (its options are final: the build leaves an existing column alone), a column the spec declares and the
+ environment lacks (the build creates it from the spec's options — or, bound to a declared global choice
+ that already exists, from the environment's copy of it), and the data stage of a staged build. A label that
+ depends on what the build is about to create — a status reason it inserts, a column of a table it makes —
+ cannot be known yet, so it is checked again in the views phase, once the data model exists, and no view is
+ written on a label that fails there. **A spec with a localized label** (any `displayName`, option or
+ lookup label written as a language-code map) is checked **only** in the views phase: reading option
+ labels ahead of creating a multi-language label can leave Dataverse with only its base-language
+ version, and a typo in a filter is not worth that risk. The check still comes before any view is written;
+ it comes after the tables and columns instead of before them.
+- **The checks around it.** The dry run (build without `--apply`) asks the same question and reports a view
+ the build would create whose label cannot be resolved as `? unknown`, with the reason, and counts it in its
+ summary as one that *would stop the build* rather than one it could not read. It also says, as a warning,
+ what the apply will say: the assumption made for a renamed option, once; and for a view that already exists,
+ which stays `reuse`, that its filters are left as they are and `verify-model-app` will report a label that
+ names no option.
+ `verify-model-app` expects the value the environment gives the label, so a view the build resolved live
+ verifies, and a label that resolves to nothing fails `view-filters` with the valid labels. A label whose
+ options verify could not read is reported as unresolved, with the reason, rather than as a missing filter —
+ unless the view has no condition on that column at all, which is reported as missing.
+ `lint-app-spec`
+ is offline and can only check what the spec declares: it says nothing for a label the spec's own options
+ prove, and warns that the label is *checked against the environment at build time* for a label that is not
+ among the declared options and for a column the spec does not declare.
- **Default-view enrichment (automatic):** the auto-generated **"Active &lt;Entity&gt;"** and
**"Inactive &lt;Entity&gt;"** system views ship with only the primary column. The build enriches
them with the primary column plus up to 6 meaningful declared columns (in declared order, skipping
@@ -660,7 +797,7 @@ why they need naming here at all.
"notes": true, // optional — add a Notes section
"autoSubgrids": true, // optional — a sub-grid for every child relationship
"deactivateOtherMainForms": true, // optional — see below (own custom tables only)
- "subgrids": [ { "childEntity": "new_ticket", "view": "Active Tickets", "label": "Tickets" } ] }
+ "subgrids": [ { "childEntity": "new_ticket", "view": "Active Tickets", "label": "Tickets" } ] } // + optional tab / column / after / before — see "Where a sub-grid goes"
// explicit layout: author tabs -> sections -> columns(1-4) -> fields
{ "entity": "new_project", "type": "main", "name": "Project",
@@ -717,15 +854,124 @@ why they need naming here at all.
```
- **`formType`** is `Main` (default), `QuickCreate`, or `QuickView`. A `QuickCreate` form is a
simplified create form on the same entity (no sub-grids, no Notes; events allowed). A `QuickView`
- form is read-only (no sub-grids, no events). Sub-grids/Notes are Main-form only.
+ form is read-only (no sub-grids, no events). Sub-grids/Notes are Main-form only. Every section on a
+ `QuickCreate` or `QuickView` form is one column: the platform refuses a wider one, so an authored
+ `columns` above 1 is built as 1, and the auto layout stays one column however many fields it holds.
+- **`notes`** *(optional, boolean, Main forms only)* — or **`hasNotes: true`** on the table — adds the Notes
+ section: `section_notes`, labelled "Notes", at the end of the first tab's first form-column, holding the
+ form's **Timeline** control. The timeline is written in the shape Dynamics renders: the fixed control id
+ `notescontrol` in a 23-row cell (`auto="false"`) over the 22 empty rows it spans. A timeline under a
+ generated id in a one-row cell is published but never shown, which is how earlier versions wrote it, so a
+ rebuild **repairs** such a section **in place** — the same section, position and cell — on an `auto` or an
+ explicit layout, and adds the section to an `auto` form that has none.
+ The height is yours to change: a timeline cell of N rows followed by the N−1 rows it spans is the shape
+ every platform form uses (N is 5 on one form and 20 on another; a new host is written at 23), so a Notes
+ section you resized in the maker is already in shape and a rebuild writes nothing — likewise one you
+ widened with the timeline, or one without `auto="false"`, which only some platform timelines carry. A
+ rebuild only adds rows the span is missing, to the span you chose, and never deletes the rows a resize left.
+ It never edits a timeline you added yourself and never writes a second `notescontrol`: where the form
+ already has a control with that id, no Notes section is added; an old section whose id cannot be renamed
+ for the same reason is left as it is; and so is one that still holds a control of yours after the build
+ has pruned the fields your layout dropped and moved the ones your layout declares in another section or a
+ `fieldOptions[].after` places elsewhere (move them out of it, or delete the section, in the maker, then
+ run a full build). Those fields never stand in the way: the repair is the last step, so a stray field the
+ same build removes is gone by then. Each refusal is reported in the build result (`skipped.layout`).
+ `--verify` fails the form (`form-timeline`) until it carries a timeline that renders — under
+ `notescontrol`, in a cell spanning more than one row, and for the Notes section the build owns, with the
+ rows its span needs under it — and says what to do about it: run a full build where the build repairs or
+ adds the timeline, what to change in the maker first where it will not. Verify reads the form as
+ published, before the build's own passes have run, so for the fields in an old Notes section it
+ **predicts** what the build will take out: the fields your layout declares in another section, the ones a
+ `fieldOptions[].after` places beside an anchor in an ordinary section (an anchor that sits in the Notes
+ section but is itself anchored is moved out first, and the field follows it), and — on an explicit layout
+ with `prune` on — the ones it does not list. For those it says to run a full build and names what the
+ build takes out first (a removal needs `--allow-destructive`), and it asks you to move out of the section
+ only a control no rule of your spec moves or removes — a field no rule moves (on an `auto` layout, any
+ field already on the form that no `fieldOptions[].after` places), or a control of your own. A field the
+ form carries **more than once** is not predicted when a rule would act on it, and neither is one anchored
+ — directly or down a chain of anchors — to a field the form carries more than once with a cell in the
+ Notes section or a sub-grid's: a build acts on one cell of a field, and which one depends on how it
+ arranges the sections. For the cell in the Notes section verify says it cannot tell whether the build
+ takes it out — a full build repairs the timeline unless it leaves that cell — and what to do if the
+ build's report says the timeline was left as it is: it neither promises the repair nor sends you to the
+ maker for what the build may do itself, and it says so while another control holds `notescontrol` too.
+ A repeated field that no rule moves is predicted: it stays, and is named. Nor can it see what only
+ happens while the build runs — a removal that was not authorized, a move skipped because the rows it
+ would split carry a row-span — so when the build's own report says the
+ timeline was left as it is, follow the report. Use a **full** build (without `--changed-only`) to pick up
+ an older Notes section: `--changed-only` skips a spec that has not changed, and this fix needs no change
+ to the spec. A download does not reconstruct `forms[]`, so `notes` is authored, not read back.
- **`quickViews[]`** (on a host form) embed a `QuickView` form via a lookup: `lookup` is the lookup
column on the host, `targetEntity` the related entity, `form` the **name** of a `QuickView` form
declared in `forms[]` (lint-enforced). Optional `label`, `section`, `displayAsCard`. The control
- renders from plain formxml, so it persists on a plain push.
+ renders from plain formxml, so it persists on a plain push. It is added to the host's first
+ **field** section — never a sub-grid's section or the Notes section, which hold nothing else.
- A sub-grid needs a matching `OneToMany` **or** `ManyToMany` between the form's entity and
`childEntity` (lint-enforced); the builder resolves the relationship name either way. Each sub-grid
renders in its **own 1-column, full-width section**; its title defaults to the child entity's
`pluralName` (then `displayName`), with `subgrids[].label` overriding.
+- **Where a sub-grid goes** *(Main forms only)*. With no placement keys a grid's section is added at the
+ end of the first tab's first form-column and never moved — as before. Four optional keys on a
+ `subgrids[]` entry say where it goes instead:
+
+ | Key | What it names | Effect |
+ |---|---|---|
+ | `after` | a **section** this form's layout declares | the grid's section goes **directly after** it, in that section's tab and form-column — nothing between them (not the Notes section a build appends to the end of the first tab) |
+ | `before` | the same | directly before it. Give one of `after` / `before`, not both |
+ | `tab` | a **tab** this form's layout declares | the grid goes in that tab — at the end of it when the build adds or moves the grid. With `after` / `before` it must be the tab the section is in |
+ | `column` | a form-column of the tab, counting from `0` | the grid goes in that form-column of the tab (the first tab when `tab` is not given). With `after` / `before` it must be the section's form-column |
+
+ Names are the ones the layout declares — `tabs[].name` and `sections[].name`, compared case-insensitively;
+ the name a tab or section gets when it declares none counts too. An `auto` layout has one tab,
+ `tab_general`, holding one section, `section_general`, so it can place a grid before or after that
+ section. Grids that share an anchor stay in the order they are declared. An unknown name, `after` with
+ `before`, a `column` the tab does not have, or a section in another tab or form-column than the one
+ named is an error in both `validateAppSpec` and the lint — each says what the form declares instead.
+ Placement on a form that is not a Main form is refused with the sub-grid itself. A key a sub-grid
+ entry does not read (`afterSection`, `Tab`) is ignored with a warning naming the key it probably meant.
+ A form holds **one grid per relationship**, so list each child table once: a table listed twice with a
+ placement key on either entry is an error (only one entry could say where the grid goes), and listed
+ twice with no placement it is a warning — the build adds one grid and ignores the rest, as it always has.
+
+ ```jsonc
+ // a full-width related-records grid between two sections: Summary, then Tasks, then Resolution
+ { "entity": "new_ticket", "name": "Ticket",
+ "tabs": [ { "name": "tab_main", "label": "General", "sections": [
+ { "name": "sec_summary", "label": "Summary", "columns": 2, "fields": ["new_name", "new_priority"] },
+ { "name": "sec_resolution", "label": "Resolution", "columns": 2, "fields": ["new_resolution", "new_closedon"] } ] } ],
+ "subgrids": [ { "childEntity": "new_task", "after": "sec_summary" } ] }
+
+ // a grid in its own tab, and one in the second form-column of a two-column tab
+ { "entity": "new_ticket", "name": "Ticket",
+ "tabs": [ { "name": "tab_main", "label": "General", "columns": [
+ { "width": "60%", "sections": [ { "name": "sec_left", "label": "Left", "columns": 1, "fields": ["new_name"] } ] },
+ { "width": "40%", "sections": [ { "name": "sec_right", "label": "Right", "columns": 1, "fields": ["new_priority"] } ] } ] },
+ { "name": "tab_related", "label": "Related", "sections": [ { "name": "sec_history", "label": "History", "columns": 1, "fields": ["new_notes"] } ] } ],
+ "subgrids": [ { "childEntity": "new_task", "tab": "tab_related" },
+ { "childEntity": "new_comment", "tab": "tab_main", "column": 1 } ] }
+ ```
+
+ **Width.** A grid's section is one form-column wide and fills the form-column it is in. In a tab with
+ several form-columns it is therefore as wide as its own column; to give a grid the full width of the
+ form, put it in a tab of **one** form-column (a tab with `sections[]` and no `columns[]` is one).
+ `column` has no other effect — the layout stays yours to shape.
+
+ **Rebuilding converges.** A rebuild puts the build's own grid section where the spec places it, and a
+ rebuilt form ends in the order a new one gets. A grid an earlier version appended to the end of the form —
+ behind the Notes section — moves, the same section with its control and anything you set on it, to sit
+ directly after (or before) its section; one already directly beside it
+ writes nothing. **Only the grid moves.** None of your sections, and not the Notes section, is moved to make
+ room, so a section you added between the grid and its section simply ends up behind the grid. With only
+ `tab` (and `column`) a grid already in that tab (and form-column) stays where it is within it. A grid in a
+ section you made yourself is never moved — the build reports it in `skipped.layout` (unless it is
+ already where the spec places it, which needs neither a move nor a report), as it does a name the
+ deployed form no longer has (a grid not yet on the form is then added at the end of the first tab, not
+ lost; one already there stays where it is). `--verify`
+ checks each placed grid (`form-subgrid`): it must be on the form, in the tab and form-column the spec
+ names, and directly beside the section it is placed by (or beside the grid placed there ahead of it) — what
+ sits between them is named. A grid an earlier version left elsewhere needs a **full** build to be moved —
+ `--changed-only` skips a spec that has not changed — and the failing check says so. A download does not
+ reconstruct `forms[]`, so placement is authored, not read back.
- **`deactivateOtherMainForms`** (optional, default `false`, Main forms only): after promoting this
form as the entity default, deactivate every OTHER active main form on the entity — i.e. hide the
blank stock "Information" form so only this form ships active. **Destructive**, so it is OFF by
@@ -759,7 +1005,9 @@ why they need naming here at all.
`"enabled": false` really does deploy a disabled handler. `enabled` and `passExecutionContext` must
be booleans and `parameters` a string; a string `"false"` is rejected rather than coerced, because it
is truthy in JS and would silently enable a handler you meant to disable.
- The build fetches the pushed form, injects the handlers, then publishes it.
+ The build fetches the pushed form and injects the handlers; they go live when the form is published
+ (with `--publish`, in the one publish of the tables the build changed, made before it publishes the app; without it,
+ as soon as they are wired).
### Which form a table opens with — `isDefault` and `entities[].mainFormOrder`
@@ -1147,8 +1395,7 @@ custom control), but the spec validator emits a warning.
whether an id is still live. An unplaced id needs a local creation receipt for this app/key/id
and a decoded stored name exactly equal to the spec page name; otherwise `unproven-manifest-id` halts,
never requests a replacement CREATE. The build takes this app's PUBLISHED navigation as proof: a page
- that is only in its saved but unpublished navigation halts with advice to publish the app first, so
- other apps' navigation is checked before the page is updated. If it is this app's page, add it to the
+ that is only in its saved but unpublished navigation halts with advice to publish the app first. If it is this app's page, add it to the
app's navigation in the maker, publish the app and re-run; otherwise remove the stale id from the manifest/spec (or delete the
page) and re-run. A read failure HALTs (`pages-existence-failed`).
An uncertain CLI CREATE stops and reports each new candidate's id, stored name and `createdon`.
@@ -1209,10 +1456,21 @@ custom control), but the spec validator emits a warning.
detected across two keys, or an off-sitemap id lacks a corroborated local creation receipt. Manual resolution required.
- `pages-manifest-corrupt` — the manifest web resource cannot be parsed (two keys mapping to the
same id). Fix or delete the manifest and rebuild.
- - `pages-shared-across-apps` — a page appears in another app's sitemap. Detach it in Maker first.
- `--allow-destructive` does NOT bypass this halt.
+ - `pages-shared-across-apps` — a page appears in another app's sitemap, published or only saved (not yet
+ published — an app that was never published counts). Detach it in Maker first. `--allow-destructive` does NOT bypass this halt. If another app's
+ saved navigation, or the list of apps that were never published, cannot be read, the build halts as `pages-shared-check-failed` instead of assuming it is clear.
+ The check runs again right before the first page is updated in place, so a page another app takes in while the build runs halts it there too ("became shared
+ across apps while this build ran"); one taken in while the pages upload is written by then, and is reported after the uploads as a warning naming the app.
- `pages-removed` — a page is live in the env but no longer in the spec. Re-add it to the spec, or
pass `--allow-destructive` to detach it from the nav (`SubArea` removed; page record left deployed).
+ - `pages-griffel-shorthand` — a page that this run uploads has a `makeStyles` key Griffel drops at runtime
+ (`all`, `borderColor`, `borderStyle`, `borderWidth`, `borderBlock*`, `borderInline*`), and is **new** (no deployed page) or
+ **changed** (its source no longer hashes to the `__contentSha` that `last-applied.json` recorded for it at the last apply to this
+ app in this environment — the record a successful full or changed-only apply, or a download, writes; for a page it is the hash of the source the build read and sent, and a failed or partial build records nothing). Raised from the pre-write scan, so nothing is created or updated; the message gives the page, each
+ key's line and column, the longhands, and what each way out does: deleting a key changes nothing on screen (Griffel never
+ applied it), writing the longhands makes the style start to render. A page that already exists and is sent again as recorded —
+ or has no record in this workspace — is sent as it is and the build **warns** with the same detail instead: it ships nothing
+ new. A call the check cannot read is reported as that (with what to change in the code), not as CSS Griffel drops.
- **Offline evaluation.** The app-builder eval harness (`evals/model-apps/app-builder/`) grades
page-stage structural facts from the spec offline (navigation graph resolution, intent-vs-tsx
completeness). See [`evals/model-apps/app-builder/EVAL_GUIDE.md`](../../../evals/model-apps/app-builder/EVAL_GUIDE.md).
diff --git a/plugins/model-apps/references/authoring-flow.md b/plugins/model-apps/references/authoring-flow.md
index 04cb74bb6..2637cad56 100644
--- a/plugins/model-apps/references/authoring-flow.md
+++ b/plugins/model-apps/references/authoring-flow.md
@@ -439,6 +439,13 @@ is optional — omit it to title the grid with the child entity's `pluralName` (
supply it to override. To ship only your form and hide the blank stock "Information" form, set
`"deactivateOtherMainForms": true` on the form (opt-in; only affects tables this build owns).
+By default a grid's section goes at the **end** of the form. To put it elsewhere — a full-width
+related-records grid between two sections, say — declare the form's layout (`tabs[].name` /
+`sections[].name`) and name where the grid goes: `"after": "<section>"` or `"before": "<section>"`, or
+`"tab": "<tab>"` (with `"column": <n>` for a form-column of that tab). A grid is as wide as the
+form-column it is in, so for a full-width grid use a tab of one form-column. The wireframe draws a
+placed grid where it will land; see app-spec-schema.md (*Where a sub-grid goes*).
+
**Choosing auto vs an explicit layout.** `auto` is the right default and already adapts: it puts
the primary field first and switches to **two columns above six fields** (Quick Create stays one
column, which Dataverse requires). What it cannot do is *group by task*.
@@ -509,6 +516,19 @@ table are supported, including current-user (`ownerid` / `eq-userid`) and relati
dates; a filter **through a related table** is not expressible and must not be
faked — say so and propose a supported alternative.
+A filter on a Choice column may name the option by its label, in any language it has. The build
+resolves the label against the options the environment holds for that column, and stops — before it
+writes anything where the environment already shows the label is wrong, and in any case before any
+view is written — when a label matches no option (the error lists the valid ones), so spell it exactly
+as the column does, or use the option's integer value. (Where your spec numbers the options — inline
+`options[]`, or a global choice you declare — an option a maker renamed in the environment still resolves
+to the number your spec gave it, with a warning, unless the environment shows the options are numbered
+otherwise, as when you added options after the column was built; then it stops.) A spec with a localized
+label is checked only
+in the views phase, after the tables and columns are written, because reading option labels ahead of
+creating a multi-language label can cost it every language but the base one. This covers a column of a
+table you reuse (`account.industrycode`) without declaring it.
+
Two edit-time limits worth stating up front, because both bite silently:
an authored view whose name collides with the table's stock default view MERGES
onto that default (its filters and sort are ignored), and an **existing** view's
diff --git a/plugins/model-apps/references/localization.md b/plugins/model-apps/references/localization.md
index 208c681ca..c30d4c0df 100644
--- a/plugins/model-apps/references/localization.md
+++ b/plugins/model-apps/references/localization.md
@@ -8,7 +8,8 @@
> (see `app-spec-schema.md` → `languageCode` and *Localized labels*).
Read this only when the planner has detected multiple configured languages OR any
-non-English language via `pac model list-languages`. English-only environments
+non-English language via `scripts/list-languages.js` (or `pac model list-languages --environment '<envUrl>'`, which the planner
+runs when that script cannot read them). English-only environments
should skip this entire file — the page-builder will write the page without any
localization scaffolding.
@@ -19,7 +20,7 @@ section, not unconditionally.
### When to Apply
-Only apply localization when `pac model list-languages` (run by the planner during requirements gathering) returns **multiple languages** or **any non-English language**. English-only environments skip this entire section.
+Only apply localization when `scripts/list-languages.js` (run by the planner during requirements gathering; its fallback is `pac model list-languages --environment '<envUrl>'`) reports **multiple languages** or **any non-English language**. English-only environments skip this entire section.
### Language Detection
@@ -30,11 +31,13 @@ const language = React.useMemo(() => {
const uiLanguageId = (typeof Xrm !== "undefined" &&
Xrm.Utility?.getGlobalContext()?.userSettings?.languageId) || 1033;
const langMap: Record<number, { code: string; name: string; isRtl: boolean }> = {
- // One entry per language `pac model list-languages` reports, copied from its columns:
- // LCID Language Code RTL
- // 1033 English (United States) en-US No
- // becomes 1033: { code: "en-US", name: "English (United States)", isRtl: false }.
- // `isRtl` comes from the RTL column (see RTL Layout Support) — never from memory.
+ // One entry per language in the plan's `## Environment` → `Languages` line, e.g.
+ // English (1033, en-US); Arabic (Saudi Arabia) (1025, ar-SA) — RTL
+ // becomes 1033: { code: "en-US", name: "English", isRtl: false } and
+ // 1025: { code: "ar-SA", name: "Arabic (Saudi Arabia)", isRtl: true }.
+ // `isRtl` is true exactly where the line carries `— RTL` (see RTL Layout Support) — never from memory.
+ // A language the plan lists with no code has nothing to key a translation by: it gets no entry, and the
+ // fallback below serves that user in English.
};
return langMap[uiLanguageId] || { code: "en-US", name: "English", isRtl: false };
}, []);
@@ -70,13 +73,15 @@ Usage: `<Text>{translate("title")}</Text>` — never `<Text>Dashboard</Text>`.
### RTL Layout Support
-Take each language's direction from the **RTL** column of `pac model list-languages` (carried into the
-plan's `## Environment` → `Languages` line as a `— RTL` mark) — never from a hand-written list of LCIDs. The platform derives that column
-from culture data, and a list always misses some: Windows culture data marks more than 40 right-to-left
-cultures — every Arabic region, Persian and Dari, Urdu, Pashto, Sindhi, Uyghur, Divehi, Syriac, Central
+Take each language's direction from the `rtl` field of `scripts/list-languages.js` (carried into the
+plan's `## Environment` → `Languages` line as a `— RTL` mark; when the planner fell back to `pac model list-languages --environment '<envUrl>'`,
+from that table's RTL column) — never from a hand-written list of LCIDs. The script reads
+it from a table of Windows culture data, and a list always misses some: Windows culture data marks more than 40
+right-to-left cultures — every Arabic region, Persian and Dari, Urdu, Pashto, Sindhi, Uyghur, Divehi, Syriac, Central
Kurdish, Hebrew and Yiddish among them — and a language a list forgot renders left-to-right.
-If a PAC build prints no RTL column, compute the flag from the language's **Code** instead. Direction is a
+If the plan marks no direction for a language (a plan written before the script reported one), compute the flag from
+the language's **Code** instead. Direction is a
property of the script a language is written in, and `Intl.Locale#maximize()` fills in the likely script
from CLDR (`fa` → `fa-Arab-IR`, `ur-PK` → `ur-Arab-PK`, `dv-MV` → `dv-Thaa-MV`):
diff --git a/plugins/model-apps/references/plan-schema.md b/plugins/model-apps/references/plan-schema.md
index 94a163922..28d798e6a 100644
--- a/plugins/model-apps/references/plan-schema.md
+++ b/plugins/model-apps/references/plan-schema.md
@@ -38,9 +38,11 @@ same relative position so downstream parsers can find them predictably:
- App: [app name] ([app-id]) OR "create new: [name]"
- Mode: app-builder ← **only** when the plan was projected from an App Spec by
`scripts/write-page-plan.js`; omitted for a planner-authored (standalone `/genpage`) plan
-- Languages: [each detected language with its LCID and code, marked `— RTL` when the RTL column of
- `pac model list-languages` says Yes — e.g. "English (1033, en-US); Arabic (Saudi Arabia) (1025,
- ar-SA) — RTL" — or "English (1033) only". The page builder takes text direction from that mark.]
+- Languages: [each detected language with its LCID and code, marked `— RTL` when `scripts/list-languages.js`
+ reports `rtl: true` for it — or, when the planner fell back to `pac model list-languages --environment '<envUrl>'`, when that table's RTL
+ column says Yes — e.g. "English (1033, en-US); Arabic (Saudi Arabia) (1025,
+ ar-SA) — RTL" — or "English (1033) only". A language the script could not name keeps its number and is written
+ "<LCID> (no culture code)" with no mark. The page builder takes text direction from that mark.]
- Solution: [solution unique name — ALWAYS present, default fallback is "Default"]
- Publisher Prefix: [prefix tied to the solution's publisher — ALWAYS present, default fallback is "new"]
diff --git a/plugins/model-apps/references/rules.md b/plugins/model-apps/references/rules.md
index 02f7f6d55..1285e09c6 100644
--- a/plugins/model-apps/references/rules.md
+++ b/plugins/model-apps/references/rules.md
@@ -185,7 +185,7 @@ const useStyles = makeStyles({
## Localization
Localization guidance has been moved to a separate reference that is loaded
-**conditionally** — only when `pac model list-languages` returns multiple
+**conditionally** — only when `scripts/list-languages.js` (or its fallback, `pac model list-languages --environment '<envUrl>'`) reports multiple
configured languages OR any non-English language. For English-only environments,
skip this entirely.
@@ -385,7 +385,8 @@ object has to be **written inline in the call**: an object built in a variable a
its token halts the build as stray. **Write the plain form, `navigateTo({ … })` or
`Xrm.Navigation.navigateTo({ … })`.** A parenthesised callee, `(navigateTo)({ … })`, is read only where a call can
start — at the start of a statement or after `;` `{` `(` `[` `,` `:`, a ternary `?`, an operator ending in `=`, `=>`,
-`&&`, `||` or `??` — and never after a name or keyword, `)`, `]`, `.`, `}`, `!`, `>`, a quote or a back-tick, because
+`&&`, `||` or `??`, or the keyword `return` on the same line (`return (navigateTo)({ … })`; not `await` or `yield`) — and never
+after a name or any other keyword, `)`, `]`, `.`, `}`, `!`, `>`, a quote or a back-tick, because
there the parentheses are an argument list for some other function (`factory!(navigateTo)({ … })`,
``tag`x`(navigateTo)({ … })``); the token in one halts the build as stray. Always emit it exactly there — never single-quoted, back-ticked,
concatenated, followed by an expression (`"PAGEREF_x".slice(8)`, `&& other`,
@@ -455,10 +456,10 @@ import { webDarkTheme, webLightTheme } from "@fluentui/react-components";
Recurring CSS bugs that type-check and compile but render wrong. Check for these before finishing a page:
1. **A bar/progress fill `<span>` with a `width`/`height` % but no `display` is invisible.** A `<span>` defaults to `display: inline`, which ignores width/height → a 0×0 box, so the colored fill never paints (only the track shows — looks like "the color got lost"). Symptom: computed `backgroundColor` is correct but `offsetWidth`/`offsetHeight` is `0`. Fix: add `display: "block"` (or `inline-block`) to the fill — or use a `<div>` for fills.
-2. **Concatenated `makeStyles` classes lose status/warning colors to a shorthand-vs-longhand collision.** ``className={`${base} ${warning}`}`` (plain template string, not `mergeClasses`) where `base` sets a shorthand `border:` / `backgroundColor: "transparent"` and `warning` sets the longhand `borderColor` / `backgroundColor` — Griffel's atomic output plus the shorthand-vs-longhand cascade lets the base win, so the amber bg/border/text silently fall back to neutral. Fix: apply the status colors **inline** (`style={{ backgroundColor: tokens.colorStatusWarningBackground1, borderColor: tokens.colorStatusWarningBorder1 }}` — inline wins) or use `mergeClasses` instead of string concatenation.
+2. **Concatenated `makeStyles` classes lose status/warning colors to a shorthand-vs-longhand collision.** ``className={`${base} ${warning}`}`` (plain template string, not `mergeClasses`) where `base` sets a shorthand `border:` / `backgroundColor: "transparent"` and `warning` sets the longhand `borderTopColor` / `backgroundColor` — Griffel's atomic output plus the shorthand-vs-longhand cascade lets the base win, so the amber bg/border/text silently fall back to neutral. Fix: apply the status colors **inline** (`style={{ backgroundColor: tokens.colorStatusWarningBackground1, borderColor: tokens.colorStatusWarningBorder1 }}` — inline wins) or use `mergeClasses` instead of string concatenation.
3. **`tokens.fontFamilyNumeric` is Bahnschrift, not Segoe UI.** Using it for tabular numbers (counts, %, ranks, dates) renders those digits in Bahnschrift — visibly mismatched against Segoe UI everywhere else. Fix: use `tokens.fontFamilyBase` and keep `fontVariantNumeric: "tabular-nums"` for aligned digits.
4. **Gradient hero with white text: `colorPalette*Background2/3` tokens are light tints, not dark.** A gradient built from e.g. `colorPalettePurpleBackground3` / `colorPaletteTealBackground2` with `color: colorNeutralForegroundOnBrand` (white) renders white-on-light → unreadable; those `Background2/3` palette tokens are pale. Fix: build the gradient from the dark, saturated `colorPalette*Foreground2` stops (e.g. `colorPalettePurpleForeground2`, `colorPaletteTealForeground2`), which are dark enough for white text to pass AA.
-5. **`borderWidth` is an unsupported Griffel shorthand.** It passes TypeScript and `pac model genpage transpile`, then logs `@griffel/react: unsupported shorthand CSS property "borderWidth"` at runtime. Use all four explicit longhands (`borderTopWidth`, `borderRightWidth`, `borderBottomWidth`, `borderLeftWidth`) instead. Grep the finished page with `['"]?borderWidth['"]?\s*:` before deployment so quoted and whitespace-separated property syntax is caught too.
+5. **Ten CSS shorthands are unsupported by Griffel — `borderWidth` is the usual one.** Griffel does not support ten CSS shorthands, and `makeStyles` drops them at runtime: the page type-checks, transpiles and deploys, then renders without the border, color or reset. They are `all`, `borderColor`, `borderStyle`, `borderWidth`, `borderBlock`, `borderBlockStart`, `borderBlockEnd`, `borderInline`, `borderInlineStart` and `borderInlineEnd`. Write longhands instead: `borderColor`, `borderStyle` and `borderWidth` become one longhand per side, `border` + `Top`, `Right`, `Bottom` or `Left` + `Color`, `Style` or `Width` (`borderWidth` → `borderTopWidth`, `borderRightWidth`, `borderBottomWidth`, `borderLeftWidth`); `borderBlock`, `borderInline` and their `Start` and `End` forms become the `Width`, `Style` and `Color` longhands of the sides they name (`borderBlockStart` → `borderBlockStartWidth`, `borderBlockStartStyle`, `borderBlockStartColor`; `borderBlock` → those and the three `borderBlockEnd…` ones); `all` has no longhands, so set the properties you need one by one. Every other shorthand (`padding`, `margin`, `border`, `borderRadius`, `gap`, `outline`) is supported, and an inline `style={{ … }}` is not Griffel at all. The browser console logs `@griffel/react: You are using unsupported shorthand CSS property "<name>"` for each one that reaches it. Run `node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file '<page.tsx>'` on the finished page. `check-griffel-styles.js` prints each problem it finds — a key Griffel drops in a `makeStyles` call, at any depth, with its line, column and longhands, or a call or a style object it cannot read, with what to change — and exits 3 while any is left: fix what it reports and run it again, and do not transpile or upload the page until it exits 0. It reads the style objects written inline in the call, `makeStyles({ … })`, so write them there: one passed or spread in from elsewhere (`makeStyles(styles)`, `...base`) is reported, because the check cannot see its keys, and so is a key computed from an expression (`[key]: …`), whose name it cannot see (a template that starts with `--`, `&`, `:` or `@` is read); Fluent's `...shorthands.*(…)` and `...typographyStyles.*` may be spread as they are.
### Data Fetching: the host double-mount, de-dupe, and caching
diff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.js
index fead6b8f1..ca0650d26 100644
--- a/plugins/model-apps/scripts/build-model-app.js
+++ b/plugins/model-apps/scripts/build-model-app.js
@@ -16,12 +16,13 @@ const path = require('node:path');
const { randomUUID } = require('node:crypto');
const { sha256 } = require('./lib/hash.js');
const { validateAppSpec, migrateAppSpec, normalizePageSource, normalizeLanguageCode, specDeclaresAttribute } = require('./lib/app-spec.js');
-const { runSdkBuild, planFor, appUniqueName, compileFormIntent, resolveExistingFormId, normalizeFormId, settleOwedPublishes } = require('./lib/sdk-build.js');
+const { runSdkBuild, planFor, appUniqueName, compileFormIntent, resolveExistingFormId, normalizeFormId, settleOwedPublishes, collectOwedPublishes } = require('./lib/sdk-build.js');
const { stagePhasesOrResolve, PHASES, STAGES } = require('./lib/stages.js');
// #455: resolves the authoring LCID over the transport hatch, BEFORE constructing the SDK that
// bakes it into the App/Form/Dashboard adapters.
const { resolveAuthoringLanguage } = require('./lib/entity-provision.js');
const { createAzHttpClient, SQL_DEADLOCK_VICTIM } = require('./lib/sdk-http-client.js');
+const { workspaceBindingError, workspaceBindingNote } = require('./lib/workspace-binding.js');
const { parseArgs, validateFlags, readAliasedFlag, readJsonArg, emitResult, dataverseRequest, readProvisionedLanguages, preflightAuth, dataverseOrigin } = require('./lib/dataverse-auth.js');
const { openJournal } = require('./lib/build-journal.js');
const { assertSafeOutputDir, assertPlainFileTarget, writeFileSafe } = require('./lib/safe-fs.js');
@@ -43,26 +44,46 @@ const { verifySpec } = require('./lib/verify-spec.js');
const { readerFor, isolatedReaderFor } = require('./verify-model-app.js');
const { makeGenpageCli } = require('./lib/genpage-cli.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
+// only ever reads from it, so a folder that is not there — or cannot be inspected — is just one with no workspace; a
+// link or a file in its place is refused either way, as everywhere the plugin takes a workspace.
+function assertWorkspaceDir(workspaceDir, { create }) {
+ try {
+ assertSafeOutputDir(workspaceDir, { create });
+ } catch (err) {
+ if (create || !(err && err.reason === 'uninspectable')) throw err;
+ }
+}
+
// Construct the SDK against the vendored bundle + an az-token HttpClient. Two clients:
// sdk — carries solutionUniqueName (metadata + record writes auto-join the
// solution via the MSCRM.SolutionUniqueName header); does no workspace I/O.
-// provisionSdk — header-less; owns the PERSISTENT workspace. Every discovery read
-// (findTables/findColumns/fetchEntityMetadata) and every artifact
-// (views/charts/forms/app) lands here, so the app folder accumulates the
-// metadata for reuse/edits. Construction is offline (no token until first call).
-async function makeSdk(env, spec, workspaceDir, languageCode) {
+// provisionSdk — header-less; owns a workspace. In an APPLY (`persistent`) that is the app
+// folder's PERSISTENT one: every discovery read (findTables/findColumns/
+// fetchEntityMetadata) and every artifact (views/charts/forms/app) lands there, so
+// the app folder accumulates the metadata for reuse/edits — and opening it binds it
+// to the environment of this run (lib/workspace-binding.js). In a DRY RUN it is a
+// throwaway inside the SDK's own temp dir: a preview builds nothing, so it must not
+// bind a folder to an environment it only previewed (the next --apply, against the
+// environment the operator meant, would be refused), and every read its live plan
+// makes goes to the server anyway. The persistent folder is only ASKED, read-only,
+// 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 } = {}) {
// 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. An explicit real directory
- // is created if missing and then re-checked — mkdir on an existing junction succeeds, so
- // the re-check is what refuses it.
- assertSafeOutputDir(workspaceDir, { create: true });
+ // directory has been refused the factory must not run at all.
+ assertWorkspaceDir(workspaceDir, { create: persistent });
const { createMakerSdk, createNodeWorkspaceStorage } = require('./vendor/cds-maker-sdk.cjs');
const httpClient = createAzHttpClient(env);
const sdkTempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'model-app-'));
const cleanup = () => {
fs.rmSync(sdkTempDir, { recursive: true, force: true });
};
+ // Inside the temp dir that `cleanup` removes, so a preview has nothing more to strand.
+ const provisionDir = persistent ? workspaceDir : path.join(sdkTempDir, 'preview-workspace');
// Everything fallible after the directory exists runs INSIDE this guard, because the caller's
// `finally { cleanup() }` only becomes reachable once this function RETURNS — so anything that
// throws before the return strands the throwaway workspace for the life of the machine.
@@ -77,6 +98,7 @@ async function makeSdk(env, spec, workspaceDir, languageCode) {
// throwaway, so a failed run must leave it exactly as it found it.
let sdk;
let provisionSdk;
+ let folderNote = null;
try {
sdk = createMakerSdk({
workspaceStorage: createNodeWorkspaceStorage(sdkTempDir), // unused (no workspace ops)
@@ -89,30 +111,57 @@ async function makeSdk(env, spec, workspaceDir, languageCode) {
...(languageCode ? { languageCode } : {}),
});
provisionSdk = createMakerSdk({
- workspaceStorage: createNodeWorkspaceStorage(workspaceDir),
+ workspaceStorage: createNodeWorkspaceStorage(provisionDir),
instanceUrl: env,
httpClient,
// Must match the `sdk` instance above: `pushArtifact` refuses a push whose stored artifact
// language disagrees with the SDK performing it (for language-sensitive registrations), so two
// instances at different LCIDs would make every push of a fetched artifact fail.
...(languageCode ? { languageCode } : {}),
+ // A form create whose answer was lost converges instead of halting. The HTTP client re-sends a POST that
+ // got no answer; when the first attempt had committed, the SDK sees the re-send's 412 for the id it minted
+ // and, without this, reports ARTIFACT_ALREADY_EXISTS — a halt a re-run repeats until the workspace is
+ // reset by hand (requireSuccessfulPush). With it the SDK reads that row and adopts it ONLY when it is
+ // exactly what was sent, writing nothing (a Main form only; anything else is refused with the reason,
+ // and the halt is as before). It is on THIS instance because it pushes every form. This instance is
+ // header-less, so no solution membership is demanded of the row — a form joins its solution after its
+ // push. An adoption reports `saved: false`; pushFailed knows that is not a failure.
+ createRecovery: 'adoptExact',
});
- await provisionSdk.initWorkspace();
+ if (!persistent) fs.mkdirSync(provisionDir);
+ try {
+ await provisionSdk.initWorkspace();
+ } catch (err) {
+ // `initWorkspace` is where the SDK refuses a workspace that belongs to another environment, before it
+ // reads or writes anything, and where it reads a manifest the JSON parser may reject. That is an
+ // operator's problem to solve, not a crash: say which environments are involved and what the safe ways
+ // forward are (lib/workspace-binding.js). Only an apply can meet it: a preview's workspace is brand new.
+ throw workspaceBindingError(err, { env, workspaceDir }) || err;
+ }
+ if (!persistent) {
+ // The preview did not open the app folder's workspace, so it cannot be refused by it — but an --apply
+ // would be, and the operator is better told now than after the plan has been read and approved.
+ try {
+ const probe = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(workspaceDir), instanceUrl: env, httpClient });
+ folderNote = await workspaceBindingNote(probe, { env, workspaceDir });
+ } catch { /* advisory only: nothing here may stop a preview */ }
+ }
} catch (err) {
cleanup();
throw err;
}
- // Only the two SDK instances, the cleanup and verify's isolated dashboard reader are returned. The raw
- // `httpClient` used to come back with them so the caller could wire verify's role-privilege reader — that
- // read had no SDK surface and had to compose an absolute `EntityDefinitions(...)?$select=Privileges` request
- // itself. The vendored bundle now exposes `getEntityPrivileges`, so the reader takes the SDK and the raw
- // client has no caller. Returning it anyway would advertise a bypass this file no longer takes.
+ // Only the two SDK instances, the cleanup and verify's isolated dashboard reader are returned (and, for a
+ // preview, the note it owes about the app folder). The raw `httpClient` used to come back with them so the
+ // caller could wire verify's role-privilege reader — that read had no SDK surface and had to compose an
+ // absolute `EntityDefinitions(...)?$select=Privileges` request itself. The vendored bundle now exposes
+ // `getEntityPrivileges`, so the reader takes the SDK and the raw client has no caller. Returning it anyway
+ // would advertise a bypass this file no longer takes.
//
// The isolated reader is built HERE so it shares this client, and with it the Azure CLI token: made by the
// caller, it created a client of its own, and a second `az account get-access-token`, for every build's
// dashboard verify. Each read still gets its own throwaway workspace and SDK (verify-model-app.js).
const isolatedReader = isolatedReaderFor(env, { httpClient });
- return { sdk, provisionSdk, cleanup, isolatedReader };
+ return { sdk, provisionSdk, cleanup, isolatedReader, folderNote };
}
// Turn engine progress events into a phase-grouped, status-marked build log:
@@ -575,9 +624,10 @@ async function buildModelApp(spec, opts, deps) {
// Injectable apply seam: production defaults to runSdkBuild; tests inject a stub to drive verify
// without a live SDK.
const runBuild = deps.runBuild || runSdkBuild;
- // What failed attempts still owe for the default views they enriched (sdk-build.js, 4b), by artifact.
- // Every attempt re-runs every phase, but a later one can halt before the enrichment an earlier one did,
- // so each debt is kept until a publish phase pays it (`owedPaid`), and the final halt settles the rest.
+ // What failed attempts still owe for the views and forms they saved and deferred (sdk-build.js: the default-view
+ // enrichment 4b, the reconcile of existing views and forms), by target. Every attempt re-runs every phase, but a
+ // later one can halt before the step an earlier one owed from, so each debt is kept until a publish phase pays it
+ // (`owedPaid`), and the final halt settles the rest.
const owedAcrossAttempts = new Map();
let r;
for (let attempt = 1; ; attempt++) {
@@ -616,7 +666,7 @@ async function buildModelApp(spec, opts, deps) {
break;
} catch (err) {
if (err && err.owedPaid) owedAcrossAttempts.clear();
- for (const target of (err && Array.isArray(err.owedPublishes) ? err.owedPublishes : [])) owedAcrossAttempts.set(`${target[0]}:${target[1]}`, target);
+ collectOwedPublishes(owedAcrossAttempts, err && err.owedPublishes);
if (attempt <= maxRetries && isTransientHalt(err, { spec })) {
const delay = opts.retryDelayMs != null ? opts.retryDelayMs : backoffMs(attempt);
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) });
@@ -628,7 +678,7 @@ async function buildModelApp(spec, opts, deps) {
// Resume by re-running the same command (idempotent): a partial range (--from and the like) is
// refused on --apply.
//
- // First publish the default views this build's attempts had enriched and no publish phase paid: no
+ // First publish the views and forms this build's attempts had saved and no publish phase paid: no
// retry follows now (see settleOwedPublishes, sdk-build.js). Best-effort, so the halt below is still
// what this run reports.
await settleOwedPublishes(deps.provisionSdk || deps.sdk, [...owedAcrossAttempts.values()], deps.warn);
@@ -638,12 +688,17 @@ async function buildModelApp(spec, opts, deps) {
}
// #559: a dry run's whole purpose is to say what an apply would DO, so summarise the decision
// rather than only listing the spec back. `unknown` is counted separately and never folded into
- // either real decision — an unresolved probe is missing information, not a verdict.
+ // either real decision — an unresolved probe is missing information, not a verdict. Within it, an item
+ // the environment ANSWERED and the answer is "this would stop the build" (`wouldHalt`: a view filter
+ // label that names no option) is a verdict too, so it is not counted as unreadable.
if (r && r.dryRun && Array.isArray(r.planItems)) {
const n = (s) => r.planItems.filter((p) => p.state === s).length;
const unprobed = r.planItems.filter((p) => !p.state).length;
+ const wouldHalt = r.planItems.filter((p) => p.state === 'unknown' && p.wouldHalt).length;
+ const unreadable = n('unknown') - wouldHalt;
const parts = [`${n('create')} to create`, `${n('reuse')} already present`];
- if (n('unknown')) parts.push(`${n('unknown')} could not be read`);
+ if (unreadable) parts.push(`${unreadable} could not be read`);
+ if (wouldHalt) parts.push(`${wouldHalt} would stop the build`);
if (unprobed) parts.push(`${unprobed} not probed`);
log(r.livePlan
? `\n▢ dry run — ${parts.join(', ')} (${r.planItems.length} steps). Re-run with --apply to execute.`
@@ -875,14 +930,19 @@ function assertSnapshotInvalidated(store, workspaceDir) {
// detect a .tsx / contentPath byte edit, not just a spec-JSON change. It records the content that was
// actually deployed by THIS apply, stamped with the environment and app it was deployed to, and the
// dashboard/page ids this apply resolved there (AB#6726727: the sitemap baseline lines entries up by
-// them, and a spec downloaded elsewhere carries another environment's). `write` is a test seam.
+// them, and a spec downloaded elsewhere carries another environment's). A page's hash is the one of the
+// source the pages phase read and sent (`created.pageSourceShas`), not of the file as it is when the build
+// ends: a page saved while the build ran must read as changed next time, and the build's Griffel check
+// judges a page against this record (deployed-baseline.js annotateForBaseline). `write` is a test seam.
function persistAppliedBaseline(r, { spec, opts, workspaceDir, appDirAbs, baselineIdentity }, write = writeBaseline) {
const fullPhaseApply = (opts.phases || PHASES).length === PHASES.length;
const changedOnlyApplied = !!(r && r.changedOnly && (r.changedOnly.decision === 'fast' || r.changedOnly.decision === 'full'));
const effectiveSuccess = !!(r && r.ok && (!r.verify || r.verify.ok));
if (!(effectiveSuccess && opts.apply && !r.dryRun && (fullPhaseApply || changedOnlyApplied))) return false;
try {
- write(workspaceDir, spec, { appDir: appDirAbs, ...baselineIdentity, created: r.created, previous: opts.baselineSpec });
+ // A changed-only run that found nothing to apply (`noop`, with no `created`) sent nothing, so it has no source to record: every page keeps the record it had.
+ const created = r.created || (r.noop === true ? { pageSourceShas: {} } : r.created);
+ write(workspaceDir, spec, { appDir: appDirAbs, ...baselineIdentity, created, previous: opts.baselineSpec });
return true;
} catch {
return false;
@@ -936,8 +996,9 @@ async function main() {
const workspaceDir = flags.workspace || path.join(path.dirname(specPath), '.maker-workspace');
// Before auth, language resolution, and SDK construction. A link planted as the workspace
// root is refused here so the factory below is never called; a real directory is allowed.
+ // Only an --apply creates it: a dry run never opens this workspace (see makeSdk).
try {
- assertSafeOutputDir(workspaceDir, { create: true });
+ assertWorkspaceDir(workspaceDir, { create: flags.apply === true });
} catch (err) {
emitResult(false, err instanceof Error ? err : new Error(String(err)));
return;
@@ -1031,7 +1092,10 @@ async function main() {
opts.preResolvedLanguageCode = authoringLanguageCode;
// Construct for both dry-run and apply: proves the vendored bundle + adapter wire up
// (offline), and apply needs it. A spec validation error short-circuits before any write.
- const { sdk, provisionSdk, cleanup, isolatedReader } = await makeSdk(env, spec, workspaceDir, authoringLanguageCode);
+ // 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 });
+ 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).
// Opened here, after the SDK exists, so a refusal still runs cleanup. The preflight above
diff --git a/plugins/model-apps/scripts/check-auth.js b/plugins/model-apps/scripts/check-auth.js
index 260c85300..562fb9eb1 100644
--- a/plugins/model-apps/scripts/check-auth.js
+++ b/plugins/model-apps/scripts/check-auth.js
@@ -118,6 +118,33 @@ function normalizeUser(u) {
return (u || '').trim().toLowerCase();
}
+// With an explicit environment the Dataverse token needs nothing from the other probes, so it is read
+// beside `az account show` instead of after it, and WhoAmI is sent the moment the token is in hand — while
+// `pac org who` (the slowest cold start) is still running. Only the START times move: every verdict is still
+// reached in the same order by main() (account, token timeout, pac, WhoAmI), and WhoAmI's answer is read
+// only when that order gets to it.
+//
+// The WhoAmI outcome is captured as data — `{ res }` or `{ error }` — because it can settle long before
+// main() looks at it, and a rejection nobody awaited yet would otherwise be reported as unhandled. It is
+// started only when the token read SUCCEEDED: with no token in the process memo, dataverseRequest would
+// run a synchronous `az` read of its own, freezing the event loop (and pac's timeout timer) mid-probe;
+// that case keeps today's order, after pac.
+//
+// The same rule is why the early request is sent with `refreshOn401: false`. On a 401 dataverseRequest would
+// replace the token with a synchronous `az` read — up to twice, seconds each on a cold Windows start — while
+// `az account show` and `pac` are still running. A wrong-tenant 401 is exactly what this preflight exists to
+// diagnose, so that freeze is the case that matters. The 401 is handed back instead, and main() sends WhoAmI
+// again at its old place (after pac), where the refresh blocks nothing.
+function warmDataverseToken(envUrl, signal) {
+ const token = Promise.resolve()
+ .then(() => getAuthTokenAsync(envUrl, { signal }))
+ .catch(() => null);
+ const whoAmI = token.then((value) => (value
+ ? dataverseRequest(envUrl, 'GET', 'WhoAmI', null, { timeout: 30000, refreshOn401: false }).then((res) => ({ res }), (error) => ({ error }))
+ : null));
+ return { token, whoAmI };
+}
+
async function main() {
const argv = process.argv.slice(2);
// This tool always exits 0 so callers can parse stdout, so a usage error is reported as a
@@ -140,20 +167,32 @@ async function main() {
// Every probe below is a cold CLI start. Measured on Windows: `pac org who` ~7 s, and each `az`
// call ~3-5 s. Run one after another (az --version, az account show, pac, then az again for the
// WhoAmI token), the preflight cost ~19 s at the start of every /genpage and /app-builder run.
- // pac needs nothing from az, so it is started FIRST and runs while the az probes run.
+ // pac needs nothing from az, so it is started FIRST and runs while the az probes run; with an explicit
+ // environment the token read and WhoAmI are independent of the account probe too (warmDataverseToken).
const pacOrgProbe = runQuietAsync('pac', ['org', 'who'], PAC_PROBE_TIMEOUT_MS);
const azBudget = azTimeoutMs();
+ // Every probe an early verdict could leave running. A non-detached child outlives the process that
+ // started it, so each early return cancels all of them — pac, and the token read started beside the
+ // account probe — before it emits.
+ const tokenAbort = new AbortController();
+ const cancelProbes = () => {
+ pacOrgProbe.cancel();
+ tokenAbort.abort();
+ };
// A slow Azure CLI is reported as slow — neither "not installed" nor "not logged in" is true of it,
// and sending the user to reinstall or `az login` fixes nothing.
const azTimedOut = (command, partial = {}) => {
- pacOrgProbe.cancel();
+ cancelProbes();
return emit(buildResult(Object.assign({ blocker: 'az_timeout', message: azTimeoutAdvice(command, azBudget) }, partial)));
};
// 1) az login. `az account show` answers "installed?" and "logged in?" together on the happy path,
// so `az --version` runs only to tell those two failures apart — and not at all when the runner
// already found no `az` on PATH.
- const account = await runQuietAsync('az', ['account', 'show', '--query', 'user.name', '-o', 'tsv'], azBudget).promise;
+ const accountProbe = runQuietAsync('az', ['account', 'show', '--query', 'user.name', '-o', 'tsv'], azBudget);
+ // Started with the account probe, awaited after it: the verdict order below is unchanged.
+ const warm = envUrl ? warmDataverseToken(envUrl, tokenAbort.signal) : null;
+ const account = await accountProbe.promise;
const azUser = account.out;
if (!azUser) {
if (account.failure === 'timeout') return azTimedOut('az account show');
@@ -162,7 +201,7 @@ async function main() {
if (version.out == null) {
// This branch returns before the pac probe is awaited. Kill the child explicitly so a
// non-detached PAC process cannot outlive the preflight after its parent exits.
- pacOrgProbe.cancel();
+ cancelProbes();
return emit(
buildResult({
blocker: 'az_missing',
@@ -172,7 +211,7 @@ async function main() {
}
// Same early-return hazard as az_missing: once we know az is installed but logged out, the
// pending PAC result cannot affect this verdict, so cancel it before emitting.
- pacOrgProbe.cancel();
+ cancelProbes();
return emit(
buildResult({
blocker: 'az_not_logged_in',
@@ -181,13 +220,12 @@ async function main() {
);
}
- // Acquire the WhoAmI token while pac is still running. getAuthToken memoizes per process, so the
+ // The WhoAmI token, read while pac is still running. getAuthToken memoizes per process, so the
// dataverseRequest below reuses it instead of paying another az cold start after pac returns. A
// failure here is not reported: WhoAmI acquires again and reports it with the right blocker — except
// a TIMEOUT, which WhoAmI's own attempt would only repeat, doubling the wait before saying so.
- if (envUrl) {
- let warmed = null;
- try { warmed = await getAuthTokenAsync(envUrl); } catch { /* reported by WhoAmI */ }
+ if (warm) {
+ const warmed = await warm.token;
if (!warmed && tokenFailureKind(envUrl) === 'timeout') {
return azTimedOut('az account get-access-token', { azUser, envUrl, warnings, message: tokenFailureMessage(envUrl, '') });
}
@@ -242,10 +280,15 @@ async function main() {
// Identity match only applies when pac is actually logged in.
const identitiesMatch = pacUser ? normalizeUser(azUser) === normalizeUser(pacUser) : false;
- // 3) WhoAmI — authoritative test
+ // 3) WhoAmI — authoritative test. Already in flight (or answered) when the token was read early, in
+ // which case its outcome is only READ here, after every verdict above; otherwise it is sent now. An early
+ // 401 is not taken as the answer: that request could not refresh the token without freezing the probes
+ // still running (see warmDataverseToken), so it is sent again here, with the refresh, as it always was.
let whoRes;
try {
- whoRes = await dataverseRequest(envUrl, 'GET', 'WhoAmI', null, { timeout: 30000 });
+ const early = warm ? await warm.whoAmI : null;
+ if (early && early.error) throw early.error;
+ whoRes = early && early.res.status !== 401 ? early.res : await dataverseRequest(envUrl, 'GET', 'WhoAmI', null, { timeout: 30000 });
} catch (e) {
// The token for WhoAmI is read here when the env URL came from pac (nothing was warmed above); a
// read that ran out of time is the Azure CLI being slow, not WhoAmI failing.
diff --git a/plugins/model-apps/scripts/check-griffel-styles.js b/plugins/model-apps/scripts/check-griffel-styles.js
new file mode 100644
index 000000000..76bf7f8d0
--- /dev/null
+++ b/plugins/model-apps/scripts/check-griffel-styles.js
@@ -0,0 +1,58 @@
+#!/usr/bin/env node
+'use strict';
+// Pre-transpile gate for /genpage: does a generated page write a CSS shorthand that Griffel drops at runtime?
+//
+// `pac model genpage transpile` does not run `makeStyles` and TypeScript does not know Griffel's list, so a page with `borderWidth: '1px'` in a style object
+// compiles, uploads and then renders without the border (the browser console logs `@griffel/react: You are using unsupported shorthand CSS property`). The rule itself
+// — which ten properties, and where in the page they count — lives in lib/griffel-styles.js. This wrapper exists so the orchestrator, an AI following SKILL.md,
+// gets a yes/no answer it cannot talk itself past, instead of a grep it has to read the result of.
+//
+// Usage:
+// node check-griffel-styles.js --file <page.tsx>
+//
+// Output (one JSON line) and exit code:
+// 0 {"ok":true,"filePath":…,"calls":1,"problems":[]}
+// 3 {"ok":false,…,"problems":[{"code","property","line","column","longhands","within","value","message"}]} — rewrite those keys with the longhands, then check again
+// 1 {"ok":false,"error":…} — usage error, or the file cannot be read
+// `calls` is how many makeStyles calls were read. A problem's `code` is `unsupported-shorthand`; or `unread-style-object`, a style object the checker cannot see — one
+// passed to the call (`makeStyles(styles)`), a slot or a selector given a variable, a spread of anything but an inline object — whose keys may be any of the ten, or a
+// computed key it cannot read as a name (`[key]: …`), so it is never reported as clean (write it inline); or — where the checker cannot read the code for certain —
+// `unverifiable-style-call` and `unbalanced-style-call`. `within` is
+// the slot, selectors and at-rules a key sits under (`["root", ":hover"]`): where it is apart from its line, and `value` is what the key is set to, as written (a quoted
+// string as its text in double quotes, anything else as its source text): together they let genpage-upload.js tell a key a page already had, set the same, from a new or
+// a changed one.
+
+const fs = require('node:fs');
+const path = require('node:path');
+const { griffelStyleProblems } = require('./lib/griffel-styles.js');
+
+function checkGriffelStyles({ filePath }) {
+ if (!filePath) return { exit: 1, result: { ok: false, error: '--file is required' } };
+ const abs = path.resolve(filePath);
+ let source;
+ try {
+ source = fs.readFileSync(abs, 'utf8');
+ } catch (e) {
+ return { exit: 1, result: { ok: false, filePath: abs, error: `--file could not be read: ${(e && e.code) || e}` } };
+ }
+ const { calls, problems } = griffelStyleProblems(source);
+ return { exit: problems.length ? 3 : 0, result: { ok: problems.length === 0, filePath: abs, calls, problems } };
+}
+
+function parseArgv(argv) {
+ const out = {};
+ for (let i = 0; i < argv.length; i += 1) {
+ if (argv[i] === '--file') { out.filePath = argv[i + 1]; i += 1; }
+ }
+ return out;
+}
+
+if (require.main === module) {
+ const { exit, result } = checkGriffelStyles(parseArgv(process.argv.slice(2)));
+ process.stdout.write(JSON.stringify(result) + '\n');
+ // Not process.exit(): a pipe's writes are queued on POSIX (synchronous on Windows), and a page with many findings makes a line longer than the pipe holds, so exiting
+ // right after the write would cut it off. https://nodejs.org/api/process.html#a-note-on-process-io
+ process.exitCode = exit;
+}
+
+module.exports = { checkGriffelStyles };
diff --git a/plugins/model-apps/scripts/dataverse-request.js b/plugins/model-apps/scripts/dataverse-request.js
index 8ccfad02c..6b9018b9e 100644
--- a/plugins/model-apps/scripts/dataverse-request.js
+++ b/plugins/model-apps/scripts/dataverse-request.js
@@ -10,7 +10,9 @@
// Arguments:
// envUrl - Dataverse environment URL (https://org.crm.dynamics.com)
// method - GET | POST | PATCH | DELETE
-// apiPath - Path after /api/data/v9.2/ (e.g. "EntityDefinitions(LogicalName='account')")
+// apiPath - Path after /api/data/v9.2/ (e.g. "EntityDefinitions(LogicalName='account')"). A path
+// that would leave that root is refused before a token is read; a '..' segment counts
+// whether written plainly, percent-encoded or joined by an encoded slash (%2F, %5C).
//
// Options:
// --body <json|@path> Inline JSON or @filepath to a JSON file
diff --git a/plugins/model-apps/scripts/download-model-app.js b/plugins/model-apps/scripts/download-model-app.js
index ffd7bed2c..6291c19ca 100644
--- a/plugins/model-apps/scripts/download-model-app.js
+++ b/plugins/model-apps/scripts/download-model-app.js
@@ -22,9 +22,11 @@ const { parseManifestBase64, manifestResourceName, reconcilePageIds } = require(
const { 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 } = require('./lib/app-spec.js');
+const { isPlatformIconRef, webResourceNameFromRef, validateAppSpec, normalizeLanguageCode, isLocalizedLabelMap, 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');
// 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' };
@@ -185,13 +187,70 @@ function adoptDeployedName(rel, deployed, auto, publisherPrefix, prefixUnknown,
}
}
-async function readRelationships(sdk, logicals, publisherPrefix, warn, { prefixUnknown = false } = {}) {
+// Per-table relationship reads overlap because they are independent network fetches, but the
+// TABLE-ORDER processing that dedupes, warns and chooses the surviving N:N owner stays sequential so
+// the emitted notes and winners do not depend on response timing.
+//
+// A failed read is captured as `{ error }` (the caught value itself) rather than as text, so the
+// ordered pass below words the note from it exactly as the sequential loop did — including for a
+// rejection that is not an Error, where `e && e.message` reads as undefined — and never mistakes a
+// falsy rejection for "no failure".
+async function readRelationshipMetadataForTable(sdk, logical) {
+ let rows = null;
+ let rowsFailure = null;
+ try {
+ // `dataverse.get` RESOLVES on a non-2xx rather than throwing, so the status must be checked
+ // explicitly — a bare try/catch would turn a 403 into "this table has no relationships".
+ const res = await sdk.dataverse.get(`/${metadataEntityPath(logical)}/ManyToOneRelationships`
+ + '?$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute,IsCustomRelationship');
+ if (!res || res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res && res.status}`);
+ rows = ((res.body && res.body.value) || []).filter((r) => r && r.IsCustomRelationship);
+ } catch (e) {
+ rowsFailure = { error: e };
+ }
+
+ if (rows === null) rows = [];
+ // Properly-cased lookup SchemaName + label. Best-effort: on failure the relationship still
+ // round-trips using the lowercase logical name, which produces the same Dataverse column.
+ // Skipped entirely when there is no relationship to label, so a table whose 1:N read failed
+ // does not also pay for an attribute read whose result nothing would consume.
+ const lookups = new Map();
+ if (rows.length) {
+ try {
+ const res = await sdk.dataverse.get(`/${metadataEntityPath(logical)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata`
+ + '?$select=LogicalName,SchemaName,DisplayName,Targets');
+ for (const a of ((res && res.body && res.body.value) || [])) lookups.set(String(a.LogicalName || '').toLowerCase(), a);
+ } catch { /* fall back to the relationship's own ReferencingAttribute */ }
+ }
+
+ let manyToManyRows = [];
+ let manyToManyFailure = null;
+ try {
+ // Many-to-many. Both ends must be in the app: the intersect table is created by the platform,
+ // so there is nothing to declare for a partner table a rebuild target would not have.
+ // Attempted INDEPENDENTLY of the 1:N read above: a failed 1:N read says nothing about whether
+ // N:N metadata is readable.
+ const res = await sdk.dataverse.get(`/${metadataEntityPath(logical)}/ManyToManyRelationships`
+ + '?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IsCustomRelationship');
+ if (!res || res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res && res.status}`);
+ manyToManyRows = ((res.body && res.body.value) || []).filter((x) => x && x.IsCustomRelationship);
+ } catch (e) {
+ manyToManyFailure = { error: e };
+ }
+ return { logical, rows, rowsFailure, lookups, manyToManyRows, manyToManyFailure };
+}
+
+async function readRelationships(sdk, logicals, publisherPrefix, warn, { prefixUnknown = false, entities = [], concurrency } = {}) {
+ concurrency = validatedDownloadConcurrency(concurrency);
const inApp = new Set((logicals || []).map((l) => String(l).toLowerCase()));
const lc = (s) => String(s || '').toLowerCase();
const relationships = [];
const skipped = [];
const seen = new Set(); // relationship SchemaName (lower) — a 1:N read from both ends, and every N:N, appears twice
const parentOk = new Map(); // logical -> can a rebuild target be relied on to have this table?
+ // The Dataverse Label of each stock parent, from the SAME read that decides whether it is stock — so
+ // knowing what a rebuild would label a lookup to it costs no request. See `omitsDefaultLabel` below.
+ const stockLabels = new Map(); // logical -> raw DisplayName
const note = (name, entity, reason) => {
skipped.push({ name, entity, reason });
if (typeof warn === 'function') warn(`relationship '${name}' on '${entity}' is not carried into the spec: ${reason}`);
@@ -210,44 +269,47 @@ async function readRelationships(sdk, logicals, publisherPrefix, warn, { prefixU
if (parentOk.has(key)) return parentOk.get(key);
let state = 'unknown';
try {
- const res = await sdk.dataverse.get(`/${metadataEntityPath(logical)}?$select=IsCustomEntity`);
+ const res = await sdk.dataverse.get(`/${metadataEntityPath(logical)}?$select=IsCustomEntity,DisplayName`);
if (res && res.status >= 200 && res.status < 300 && res.body) {
state = res.body.IsCustomEntity === false ? 'rebuildable' : 'custom';
+ if (res.body.DisplayName) stockLabels.set(key, res.body.DisplayName);
}
} catch { state = 'unknown'; }
parentOk.set(key, state);
return state;
};
- for (const logical of logicals || []) {
- let rows = null;
- try {
- // `dataverse.get` RESOLVES on a non-2xx rather than throwing, so the status must be checked
- // explicitly — a bare try/catch would turn a 403 into "this table has no relationships".
- const res = await sdk.dataverse.get(`/${metadataEntityPath(logical)}/ManyToOneRelationships`
- + '?$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute,IsCustomRelationship');
- if (!res || res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res && res.status}`);
- rows = ((res.body && res.body.value) || []).filter((r) => r && r.IsCustomRelationship);
- } catch (e) {
+ // ADO 6691205: may this lookup's label be left out of the downloaded spec? Only when a rebuild writes (or
+ // repairs it to) the same label for a lookup that sets none, so the downloaded spec stays minimal and a
+ // rebuild reproduces the label. A label that differs is carried, as ever, and so is every label when there
+ // is nothing to compare it with (no downloaded tables passed, or a stock parent whose label was not read):
+ // omitting is a claim about what a rebuild writes.
+ // * a parent IN the app: its downloaded displayName, string or map, compared whole;
+ // * a STOCK parent: its label in the one language the lookup's label is written in, because that is the
+ // language a rebuild writes it in;
+ // * the OLD DEFAULT an earlier build left on the column — the parent's logical name — is omitted too. It is an
+ // identifier, never a label anyone chose, and an explicit label is never repaired on a
+ // rebuild: writing it out would carry the defect through download -> edit -> rebuild for good,
+ // where leaving it out lets the rebuild repair it (the data-model phase's lookup label repair). The
+ // lookup's own name is NOT one: that is what the SDK left on a form FIELD it could not resolve, and no
+ // build ever wrote it on a column, so a column carrying it is somebody's label and is carried.
+ const omitsDefaultLabel = (referenced, lookupLabel, rawLookupLabel) => {
+ if (isOldLookupColumnLabel({ referenced }, lookupLabel)) return true;
+ const lookupLanguages = Object.keys(labelsByLcid(rawLookupLabel));
+ const stockRaw = stockLabels.get(lc(referenced));
+ const live = stockRaw && lookupLanguages.length === 1 ? labelsByLcid(stockRaw)[lookupLanguages[0]] : undefined;
+ const would = lookupLabelFor({ entities }, { referenced }, { liveReferencedLabel: live });
+ return (would.source === 'table' || would.source === 'environment') && sameLabel(lookupLabel, would.label);
+ };
+
+ const captured = await mapLimit(logicals || [], concurrency, (logical) => readRelationshipMetadataForTable(sdk, logical), { firstInOrder: true });
+ for (const { logical, rows, rowsFailure, lookups, manyToManyRows, manyToManyFailure } of captured) {
+ if (rowsFailure) {
// Report rather than swallow: "no relationships" and "the query failed" must not look alike.
// `rows` stays null so the 1:N block below is skipped, but the N:N read still runs — an
// earlier version `continue`d here, which meant a failed 1:N read ALSO skipped the N:N read
// silently, leaving any N:N both unreconstructed and unmentioned.
- note('(all)', lc(logical), `their metadata could not be read (${e && e.message})`);
- }
-
- if (rows === null) rows = [];
- // Properly-cased lookup SchemaName + label. Best-effort: on failure the relationship still
- // round-trips using the lowercase logical name, which produces the same Dataverse column.
- // Skipped entirely when there is no relationship to label, so a table whose 1:N read failed
- // does not also pay for an attribute read whose result nothing would consume.
- const lookups = new Map();
- if (rows.length) {
- try {
- const res = await sdk.dataverse.get(`/${metadataEntityPath(logical)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata`
- + '?$select=LogicalName,SchemaName,DisplayName,Targets');
- for (const a of ((res && res.body && res.body.value) || [])) lookups.set(lc(a.LogicalName), a);
- } catch { /* fall back to the relationship's own ReferencingAttribute */ }
+ note('(all)', lc(logical), `their metadata could not be read (${rowsFailure.error && rowsFailure.error.message})`);
}
// POLYMORPHIC lookups. One lookup column that targets several tables surfaces as SEVERAL
@@ -285,7 +347,7 @@ async function readRelationships(sdk, logicals, publisherPrefix, warn, { prefixU
const a = lookups.get(attr);
const lookup = { schemaName: (a && a.SchemaName) || r.ReferencingAttribute };
const displayName = a && labelFromDataverse(a.DisplayName);
- if (displayName) lookup.displayName = displayName;
+ if (displayName && !omitsDefaultLabel(referenced, displayName, a.DisplayName)) lookup.displayName = displayName;
// Keep the deployed name whenever it is not the one this prefix would generate. Omitting a
// foreign name used to rename it onto the generated default; the rebuild then created under
// that name, the CREATE failed because the lookup already existed, and the name search found
@@ -301,15 +363,11 @@ async function readRelationships(sdk, logicals, publisherPrefix, warn, { prefixU
relationships.push(rel);
}
- // Many-to-many. Both ends must be in the app: the intersect table is created by the platform,
- // so there is nothing to declare for a partner table a rebuild target would not have.
- // Attempted INDEPENDENTLY of the 1:N read above: a failed 1:N read says nothing about whether
- // N:N metadata is readable.
+ // The N:N rows were read above; the processing stays inside the same try as before, so a failed
+ // read — or anything thrown while processing — is still reported as the N:N metadata being unreadable.
try {
- const res = await sdk.dataverse.get(`/${metadataEntityPath(logical)}/ManyToManyRelationships`
- + '?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IsCustomRelationship');
- if (!res || res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res && res.status}`);
- for (const r of ((res.body && res.body.value) || []).filter((x) => x && x.IsCustomRelationship)) {
+ if (manyToManyFailure) throw manyToManyFailure.error;
+ for (const r of manyToManyRows) {
const key = lc(r.SchemaName);
if (seen.has(key)) continue;
seen.add(key);
@@ -1449,7 +1507,74 @@ function metadataEntityPath(logical) {
return `EntityDefinitions(LogicalName='${String(logical).replace(/'/g, "''")}')`;
}
-async function readEntityWithDescriptions(sdk, logical) {
+function validatedDownloadConcurrency(concurrency) {
+ if (concurrency === undefined) return 4;
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
+ throw new Error(`concurrency must be a positive integer (got ${JSON.stringify(concurrency)})`);
+ }
+ return concurrency;
+}
+
+// The SDK already fans a single table metadata fetch out across several concurrent reads. Keep the
+// TABLE loop ordered so the download never multiplies that environment-sized load; only the
+// post-hydration auxiliary reads below overlap, and their MERGE still runs in the original fixed
+// order so the emitted metadata stays byte-identical to the sequential download.
+async function readEntityAuxMetadata(sdk, logical, concurrency) {
+ const entityPath = `/${metadataEntityPath(logical)}`;
+ const tasks = [
+ async () => {
+ try {
+ const res = await sdk.dataverse.get(`${entityPath}?$select=LogicalName,Description,DisplayName,DisplayCollectionName`);
+ if (res && res.status >= 200 && res.status < 300 && res.body) {
+ return { kind: 'entityLabels', body: res.body };
+ }
+ return { kind: 'entityLabels', failed: `HTTP ${res && res.status}` };
+ } catch (err) {
+ return { kind: 'entityLabels', failed: (err && err.message) ? String(err.message).slice(0, 200) : 'read failed' };
+ }
+ },
+ async () => {
+ try {
+ const res = await sdk.dataverse.get(`${entityPath}/Attributes?$select=LogicalName,Description,DisplayName,IsLogical,AttributeOf,AttributeTypeName`);
+ 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 { kind: 'attributeLabels', rows: res.body.value };
+ } catch (err) {
+ return { kind: 'attributeLabels', failed: (err && err.message) ? String(err.message).slice(0, 200) : 'read failed' };
+ }
+ },
+ async () => {
+ try {
+ const res = await sdk.dataverse.get(`${entityPath}/Attributes/Microsoft.Dynamics.CRM.MoneyAttributeMetadata?$select=LogicalName,IsBaseCurrency`);
+ if (res && res.status >= 200 && res.status < 300 && res.body && Array.isArray(res.body.value)) {
+ return {
+ kind: 'moneyFlags',
+ baseCurrency: new Set(res.body.value
+ .filter((r) => r && r.LogicalName && r.IsBaseCurrency === true)
+ .map((r) => String(r.LogicalName).toLowerCase())),
+ };
+ }
+ } catch { /* best-effort: absent IsBaseCurrency keeps the column, which is the safe direction */ }
+ return { kind: 'moneyFlags', baseCurrency: new Set() };
+ },
+ async () => {
+ try {
+ const { byLogical, failed } = await readOptionSets(sdk, logical);
+ return { kind: 'optionSets', byLogical, failed: failed || null };
+ } catch (err) {
+ return {
+ kind: 'optionSets',
+ byLogical: new Map(),
+ failed: (err && err.message) ? String(err.message).slice(0, 200) : 'read failed',
+ };
+ }
+ },
+ ];
+ return mapLimit(tasks, concurrency, (task) => task(), { firstInOrder: true });
+}
+
+async function readEntityWithDescriptions(sdk, logical, { concurrency } = {}) {
+ concurrency = validatedDownloadConcurrency(concurrency);
const meta = { ...(await sdk.fetchEntityMetadata(logical)) };
// The SDK's fetchEntityMetadata projection is enough for identity but carries NO descriptions —
// measured against a live org, its entity keys are logicalName/schemaName/displayName/
@@ -1468,26 +1593,21 @@ async function readEntityWithDescriptions(sdk, logical) {
// NOTE `dataverse.get` RESOLVES with `{ status, headers, body }` on a non-2xx rather than throwing
// (a 404 returns status 404), so the status MUST be checked explicitly. A try/catch alone would
// reintroduce exactly the silence this replaces.
- const entityPath = `/${metadataEntityPath(logical)}`;
- try {
+ const [entityLabels, attributeLabels, moneyFlags, optionSets] = await readEntityAuxMetadata(sdk, logical, concurrency);
+ if (entityLabels.body) {
// DisplayName / DisplayCollectionName are read alongside Description so a table labelled in more
// than one language round-trips (AB#6686428). The SDK's own `fetchEntityMetadata` projection
// flattens `displayName` to ONE string, which is enough for identity but silently loses every
// other language — a rebuild from such a spec would recreate the table English-only.
- const res = await sdk.dataverse.get(`${entityPath}?$select=LogicalName,Description,DisplayName,DisplayCollectionName`);
- if (res && res.status >= 200 && res.status < 300 && res.body) {
- meta.Description = res.body.Description;
- meta.DisplayName = res.body.DisplayName;
- meta.DisplayCollectionName = res.body.DisplayCollectionName;
- } else {
- // 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 = `HTTP ${res && res.status}`;
- }
- } catch (err) {
- meta.labelReadFailed = (err && err.message) ? String(err.message).slice(0, 200) : 'read failed';
+ meta.Description = entityLabels.body.Description;
+ meta.DisplayName = entityLabels.body.DisplayName;
+ meta.DisplayCollectionName = entityLabels.body.DisplayCollectionName;
+ } else if (entityLabels.failed) {
+ // 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;
}
- try {
+ if (attributeLabels.rows) {
// Merge onto the SDK's attribute list rather than replacing it: `fetchEntityMetadata` supplies
// `targets` (lookup target tables) and `attributeType`, which this projection does not, and
// entityFromMetadata/other callers rely on them.
@@ -1503,73 +1623,50 @@ async function readEntityWithDescriptions(sdk, logical) {
// `AttributeOf` rides along for the same filter and is the STRONGER signal: it names the
// attribute a shadow belongs to, and a POLYMORPHIC lookup's shadows report `IsLogical: false`
// (live-measured), so `IsLogical` alone cannot see them.
- const res = await sdk.dataverse.get(`${entityPath}/Attributes?$select=LogicalName,Description,DisplayName,IsLogical,AttributeOf,AttributeTypeName`);
- 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');
- const rows = res.body.value;
- const byLogical = new Map(rows.filter((r) => r && r.LogicalName).map((r) => [String(r.LogicalName).toLowerCase(), r]));
+ const byLogical = new Map(attributeLabels.rows.filter((r) => r && r.LogicalName).map((r) => [String(r.LogicalName).toLowerCase(), r]));
meta.attributes = (meta.attributes || []).map((a) => {
const key = String((a && (a.logicalName || a.LogicalName)) || '').toLowerCase();
const row = byLogical.get(key);
return row ? { ...a, Description: row.Description, DisplayName: row.DisplayName, IsLogical: row.IsLogical, AttributeOf: row.AttributeOf, AttributeTypeName: row.AttributeTypeName } : a;
});
- } catch (err) {
+ } else if (attributeLabels.failed && !meta.labelReadFailed) {
// 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.
- if (!meta.labelReadFailed) {
- meta.labelReadFailed = (err && err.message) ? String(err.message).slice(0, 200) : 'read failed';
- }
+ meta.labelReadFailed = attributeLabels.failed;
}
- try {
- // 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.
- //
- // This is the only unambiguous way to recognise the `<money>_base` column Dataverse generates
- // beside every Money column. It reports no `AttributeOf`, is not logical, and is
- // `IsCustomAttribute: true`, so nothing else in the projection distinguishes it from a column the
- // author wrote — and emitting it made a rebuild try to create a column the platform owns.
- //
- // Best-effort on purpose: a failure leaves `IsBaseCurrency` absent on every attribute, and the
- // filter KEEPS an attribute whose flag it could not read. The cost of a failed read is the twin
- // reappearing, never a real column disappearing.
- const res = await sdk.dataverse.get(`${entityPath}/Attributes/Microsoft.Dynamics.CRM.MoneyAttributeMetadata?$select=LogicalName,IsBaseCurrency`);
- if (res && res.status >= 200 && res.status < 300 && res.body && Array.isArray(res.body.value)) {
- const baseCurrency = new Set(res.body.value
- .filter((r) => r && r.LogicalName && r.IsBaseCurrency === true)
- .map((r) => String(r.LogicalName).toLowerCase()));
- if (baseCurrency.size) {
- meta.attributes = (meta.attributes || []).map((a) => {
- const key = String((a && (a.logicalName || a.LogicalName)) || '').toLowerCase();
- return baseCurrency.has(key) ? { ...a, IsBaseCurrency: true } : a;
- });
- }
- }
- } catch {
- /* best-effort: absent IsBaseCurrency keeps the column, which is the safe direction */
- }
- try {
- // Choice / MultiChoice option sets (#564). A SEPARATE read from the attribute one above, and it
- // has to be: `OptionSet` can only be `$expand`ed through a type CAST, which the heterogeneous
- // `Attributes` collection cannot carry (see OPTION_SET_CASTS). Without it every Choice column
- // downloads WITHOUT a type, and a rebuild into a FRESH environment creates it as single-line
- // Text while a rebuild into the ORIGINAL environment silently reuses the real column — an
- // asymmetry that is much harder to notice than an outright failure.
- const { byLogical, failed } = await readOptionSets(sdk, logical);
- // Merged onto the attribute list, never replacing it: the SDK's own projection supplies
- // `attributeType`/`targets`, and the cast read returns ONLY picklist attributes.
+ // 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.
+ //
+ // This is the only unambiguous way to recognise the `<money>_base` column Dataverse generates
+ // beside every Money column. It reports no `AttributeOf`, is not logical, and is
+ // `IsCustomAttribute: true`, so nothing else in the projection distinguishes it from a column the
+ // author wrote — and emitting it made a rebuild try to create a column the platform owns.
+ //
+ // Best-effort on purpose: a failure leaves `IsBaseCurrency` absent on every attribute, and the
+ // filter KEEPS an attribute whose flag it could not read. The cost of a failed read is the twin
+ // reappearing, never a real column disappearing.
+ if (moneyFlags.baseCurrency && moneyFlags.baseCurrency.size) {
meta.attributes = (meta.attributes || []).map((a) => {
- const os = byLogical.get(String((a && (a.logicalName || a.LogicalName)) || '').toLowerCase());
- return os ? { ...a, optionSet: os } : a;
+ const key = String((a && (a.logicalName || a.LogicalName)) || '').toLowerCase();
+ return moneyFlags.baseCurrency.has(key) ? { ...a, IsBaseCurrency: true } : a;
});
- // A cast that failed is recorded WITHOUT discarding what the other one returned.
- if (failed) meta.optionSetReadFailed = failed;
- } catch (err) {
- // Recorded, not swallowed. "This table has no Choice columns" and "the option-set read returned
- // 403" are indistinguishable from the emitted spec — both yield untyped columns — so the reason
- // has to travel back with the metadata or the caller reports a degrade it cannot explain.
- meta.optionSetReadFailed = (err && err.message) ? String(err.message).slice(0, 200) : 'read failed';
}
+ // Choice / MultiChoice option sets (#564). A SEPARATE read from the attribute one above, and it
+ // has to be: `OptionSet` can only be `$expand`ed through a type CAST, which the heterogeneous
+ // `Attributes` collection cannot carry (see OPTION_SET_CASTS). Without it every Choice column
+ // downloads WITHOUT a type, and a rebuild into a FRESH environment creates it as single-line
+ // Text while a rebuild into the ORIGINAL environment silently reuses the real column — an
+ // asymmetry that is much harder to notice than an outright failure.
+ //
+ // Merged onto the attribute list, never replacing it: the SDK's own projection supplies
+ // `attributeType`/`targets`, and the cast read returns ONLY picklist attributes.
+ meta.attributes = (meta.attributes || []).map((a) => {
+ const os = optionSets.byLogical.get(String((a && (a.logicalName || a.LogicalName)) || '').toLowerCase());
+ return os ? { ...a, optionSet: os } : a;
+ });
+ // A cast that failed is recorded WITHOUT discarding what the other one returned.
+ if (optionSets.failed) meta.optionSetReadFailed = optionSets.failed;
return meta;
}
@@ -1871,7 +1968,8 @@ function installDownloadedPages(stagingRoot, pagesRoot) {
}
}
-async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLossy = false }) {
+async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLossy = false, concurrency }) {
+ concurrency = validatedDownloadConcurrency(concurrency);
// The caller named this directory. A link at its final component would make every page and
// the spec land outside it. Ancestors are the caller's choice and are not inspected.
assertSafeOutputDir(outDir);
@@ -2109,7 +2207,7 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLos
// the confusing downstream error the explicit branch below exists to avoid. Bucket it by origin
// exactly like the no-primary-name case, so the user is told the table AND the reason.
try {
- const meta = await readEntityWithDescriptions(sdk, logical);
+ const meta = await readEntityWithDescriptions(sdk, logical, { concurrency });
if (meta && meta.labelReadFailed) labelReadFailures.set(logical, meta.labelReadFailed);
if (meta && meta.optionSetReadFailed) optionSetReadFailures.set(logical, meta.optionSetReadFailed);
collectGlobalChoices(meta, globalChoiceDecls);
@@ -2279,7 +2377,7 @@ async function runDownload({ sdk, genpageCli, outDir, appId, appUnique, allowLos
try {
const rel = await readRelationships(sdk, allLogicals, solution.publisherPrefix, (m) => {
process.stderr.write(`WARNING: ${m}\n`);
- }, { prefixUnknown });
+ }, { prefixUnknown, entities, concurrency });
relationships = rel.relationships;
relationshipsSkipped = rel.skipped;
} catch (e) {
diff --git a/plugins/model-apps/scripts/genpage-upload.js b/plugins/model-apps/scripts/genpage-upload.js
index 3765811e4..953566e2a 100644
--- a/plugins/model-apps/scripts/genpage-upload.js
+++ b/plugins/model-apps/scripts/genpage-upload.js
@@ -23,15 +23,18 @@
// Usage:
// node scripts/genpage-upload.js --env <orgUrl> --app-id <guid> --code-file <path>
// --prompt-file <path> --agent-message-file <path>
-// [--page-id <guid>] [--name <text>] [--data-sources <csv>] [--compiled-code-file <path>]
+// [--page-id <guid>] [--name <text>] [--data-sources <csv>]
//
// `--prompt` / `--agent-message` are accepted for short, shell-safe text, but `--prompt-file` is
-// the documented path precisely because it cannot be mangled by a shell.
+// the documented path precisely because it cannot be mangled by a shell. `--compiled-code-file` is
+// refused (see main): pac compiles the checked `--code-file` itself.
const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const { parseArgs, validateFlags, emitResult } = require('./lib/dataverse-auth.js');
const { makeGenpageCli, suppliedButBlank, unescapePacName } = require('./lib/genpage-cli.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');
@@ -44,7 +47,7 @@ const NEED_VALUE = KNOWN.filter((f) => !SWITCHES.includes(f));
const USAGE = 'Usage: node scripts/genpage-upload.js --env <orgUrl> --app-id <guid> --code-file <path> '
+ '--prompt-file <path> --agent-message-file <path> [--page-id <guid>] [--name-file <path> | --name <text>] '
- + '[--data-sources <csv>] [--clear-data-sources] [--compiled-code-file <path>] [--model <id>] '
+ + '[--data-sources <csv>] [--clear-data-sources] [--model <id>] '
+ '[--connectors <path>] [--actions <path>] [--add-to-sitemap] [--overwrite-deployed]';
// The skill writes these inputs — the prompt, agent-message and page-name files, connectors.json, actions.json —
@@ -195,13 +198,15 @@ async function recordObservedBase(args) {
}
}
-async function writeObservedBase({ cli, flags, pageId, base, warnings, mkdtempSync, rmSync }) {
+async function writeObservedBase({ cli, flags, pageId, base, warnings, checkedText, mkdtempSync, rmSync }) {
const codeFile = flags['code-file'];
const mkdtemp = mkdtempSync || fs.mkdtempSync;
const rm = rmSync || fs.rmSync;
- let localText;
+ // The marker sits beside the file the caller named, which must still be a regular file with one name: readPlainText refuses a link, or a file
+ // that is gone, as it always did. What the marker records is the hash of the bytes that were checked and sent (`checkedText`) — never a new
+ // read of the file, which may have been saved again since; a later check then sees that save as a local change, which it is.
try {
- localText = base.readPlainText(path.resolve(codeFile));
+ base.readPlainText(path.resolve(codeFile));
} catch (e) {
warnings.push(`could not read ${codeFile} to record a base marker (${e.message}) — a later update will refuse no-base until the page is recorded`);
try { base.deleteMarker(codeFile); } catch (del) {
@@ -209,6 +214,7 @@ async function writeObservedBase({ cli, flags, pageId, base, warnings, mkdtempSy
}
return;
}
+ const localText = checkedText;
const localSha256 = base.pageHash(localText);
let deployedSha256 = localSha256;
let source = 'upload';
@@ -269,6 +275,16 @@ async function main(argv = process.argv.slice(2), deps = {}) {
return emit(false, { error: `--${required} is required\n${USAGE}` });
}
}
+ // Refused, not passed on. pac deploys the JavaScript in --compiled-code-file instead of compiling --code-file, and the Griffel check below
+ // reads the TypeScript: compiled output names makeStyles in ways the check does not read as Griffel's (`(0, x.makeStyles)(…)` after a
+ // require), and nothing ties the file to the source that was checked — so a page could ship a shorthand Griffel drops with no check at all.
+ // No flow of this plugin sends it; without it pac compiles the checked file itself, which is how every page here is deployed.
+ if (flags['compiled-code-file'] !== undefined) {
+ return emit(false, {
+ error: '--compiled-code-file is not accepted: the Griffel check reads the TypeScript in --code-file, and JavaScript compiled '
+ + 'elsewhere would be deployed without it. Leave it out — pac compiles the --code-file it is given.',
+ });
+ }
const prompt = resolveText(flags, 'prompt', 'prompt-file', readFile);
if (!prompt.ok) return emit(false, { error: prompt.error });
@@ -346,6 +362,39 @@ async function main(argv = process.argv.slice(2), deps = {}) {
if (linked) return emit(false, { error: `--${flag} ${linked}` });
}
+ // The page is read ONCE, here, and everything after is decided on these bytes: the Griffel check below, an update's comparison with the deployed page, the base marker's hash,
+ // and the upload itself, which sends pac a copy of them rather than the file (see the upload below). An update lists the environment and downloads the deployed page before it
+ // uploads — seconds in which the file can be saved again — and pac reading the file then would deploy bytes nothing here checked. A file that cannot be read is refused: there
+ // is nothing to check, or to send.
+ let checkedCode;
+ try {
+ checkedCode = fs.readFileSync(path.resolve(flags['code-file']));
+ } catch (e) {
+ return emit(false, { error: `--code-file could not be read: ${(e && e.message) || e}` });
+ }
+ const checkedText = checkedCode.toString('utf8');
+
+ // The Griffel check (AB#6691124), where every page upload passes: a /genpage create, an edit-flow update and a browser-verify fix all go through this script, so a page whose
+ // `makeStyles` writes one of the ten shorthands Griffel drops at runtime is refused here whether or not the skill's own gate (scripts/check-griffel-styles.js) was run before
+ // it — pac transpiles without executing makeStyles, and the page would otherwise deploy and render without its border, colour or reset. It is made on the bytes read above,
+ // which are the ones pac is sent.
+ // A CREATE is refused here, before any listing or download. An UPDATE is held to the check by what it ADDS: the page is already deployed, possibly with a key Griffel drops that an
+ // earlier version of the plugin let through, and the same bytes sent again ship nothing new — so the file is compared with the deployed page, which an update downloads anyway for
+ // its base check, and only a key that page did not have stops the upload (below, once it is read).
+ const styleProblems = griffelStyleProblems(checkedText).problems;
+ // The checker command the message suggests names the file: as one argument no shell reads anything in, or — for a path a shell cannot be given literally — as a
+ // placeholder, with the path named in a sentence instead (lib/cli-failure.js commandArg; a path can come from an untrusted checkout).
+ const griffelFile = commandArgOrPlaceholder(flags['code-file'], '<file>');
+ const griffelWords = { surface: 'upload', subject: flags['code-file'], command: `node scripts/check-griffel-styles.js --file ${griffelFile.arg}`, ...(griffelFile.note ? { note: griffelFile.note } : {}) };
+ const refuseStyles = (problems) => emit(false, {
+ ok: false,
+ code: 'griffel-shorthand',
+ error: describeGriffelRefusal(problems, flags['code-file'], griffelWords),
+ problems,
+ });
+ if (styleProblems.length && !flags['page-id']) return refuseStyles(styleProblems);
+ let griffelWarnings = [];
+
const cli = cliFactory(flags.env);
const base = deps.base || genpageBase;
@@ -504,6 +553,23 @@ async function main(argv = process.argv.slice(2), deps = {}) {
+ 'to replace it deliberately, or retry when the page can be downloaded.',
});
}
+ // The Griffel check for an UPDATE (see the create check above): what the deployed page already has ships nothing new. A file that IS the deployed page's text (pac's BOM and final
+ // CRLF are not a difference) is a re-send as it is, so none of its problems is new; otherwise a key counts as already there when the deployed page has it (griffelProblemsNotIn).
+ // Only a key, or a call the checker cannot read, that the deployed page did not have stops the upload — and --overwrite-deployed is no way past it: that flag is about edits made
+ // to the deployed page, not about what this file writes. When the deployed page could not be read (possible only under --overwrite-deployed) nothing says which keys it had; the
+ // page exists, and the release before this check updated it as it was, so the update goes on with a warning — as the build does for a page it has no record of.
+ if (styleProblems.length) {
+ if (probe.deployedText === null) {
+ griffelWarnings = [describeGriffelWarning(styleProblems, flags['code-file'], { ...griffelWords, standing: 'undetermined' })];
+ } else {
+ const sameAsDeployed = base.pageHash(checkedText) === base.pageHash(probe.deployedText);
+ const { added, inherited } = sameAsDeployed
+ ? { added: [], inherited: styleProblems }
+ : griffelProblemsNotIn(styleProblems, griffelStyleProblems(probe.deployedText).problems);
+ if (added.length) return refuseStyles(added);
+ griffelWarnings = [describeGriffelWarning(inherited, flags['code-file'], { ...griffelWords, standing: 'inherited' })];
+ }
+ }
if (preserveBindings) {
let why = null;
if (probe.configError || !probe.cfg) {
@@ -552,9 +618,7 @@ async function main(argv = process.argv.slice(2), deps = {}) {
});
}
if (cmp.deployed === 'changed') {
- let localText = '';
- try { localText = base.readPlainText(path.resolve(flags['code-file'])); } catch { /* summary against an unreadable local file */ }
- const lines = base.lineDelta(localText, probe.deployedText);
+ const lines = base.lineDelta(checkedText, probe.deployedText);
let deployedCopy;
let copyError;
try {
@@ -582,23 +646,40 @@ async function main(argv = process.argv.slice(2), deps = {}) {
}
}
+ // pac reads the code file itself, after every check above, so it is sent a copy of the bytes they were made on: a file of the same name (pac compiles by its extension) in a
+ // folder of its own, removed as soon as pac has answered and before anything is reported (emit may end the process). `sourceFile` is the file the caller named, which is what
+ // an upload's own messages point at; the base marker belongs to it too, and records the hash of these bytes.
+ let stageDir = null;
+ const removeStage = () => {
+ if (!stageDir) return;
+ try { fs.rmSync(stageDir, { recursive: true, force: true }); } catch { /* leave the temp dir */ }
+ stageDir = null;
+ };
try {
- const res = await cli.upload({
- appId: flags['app-id'],
- pageId: flags['page-id'] || undefined,
- codeFile: flags['code-file'],
- compiledCodeFile: flags['compiled-code-file'] || undefined,
- name: pageName.value || preservedName || undefined,
- prompt: prompt.value,
- agentMessage: agentMessage.value,
- // Passed through as the CSV the caller typed; upload() normalizes array-or-string. When the
- // caller said nothing on an update, this carries the page's EXISTING bindings so they survive.
- dataSources: flags['data-sources'] || preservedDataSources || undefined,
- model: flags.model || preservedModel || undefined,
- connectors: flags.connectors || undefined,
- actions: flags.actions || undefined,
- addToSitemap,
- });
+ stageDir = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-code-'));
+ const stagedCodeFile = path.join(stageDir, path.basename(flags['code-file']));
+ fs.writeFileSync(stagedCodeFile, checkedCode);
+ let res;
+ try {
+ res = await cli.upload({
+ appId: flags['app-id'],
+ pageId: flags['page-id'] || undefined,
+ codeFile: stagedCodeFile,
+ sourceFile: flags['code-file'],
+ name: pageName.value || preservedName || undefined,
+ prompt: prompt.value,
+ agentMessage: agentMessage.value,
+ // Passed through as the CSV the caller typed; upload() normalizes array-or-string. When the
+ // caller said nothing on an update, this carries the page's EXISTING bindings so they survive.
+ dataSources: flags['data-sources'] || preservedDataSources || undefined,
+ model: flags.model || preservedModel || undefined,
+ connectors: flags.connectors || undefined,
+ actions: flags.actions || undefined,
+ addToSitemap,
+ });
+ } finally {
+ removeStage();
+ }
const pageId = (res && (res.pageId || res.id)) || null;
// A create that asked for placement, crashed mid-flight, and was recovered as an UPDATE leaves
// the page deployed but NOT in the sitemap — invisible in the app's navigation. That is an
@@ -615,6 +696,7 @@ async function main(argv = process.argv.slice(2), deps = {}) {
// `pageId` is the one value a caller needs in order to continue (sitemap wiring, a follow-up
// edit). Echo the identity back rather than making the caller re-parse pac output.
const warnings = [
+ ...griffelWarnings,
...(modelUnread ? [`could not read page ${flags['page-id']}'s current model (${modelUnread}), so this update stored it empty — pass --model to set it`] : []),
...(nameUnread ? [`could not read page ${flags['page-id']}'s current name (${nameUnread}), so pac may have renamed it to its navigation title — pass --name-file to set it`] : []),
...(nameChanged ? [`page ${flags['page-id']}'s name ${JSON.stringify(nameChanged)} has a double quote (") pac cannot store as it is, so the page now shows \\" there — pass --name-file with typographic quotes (“ ”) or an apostrophe to fix it`] : []),
@@ -622,7 +704,7 @@ async function main(argv = process.argv.slice(2), deps = {}) {
];
// After the upload, not before emit's caller returns. The post-upload probe is removed inside
// recordObservedBase, so this emit — which may process.exit — does not leak it.
- if (pageId) await recordObservedBase({ cli, flags, pageId, base, warnings, mkdtempSync: deps.mkdtempSync, rmSync: deps.rmSync });
+ if (pageId) await recordObservedBase({ cli, flags, pageId, base, warnings, checkedText, mkdtempSync: deps.mkdtempSync, rmSync: deps.rmSync });
return emit(true, {
ok: true,
pageId,
@@ -632,6 +714,7 @@ async function main(argv = process.argv.slice(2), deps = {}) {
...(warnings.length ? { warnings } : {}),
});
} catch (e) {
+ removeStage();
return emit(false, { error: e && e.message ? e.message : String(e) });
}
}
diff --git a/plugins/model-apps/scripts/lib/ai-app-settings.js b/plugins/model-apps/scripts/lib/ai-app-settings.js
index 5e809c5b9..94fbfc85e 100644
--- a/plugins/model-apps/scripts/lib/ai-app-settings.js
+++ b/plugins/model-apps/scripts/lib/ai-app-settings.js
@@ -179,6 +179,39 @@ function rebucketNonEnablingSkips(result, encodedFlags) {
return result;
}
+/**
+ * Move the outcomes the SDK reports `applied` but flags `pendingPublish` out of `applied`, into a `pendingPublish`
+ * bucket of their own.
+ *
+ * The SDK proves an app-scope override where the write put it, and a write lands in the app's UNPUBLISHED layer — the
+ * published `appsettings` projection cannot show it, which is why a feature on a freshly created app used to read back
+ * `notPersisted` and be written again after a publish. It now reads the row where it is, and answers `applied` with
+ * `pendingPublish: true`: saved, in force once the app is published. That is not "applied" for this build unless a
+ * publish follows — nothing else publishes the app after the write, and `--verify` reads the published layer — so
+ * counting it applied would let a build without `--publish` report rows that are not in force.
+ *
+ * The bucket is the plugin's own, so `applied` stays the one bucket that means "in force", and the build's generic
+ * re-confirmation (every non-`applied` array in the result) takes it from here: it publishes the app and PROVES the
+ * row — the row is already saved, so there is nothing to write again — or, when the build has already published the
+ * app, only proves it. The same filing applies to the result of a write the re-confirmation re-issues, because a
+ * publish that failed, or could not be confirmed, leaves that row in the unpublished layer too.
+ *
+ * Mutates and returns `result`.
+ */
+function rebucketPendingPublish(result) {
+ if (!result || !Array.isArray(result.outcomes)) return result;
+ const pending = result.outcomes.filter((o) => o && o.status === 'applied' && o.pendingPublish === true && typeof o.feature === 'string');
+ if (!pending.length) return result;
+ const features = pending.map((o) => o.feature);
+ result.applied = (Array.isArray(result.applied) ? result.applied : []).filter((f) => !features.includes(f));
+ result.pendingPublish = [...(Array.isArray(result.pendingPublish) ? result.pendingPublish : []), ...features];
+ for (const o of pending) {
+ o.status = 'pendingPublish';
+ o.reason = "saved in the app's unpublished layer, so it is not in force until the app is published";
+ }
+ return result;
+}
+
/**
* Compare a stored setting value against a requested one.
*
@@ -273,6 +306,22 @@ async function proveAppOverride(read, appModuleId, setting, opts = {}) {
return last;
}
+// How long an app-scope override row is waited for after the call that should have put it in force (a write, or the
+// publish of the app). The row can lag briefly behind that call, and one read turns the lag into a false negative: it
+// reported a published row as NOT YET PUBLISHED in a run whose own `--verify` — which reads three times — passed. Only the
+// ABSENT case is read again (see proveAppOverride), 500 ms apart. ONE budget for the build's proof after its publish
+// and for `--verify`, so the two cannot disagree about the same row for want of a second look.
+const AI_PROOF_BUDGET = Object.freeze({ attempts: 3, delayMs: 500 });
+
+// The budget a caller uses: `AI_PROOF_BUDGET`, unless a test passes `proofAttempts` / `proofDelayMs` to drive the absent
+// path without paying the backoff (both callers take the same two options).
+function proofBudget(opts = {}) {
+ return {
+ attempts: opts.proofAttempts === undefined ? AI_PROOF_BUDGET.attempts : opts.proofAttempts,
+ delayMs: opts.proofDelayMs === undefined ? AI_PROOF_BUDGET.delayMs : opts.proofDelayMs,
+ };
+}
+
/**
* Resolve the EFFECTIVE value of a per-app AI setting: the most specific scope that holds a value
* wins — app-scope override, then the ENVIRONMENT-scope value, then the definition's default.
@@ -382,9 +431,12 @@ module.exports = {
featureWantValue,
encodeAiFlags,
rebucketNonEnablingSkips,
+ rebucketPendingPublish,
sameSettingValue,
resolveAppModuleId,
proveAppOverride,
+ AI_PROOF_BUDGET,
+ proofBudget,
effectiveSettingValue,
settingIsOn,
odataGuid,
diff --git a/plugins/model-apps/scripts/lib/app-components.js b/plugins/model-apps/scripts/lib/app-components.js
index c32a593ef..39dc81cb0 100644
--- a/plugins/model-apps/scripts/lib/app-components.js
+++ b/plugins/model-apps/scripts/lib/app-components.js
@@ -54,6 +54,12 @@ async function collectionRows(client, path, label) {
return rows;
}
+// The rows of ONE app that are its current layer: the only row, or — when a pending edit makes the platform answer with both layers — the authored one (componentstate 1).
+// Anything other than exactly one is for the caller to refuse: it does not say which layer is current.
+function currentLayerRows(rows) {
+ return rows.length === 1 ? rows : rows.filter((row) => row && Number(row.componentstate) === 1);
+}
+
async function currentAppLayer(client, appId) {
try {
const rows = await collectionRows(client,
@@ -61,7 +67,7 @@ async function currentAppLayer(client, appId) {
`current layer of app '${appId}'`);
// Measured: a pending write creates a NEW layer key; the published key still addresses the old
// rows. Never union the layers or cache this key across AddAppComponents or PublishXml.
- const current = rows.length === 1 ? rows : rows.filter((row) => row && Number(row.componentstate) === 1);
+ const current = currentLayerRows(rows);
if (current.length !== 1 || !current[0] || !FORM_GUID_RE.test(guidKey(current[0].appmoduleidunique))) {
return { ok: false, reason: `no single current layer among ${rows.length} app row(s)` };
}
@@ -523,7 +529,7 @@ async function appEntityComponentsFor(sdk, appUnique, wanted) {
}
module.exports = {
- currentAppLayer, publishedAppLayer, appComponentRows, tableRefs, tableComponentIds, pinAppTables,
+ currentAppLayer, currentLayerRows, publishedAppLayer, appComponentRows, collectionRows, tableRefs, tableComponentIds, pinAppTables,
publishAppComponents, appComponentsFor, applyAppMainForms, explainAppPushWarnings,
resolveMainForms, readMainFormMembership, appMainFormsFor, appEntityComponentsFor,
APP_COMPONENT_ENTITY_SOURCES, readAppComponentInventory, appComponentEntities, downloadAppMainForms, setAppMembershipFloor,
diff --git a/plugins/model-apps/scripts/lib/app-preview.js b/plugins/model-apps/scripts/lib/app-preview.js
index 0a6eb41a3..dc6741987 100644
--- a/plugins/model-apps/scripts/lib/app-preview.js
+++ b/plugins/model-apps/scripts/lib/app-preview.js
@@ -5,7 +5,7 @@
// per-form wireframes (reusing form-preview.js), page-INTENTS (purpose/data-sources/navigation), and
// the page design contract. Pure (no I/O); the CLI wrapper is preview-app.js. See design §12.
const { renderFormWireframe } = require('./form-preview.js');
-const { labelText } = require('./app-spec.js');
+const { labelText, lookupLabelFor } = require('./app-spec.js');
const lc = (s) => String(s || '').toLowerCase();
const h = (title) => `\n=== ${title} ===`;
@@ -20,7 +20,9 @@ function dataModelSection(spec) {
if (cols.length) out.push(` columns: ${cols.join(', ')}`);
}
for (const r of spec.relationships || []) {
- if (r.type === 'OneToMany') out.push(` ↳ 1:N ${lc(r.referenced)} → ${lc(r.referencing)} (lookup ${r.lookup && r.lookup.schemaName})`);
+ // The lookup's LABEL is shown beside its name: an omitted lookup.displayName defaults to the parent
+ // table's (lookupLabelFor), and that default is what the maker will read on the form.
+ if (r.type === 'OneToMany') out.push(` ↳ 1:N ${lc(r.referenced)} → ${lc(r.referencing)} (lookup ${r.lookup && r.lookup.schemaName} — "${labelText(lookupLabelFor(spec, r).label, spec && spec.languageCode)}")`);
else if (r.type === 'ManyToMany') out.push(` ↳ N:N ${lc(r.entity1)} ↔ ${lc(r.entity2)}`);
}
return out;
diff --git a/plugins/model-apps/scripts/lib/app-spec-doc.js b/plugins/model-apps/scripts/lib/app-spec-doc.js
index 4da9ed7ce..b6a7c264d 100644
--- a/plugins/model-apps/scripts/lib/app-spec-doc.js
+++ b/plugins/model-apps/scripts/lib/app-spec-doc.js
@@ -16,7 +16,7 @@
// PURE: no I/O. The CLI wrapper (scripts/write-app-spec-doc.js) owns writing the file.
const lc = (s) => String(s || '').toLowerCase();
-const { labelText } = require('./app-spec.js');
+const { labelText, lookupLabelFor } = require('./app-spec.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
@@ -38,6 +38,18 @@ const text = (value, fallback = '') => {
return s || fallback;
};
+// Where a sub-grid says it goes (`tab` / `column` / `after` / `before`), worded for the plan; empty for a grid
+// that says nothing, which is how every grid read before the keys existed. A value of the wrong type is skipped:
+// reporting it is validateAppSpec's job, not the plan's.
+function gridPlacement(sg) {
+ const parts = [];
+ if (typeof sg.tab === 'string' && sg.tab.trim()) parts.push(`tab ${sg.tab.trim()}`);
+ if (Number.isInteger(sg.column)) parts.push(`column ${sg.column}`);
+ if (typeof sg.after === 'string' && sg.after.trim()) parts.push(`after ${sg.after.trim()}`);
+ if (typeof sg.before === 'string' && sg.before.trim()) parts.push(`before ${sg.before.trim()}`);
+ return parts.join(', ');
+}
+
function overview(spec) {
const app = spec.app || {};
const out = [`# ${text(app.name, 'Model-driven app')} — design`, ''];
@@ -149,10 +161,12 @@ function dataModel(spec) {
}
const rels = objs(spec.relationships);
if (rels.length) {
- out.push('### Relationships', '', '| Kind | From | To | Lookup |', '|---|---|---|---|');
+ // `Label` is what the lookup column (and its form field) is called: the author's lookup.displayName, else
+ // the parent table's name — see lookupLabelFor — so the plan reads "Project", not a logical name.
+ out.push('### Relationships', '', '| Kind | From | To | Lookup | Label |', '|---|---|---|---|---|');
for (const r of rels) {
- if (r.type === 'ManyToMany') out.push(`| N:N | ${cell(lc(r.entity1))} | ${cell(lc(r.entity2))} | — |`);
- else out.push(`| 1:N | ${cell(lc(r.referenced))} | ${cell(lc(r.referencing))} | ${cell(r.lookup && r.lookup.schemaName)} |`);
+ if (r.type === 'ManyToMany') out.push(`| N:N | ${cell(lc(r.entity1))} | ${cell(lc(r.entity2))} | — | — |`);
+ else out.push(`| 1:N | ${cell(lc(r.referenced))} | ${cell(lc(r.referencing))} | ${cell(r.lookup && r.lookup.schemaName)} | ${cell(labelText(lookupLabelFor(spec, r).label, spec && spec.languageCode))} |`);
}
out.push('');
}
@@ -194,7 +208,7 @@ function surfaces(spec) {
else {
out.push('| Form | Table | Type | Layout | Sub-grids |', '|---|---|---|---|---|');
for (const f of forms) {
- const sg = objs(f.subgrids).map((s) => cell(lc(s.childEntity))).join(', ');
+ const sg = objs(f.subgrids).map((s) => { const where = gridPlacement(s); return `${cell(lc(s.childEntity))}${where ? ` (${cell(where)})` : ''}`; }).join(', ');
// `formType` is the canonical field (Main / QuickCreate / QuickView), defaulting to Main —
// NOT `type`. Reading the wrong one rendered every QuickCreate/QuickView form as "main",
// hiding a real difference in what the form does.
diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.js
index cadbb8354..b36849bcd 100644
--- a/plugins/model-apps/scripts/lib/app-spec.js
+++ b/plugins/model-apps/scripts/lib/app-spec.js
@@ -5,6 +5,7 @@ const path = require('node:path');
const { isAppSourcePath } = require('./app-source-path.js');
const { normalizeSpecShape } = require('./spec-shape.js');
const { isMainForm, selectDefaultForm, ordersByHand } = require('./form-order.js');
+const { AUTO_TAB_NAME, AUTO_SECTION_NAME, placementOf, resolvePlacement } = require('./form-subgrid-placement.js');
// URL scheme allowlist for spec-supplied URLs that the built app will RENDER (iframe dashboard tiles,
// sitemap URL subareas). Only http(s) is allowed — a `javascript:`, `data:`, `vbscript:`, or `file:`
@@ -289,7 +290,8 @@ function resolveParentRelationship(spec, parentEntity, childEntity, wanted) {
// auto-layout and default-view enrichment call this to surface the parent links (otherwise the
// parent lookup is invisible on the form/grid). N:N relationships use an intersect table and place
// no lookup column on either side, so they're excluded. Deduped by logical name; declared order
-// preserved. Returns [{ logical, displayName }].
+// preserved. Returns [{ logical, displayName, source, rel }] — `displayName` is the label the column
+// carries (see lookupLabelFor), `source` where it came from, and `rel` the relationship it belongs to.
function lookupColumnsFor(spec, entityLogical) {
const child = String(entityLogical || '').toLowerCase();
const seen = new Set();
@@ -300,11 +302,117 @@ function lookupColumnsFor(spec, entityLogical) {
const logical = String((r.lookup && r.lookup.schemaName) || '').toLowerCase();
if (!logical || seen.has(logical)) continue;
seen.add(logical);
- out.push({ logical, displayName: labelText((r.lookup && r.lookup.displayName), spec && spec.languageCode) || (r.lookup && r.lookup.schemaName) || logical });
+ const { label, source } = lookupLabelFor(spec, r);
+ out.push({ logical, displayName: labelText(label, spec && spec.languageCode) || (r.lookup && r.lookup.schemaName) || logical, source, rel: r });
}
return out;
}
+// --- 1:N lookup column labels (ADO 6691205) ------------------------------------------------------
+//
+// A relationship's lookup column is labelled by `relationships[].lookup.displayName`. When the author
+// omits it the label used to be whatever the SDK fell back to: the build passed `lookupDisplayName:
+// undefined` and the vendored SDK substitutes the REFERENCED table's LOGICAL name —
+// DisplayName: label(opts.lookupDisplayName ?? opts.referencedEntity, lcid) // "new_project"
+// — so the column read "new_project" where a maker expects "Project", and so did every form cell: the
+// SDK derives a bound control's label from the column's DisplayName when it pushes. The maker portal
+// does the opposite and labels a new lookup with the related table's display name.
+//
+// ONE rule serves every consumer — the build (what is sent), the form/preview/doc/eval surfaces (what
+// is shown) and the rebuild repair (what an old default becomes) — so none can disagree. In order:
+// 1. an explicit `lookup.displayName`, string or LCID map, kept as written ('explicit');
+// 2. the referenced table's own `displayName` when entities[] declares it, string or LCID map, kept
+// as the map: the SDK serializes a map into one LocalizedLabel per language ('table');
+// 3. the display name the ENVIRONMENT reports for a parent whose name the spec cannot give: a table
+// it does not declare — account, contact, systemuser… — or one it declares WITHOUT a displayName
+// that the build does not create (see lookupParentNeedsEnvironment). Only a caller that read it can
+// supply `liveReferencedLabel`, so offline surfaces skip this step ('environment');
+// 4. a humanized form of the table's name ("contoso_ProjectPhase" -> "Project Phase"), only when
+// nothing above applies: an offline surface, a failed environment read, or a declared table that
+// has no displayName of its own and is created by the build ('derived').
+// A blank explicit label counts as omitted, because every create site already treats it that way
+// (`x.displayName || x.schemaName`), so "" and undefined reach Dataverse identically.
+//
+// `liveReferencedLabel` is ignored when it is only the table's own identifier — its logical name, or its
+// schema name as written (exact, case-sensitive: "Contact" is a name, "contact" is not). That is what a
+// build writes as the label of a table whose spec sets no displayName, so reading it back is no more a
+// name than the humanized fallback is, and using it would reproduce the very label this rule replaces.
+function lookupLabelFor(spec, rel, opts = {}) {
+ const explicit = rel && rel.lookup && rel.lookup.displayName;
+ if (!labelIsMissing(explicit)) return { label: explicit, source: 'explicit' };
+ const wanted = String((rel && rel.referenced) || '').toLowerCase();
+ const parent = ((spec && spec.entities) || []).find((e) => e && String(e.schemaName || '').toLowerCase() === wanted);
+ if (parent && !labelIsMissing(parent.displayName)) return { label: parent.displayName, source: 'table' };
+ const live = opts && opts.liveReferencedLabel;
+ if (typeof live === 'string' && live.trim() && live !== wanted && !(parent && live === parent.schemaName)) return { label: live, source: 'environment' };
+ return { label: humanizeTableName(parent ? parent.schemaName : rel && rel.referenced), source: 'derived' };
+}
+
+// Must a build ask the ENVIRONMENT for this lookup's parent name? (It does the asking — this file does no
+// I/O.) Meaningful only when the lookup sets no label of its own.
+// * a parent the spec does not declare: always — account, contact, systemuser… have no displayName here;
+// * a parent the spec declares WITH a displayName: never — the spec names it (lookupLabelFor, step 2);
+// * a parent declared WITHOUT one: when the build did not create it. `existing: true` says the table
+// pre-exists (incident is "Case", systemuser is "User", which a humanized "Incident"/"Systemuser" would
+// contradict), and `reused` — the declared tables, lower-case, that the data-model phase found already
+// in the environment — covers one that merely was there. `existing` records ownership, not presence,
+// so a flagged table the build had to create is still labelled by what the build wrote (its schema
+// name, which lookupLabelFor discards) and falls through to the humanized name.
+// A declared table the build creates with no displayName has nothing worth reading: it is labelled with
+// its own schema name, so the answer would only ever be the identifier.
+function lookupParentNeedsEnvironment(spec, rel, { reused } = {}) {
+ const wanted = String((rel && rel.referenced) || '').toLowerCase();
+ const parent = ((spec && spec.entities) || []).find((e) => e && String(e.schemaName || '').toLowerCase() === wanted);
+ if (!parent) return true;
+ if (!labelIsMissing(parent.displayName)) return false;
+ return parent.existing === true || !!(reused && reused.has(wanted));
+}
+
+// A person's name for a table, from its Dataverse name:
+// contoso_ProjectPhase -> "Project Phase" new_project -> "Project" account -> "Account"
+// contoso_work_item -> "Work Item" contoso_SLA -> "SLA"
+// A Dataverse table name is `<publisher prefix>_<name>`; the prefix is bookkeeping, not part of what a
+// person calls the table, and a name with no underscore (`account`) has none. A cased schema name
+// ("ProjectPhase") splits on its capitals; an all-lowercase logical name has nothing to split on, so
+// "budgetline" stays one word — the reason this is the LAST resort rather than the rule.
+function humanizeTableName(name) {
+ const parts = String(name == null ? '' : name).trim().split('_').filter(Boolean);
+ const words = [];
+ for (const part of parts.length > 1 ? parts.slice(1) : parts) {
+ for (const word of part.replace(/([a-z0-9])([A-Z])/g, '$1 $2').split(' ')) {
+ if (word) words.push(word.charAt(0).toUpperCase() + word.slice(1));
+ }
+ }
+ return words.join(' ');
+}
+
+// The strings a lookup was labelled with when no label was supplied. All of them are identifiers, never
+// something a person writes as a label, which is what lets a rebuild repair them without risking a label a maker
+// chose. Which strings count depends on what carries the label, because each is exactly what some build wrote
+// THERE and nothing else is:
+// * the COLUMN: the referenced table's LOWER-CASE logical name — what the vendored SDK substitutes for an
+// omitted `lookupDisplayName` (this plugin hands it `referenced` lower-cased). No build wrote anything else on
+// a column, so a column labelled with the lookup's own name is somebody's label, and is never repaired;
+// * the form FIELD: that same name, inherited from the column, or — when the SDK cannot resolve the column at
+// push — the field's own LOWER-CASE logical name, because its control normalization defaults `label` to
+// `fieldName`, which is the lower-case logical name, not the schema name the spec spells with capitals.
+//
+// Exactly those strings, not their case variants. A match that ignored case would call a correct "Contact"
+// (the display name of the table `contact`) an old default: every rebuild would read the label and then the
+// table's name to find out it was already right, and a maker's "Contact" on a table the org later renamed
+// would be overwritten. A map is never the default either: the old default was written in one language only,
+// so a label carrying several was touched since.
+const lowerName = (n) => (n == null ? '' : String(n).toLowerCase());
+const isExactlyOneOf = (label, names) => typeof label === 'string' && label !== '' && names.includes(label);
+
+function isOldLookupColumnLabel(rel, label) {
+ return isExactlyOneOf(label, [lowerName(rel && rel.referenced)]);
+}
+
+function isOldLookupFieldLabel(rel, label) {
+ return isExactlyOneOf(label, [lowerName(rel && rel.referenced), lowerName(rel && rel.lookup && rel.lookup.schemaName)]);
+}
+
// The child relationships to show as sub-grids on `entityLogical`'s (parent) form: every 1:N where
// this entity is the REFERENCED (parent) side, plus every N:N it participates in. Returns the child
// (the "many"/other side) as [{ childEntity }], deduped, declared order preserved. Used by the opt-in
@@ -393,6 +501,17 @@ function manyToManySchemaName(rel, publisherPrefix) {
return prefixedRelationshipName(a, b, publisherPrefix);
}
+// The relationship a form's sub-grid for `childEntity` shows — a 1:N where the child holds the lookup, else an N:N
+// — as the schema name the grid control carries (`RelationshipName`), or null when the two tables have none. One
+// definition for the build, which writes the control, and `--verify`, which looks for it by that name.
+function subgridRelationshipName(spec, formEntity, childEntity) {
+ const prefix = spec && spec.solution && spec.solution.publisherPrefix;
+ const oneToMany = relationshipFor(spec, formEntity, childEntity);
+ if (oneToMany) return relationshipSchemaName(oneToMany, prefix);
+ const manyToMany = manyToManyFor(spec, formEntity, childEntity);
+ return manyToMany ? manyToManySchemaName(manyToMany, prefix) : null;
+}
+
// Effective schema name, or null when the entry cannot name one. An explicit schemaName wins
// verbatim (the same rule relationshipSchemaName / manyToManySchemaName use). Incomplete entries
// are skipped: composing them would yield a shared "_" name and a false collision.
@@ -734,6 +853,32 @@ const ENTITY_KEY_HINTS = Object.assign(Object.create(null), {
localizedLabels: ' — write the LCID map on the label FIELD itself (e.g. "displayName": { "1033": "Baseline", "3082": "Línea base" }), not in a separate per-table block; see references/app-spec-schema.md → "Localized labels"',
});
+// The most characters a table's primary name column may be asked for. A single line of text elsewhere in a table takes up
+// to 4,000, but the name column of a table does not: asked for more than 850 in a table create that also carried other columns, the
+// platform refuses it — HTTP 400, "The maximum length of Primary attribute 'new_name' is 4000. The maximum allowed limit
+// is 850." (live-measured, with 4000 asked for). `primaryAttribute.maxLength` was accepted and ignored until the build
+// began sending it, so a value the platform cannot take is refused at the spec gate rather than part-way through a build.
+// See: https://learn.microsoft.com/en-us/power-apps/maker/data-platform/types-of-fields
+const PRIMARY_NAME_MAX_LENGTH = 850;
+
+// Why a `primaryAttribute.maxLength` cannot be used, or null when it can; an omitted one is fine (the build then asks for
+// 100, as it always has). The ONE rule behind both gates — validateAppSpec and the
+// provision-entities input validator, the entry point of /genpage and /app-builder — so that neither accepts what the other
+// refuses. `!== undefined`, so an explicit null or 0 is refused rather than read as "not given".
+function primaryNameLengthProblem(length) {
+ if (length === undefined) return null;
+ if (Number.isInteger(length) && length >= 1 && length <= PRIMARY_NAME_MAX_LENGTH) return null;
+ return `primaryAttribute.maxLength must be a whole number from 1 to ${PRIMARY_NAME_MAX_LENGTH} (got ${describeSpecValue(length)})`;
+}
+
+// The length the spec asks for a table's primary name column, or undefined when it does not ask. The build, its dry-run plan
+// and its progress total all key on this one answer — it decides whether the build has a "primary column length" step for
+// the table — so they cannot disagree about it (the same arrangement as quickCreateEnabledFor).
+function askedPrimaryNameLength(entity) {
+ const asked = entity && entity.primaryAttribute && entity.primaryAttribute.maxLength;
+ return asked === undefined || asked === null ? undefined : asked;
+}
+
// 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
@@ -1413,6 +1558,126 @@ function authoredTabNames(formSpec) {
return names;
}
+// The tabs, form-columns and sections a form's layout DECLARES, under the names the compiler gives them,
+// lower-cased — the vocabulary `subgrids[].tab/after/before` is written in, and what the build, verify and the
+// wireframe resolve a placement against (lib/form-subgrid-placement.js). Unlike the name sets above it keeps the
+// STRUCTURE, because "right after this section" and "in this tab's second form-column" need to know which
+// column a section is in. An auto layout (no `tabs`) is its one tab, holding one section.
+function formLayoutNames(formSpec) {
+ if (!formSpec || !Array.isArray(formSpec.tabs)) return [{ name: AUTO_TAB_NAME, columns: [{ sections: [AUTO_SECTION_NAME] }] }];
+ return formSpec.tabs.map((t, ti) => ({
+ name: String((t && t.name) || generatedTabName(ti)).toLowerCase(),
+ columns: formColumnsOf(t).map((col, ci) => ({
+ sections: ((col && Array.isArray(col.sections)) ? col.sections : [])
+ .map((s, si) => String((s && s.name) || generatedSectionName(ti, ci, si)).toLowerCase()),
+ })),
+ }));
+}
+
+// The keys a `subgrids[]` entry reads. The build ignores any other, so a mistyped placement key (`After`,
+// `afterSection`) would leave the grid at the end of the form with nothing said — hence a warning. A warning,
+// not an error: entries written before the placement keys existed carry whatever extra keys their authors
+// tried, and the build never read them, so refusing those now would break a spec that built.
+const SUBGRID_KEYS = ['childEntity', 'view', 'label', 'tab', 'column', 'after', 'before'];
+
+// The keys of a `subgrids[]` entry that nothing reads, as messages that start with the entry (the caller adds
+// the form) — with the key it most likely meant when the name differs only in case or by a suffix.
+function subgridUnknownKeys(sg) {
+ if (!sg || typeof sg !== 'object' || Array.isArray(sg)) return [];
+ return Object.keys(sg).filter((k) => !SUBGRID_KEYS.includes(k)).map((k) => {
+ const lower = k.toLowerCase();
+ const meant = SUBGRID_KEYS.find((known) => lower === known.toLowerCase() || (known.length >= 3 && lower.startsWith(known.toLowerCase())));
+ return `subgrid '${sg.childEntity}' has the key '${k}', which nothing reads${meant ? ` — did you mean '${meant}'?` : ''} (the keys are ${SUBGRID_KEYS.join(', ')})`;
+ });
+}
+
+// What is wrong with where a `subgrids[]` entry places its grid, as messages that start with the entry (the
+// caller adds the form). Empty for an entry that places nothing. The spec gate and the standalone lint both ask
+// this one function, so they cannot disagree about what is a valid placement — a placement that validates here
+// is one the build resolves, and one it resolves is one `--verify` can check.
+//
+// Types are checked first and stop the rest: a placement whose values are not names or a whole number cannot be
+// resolved against the layout, and a second message about it would only restate the first.
+function subgridPlacementProblems(formSpec, sg) {
+ const out = [];
+ if (!sg || typeof sg !== 'object' || Array.isArray(sg)) return out;
+ const who = `subgrid '${sg.childEntity}'`;
+ for (const key of ['tab', 'after', 'before']) {
+ if (sg[key] !== undefined && !(typeof sg[key] === 'string' && sg[key].trim() !== '')) {
+ out.push(`${who} has ${key} ${JSON.stringify(sg[key])} — it must be the name of a ${key === 'tab' ? 'tab' : 'section'} on this form, as a non-empty string`);
+ }
+ }
+ if (sg.column !== undefined && (!Number.isInteger(sg.column) || sg.column < 0)) {
+ out.push(`${who} has column ${JSON.stringify(sg.column)} — it must be a whole number from 0, the first form-column of its tab`);
+ }
+ if (out.length) return out;
+ const placement = placementOf(sg);
+ if (!placement) return out;
+ const layout = formLayoutNames(formSpec);
+ const resolved = resolvePlacement(layout, placement);
+ if (resolved.ok) return out;
+ const explicit = Array.isArray(formSpec && formSpec.tabs);
+ const tabs = layout.map((t) => t.name).join(', ');
+ const sections = layout.flatMap((t) => t.columns.flatMap((c) => c.sections)).join(', ');
+ const autoNote = explicit ? '' : ` (an auto layout has the one tab '${AUTO_TAB_NAME}' holding the one section '${AUTO_SECTION_NAME}' — declare tabs[] for more)`;
+ switch (resolved.code) {
+ case 'both':
+ out.push(`${who} sets both 'after' and 'before' — give one: the grid goes right after a section or right before one, not both`);
+ break;
+ case 'tab':
+ out.push(`${who} places the grid in tab '${sg.tab}', which this form does not declare (its tabs: ${tabs})${autoNote}`);
+ break;
+ case 'column':
+ out.push(`${who} places the grid in column ${sg.column} of tab '${layout[resolved.tabIndex].name}', which has ${resolved.columns} form-column(s) — count from 0`);
+ break;
+ case 'anchor':
+ out.push(`${who} places the grid ${resolved.anchor.side} section '${sg[resolved.anchor.side]}', which this form does not declare (its sections: ${sections || 'none'})${autoNote}`);
+ break;
+ case 'anchor-tab':
+ out.push(`${who} places the grid ${resolved.anchor.side} section '${sg[resolved.anchor.side]}', which is in tab '${resolved.actualTab}', not in tab '${sg.tab}' — the grid goes in its anchor's tab, so drop 'tab' or name the right one`);
+ break;
+ case 'anchor-column':
+ out.push(`${who} places the grid ${resolved.anchor.side} section '${sg[resolved.anchor.side]}', which is in form-column ${resolved.actualColumn} of its tab, not ${sg.column} — the grid goes in its anchor's column, so drop 'column' or name the right one`);
+ break;
+ default:
+ break;
+ }
+ return out;
+}
+
+// The entries of a form's `subgrids[]` that name ONE relationship, as { errors, warnings } of messages that start with
+// the entry (the caller adds the form). A form holds one grid per relationship — the build finds a grid by it, and an
+// entry whose grid is already there adds nothing — so of several entries only one can say where the grid goes, and the
+// others' placement could never be honoured, silently: a check looks a grid up by its relationship, so every entry
+// for it would read the same grid and pass or fail together.
+//
+// An ERROR when any of the entries declares where the grid goes. Those keys are new, so no spec that built before can
+// carry one. A repeat that places nothing is a WARNING: specs have always been able to carry it and the build has always
+// ignored the extra entry, so refusing it now would break a spec that built. Entries are grouped by the relationship
+// they resolve to (subgridRelationshipName — what the build writes and verify looks for), so the same table spelled in
+// another case counts, and an entry with no relationship is left to the error it already gets. The gate and the lint
+// both ask this one function.
+function subgridDuplicateProblems(spec, formSpec) {
+ const out = { errors: [], warnings: [] };
+ const groups = new Map();
+ (Array.isArray(formSpec && formSpec.subgrids) ? formSpec.subgrids : []).forEach((sg, index) => {
+ if (!sg || typeof sg !== 'object' || Array.isArray(sg) || typeof sg.childEntity !== 'string') return;
+ const relationship = subgridRelationshipName(spec, formSpec.entity, sg.childEntity);
+ if (!relationship) return;
+ const key = relationship.toLowerCase();
+ if (!groups.has(key)) groups.set(key, []);
+ groups.get(key).push({ index, sg });
+ });
+ for (const entries of groups.values()) {
+ if (entries.length < 2) continue;
+ const which = entries.map((e) => `subgrids[${e.index}]`).join(', ');
+ const said = `subgrids lists the sub-grid for '${entries[0].sg.childEntity}' more than once (${which}) — a form holds one grid per relationship`;
+ if (entries.some((e) => placementOf(e.sg))) out.errors.push(`${said}, so only one entry can say where it goes; keep one`);
+ else out.warnings.push(`${said}, so the build adds one and ignores the rest`);
+ }
+ return out;
+}
+
// The plugin's own version, read from its manifest, for the `minimumPluginVersion` capability gate.
//
// Cached, and NULL when the manifest cannot be read. The caller decides what that means, and it is
@@ -2153,6 +2418,12 @@ function validateAppSpec(spec, opts = {}) {
if (!e.primaryAttribute || !e.primaryAttribute.schemaName) {
errors.push(`entity ${e.schemaName}: primaryAttribute.schemaName required`);
}
+ // The length of the table's name column, asked for when the table is created (an existing table's column is left as it
+ // is).
+ if (e.primaryAttribute && typeof e.primaryAttribute === 'object') {
+ const lengthProblem = primaryNameLengthProblem(e.primaryAttribute.maxLength);
+ if (lengthProblem) errors.push(`entity ${e.schemaName}: ${lengthProblem}`);
+ }
if (e.quickCreate !== undefined && typeof e.quickCreate !== 'boolean') {
errors.push(`entity ${e.schemaName}: quickCreate must be a boolean`);
}
@@ -2463,6 +2734,7 @@ function validateAppSpec(spec, opts = {}) {
errors.push(`form ${f.entity}: a subgrid is missing childEntity`);
continue;
}
+ for (const message of subgridUnknownKeys(sg)) warnings.push(`form ${f.entity}: ${message}`);
if (badEntityRef(sg.childEntity, `form ${f.entity}: subgrid childEntity`)) continue;
if (!entityByLower.has(String(sg.childEntity).toLowerCase())) {
errors.push(`form ${f.entity}: subgrid references unknown childEntity '${sg.childEntity}'`);
@@ -2473,6 +2745,17 @@ function validateAppSpec(spec, opts = {}) {
`form ${f.entity}: no OneToMany or ManyToMany relationship between '${f.entity}' and subgrid childEntity '${sg.childEntity}'`
);
}
+ // Where the grid goes (tab / column / after / before). A non-Main form already fails for hosting a
+ // grid at all, so its placement is not judged on top of that.
+ if (formType === 'Main') {
+ for (const message of subgridPlacementProblems(f, sg)) errors.push(`form ${f.entity}: ${message}`);
+ }
+ }
+ // …and a relationship listed more than once (an error when an entry places the grid, else a warning).
+ if (formType === 'Main') {
+ const duplicates = subgridDuplicateProblems(spec, f);
+ for (const message of duplicates.errors) errors.push(`form ${f.entity}: ${message}`);
+ for (const message of duplicates.warnings) warnings.push(`form ${f.entity}: ${message}`);
}
}
}
@@ -3939,7 +4222,14 @@ module.exports = {
formColumnsOf,
authoredSectionNames,
authoredTabNames,
+ formLayoutNames,
+ subgridPlacementProblems,
+ subgridDuplicateProblems,
+ subgridUnknownKeys,
validateAppSpec,
+ PRIMARY_NAME_MAX_LENGTH,
+ primaryNameLengthProblem,
+ askedPrimaryNameLength,
validateSampleDataRows,
normalizePageSource,
normalizeLanguageCode,
@@ -3991,6 +4281,11 @@ module.exports = {
relationshipFor,
resolveParentRelationship,
lookupColumnsFor,
+ lookupLabelFor,
+ lookupParentNeedsEnvironment,
+ humanizeTableName,
+ isOldLookupColumnLabel,
+ isOldLookupFieldLabel,
// Exported so every raw-spec form reader — including the offline eval harness — goes through the
// one helper that understands BOTH tab shapes. A reader that opens `tab.sections` directly silently
// skips every multi-column tab, which is exactly how a lint rule came to report such a tab as
@@ -4001,6 +4296,7 @@ module.exports = {
prefixedRelationshipName,
manyToManyFor,
manyToManySchemaName,
+ subgridRelationshipName,
relationshipNameCollisions,
relationshipCollisionMessage,
specDeclaresAttribute,
diff --git a/plugins/model-apps/scripts/lib/artifact-intent.js b/plugins/model-apps/scripts/lib/artifact-intent.js
index 942d12c4c..669c282fa 100644
--- a/plugins/model-apps/scripts/lib/artifact-intent.js
+++ b/plugins/model-apps/scripts/lib/artifact-intent.js
@@ -13,6 +13,7 @@
const { entityByLogical } = require('./_graph.js');
const { lookupColumnsFor, generatedTabName, generatedSectionName, formColumnsOf, authoredSectionNames, authoredTabNames } = require('./app-spec.js');
const { SDK_COLUMN_TYPE } = require('./entity-provision.js');
+const { timelineCellIntent, timelineRowsIntent, wantsTimeline } = require('./form-timeline.js');
// Arrange field cells into `columns` cells-per-row.
// Mirrors rowsFromCells in sdk-build.js but lives here so this module is
@@ -251,20 +252,17 @@ function mergeFieldOptions(base, inline, logical) {
// the GUID lives in the SDK bundle's constants, not in the plugin. Hardcoding it would
// break when the bundle is re-vendored with a changed GUID.
// Shape proven by the SDK's form.workflow.test.ts.
+//
+// The cell is the platform's timeline cell — the fixed control id `notescontrol` in a tall cell with
+// `auto="false"` — not just a control in a one-row cell, which Dynamics publishes and never renders (#680).
+// The shape lives in form-timeline.js, shared with the build's repair of an older host and with verify.
function notesCellIntent(notesClassId) {
- return {
- control: {
- classId: String(notesClassId),
- fieldName: null,
- label: 'Notes',
- showLabel: false,
- parameters: {}
- }
- };
+ return timelineCellIntent(notesClassId);
}
-// The whole Notes SectionIntent — a pre-built section holding only the timeline cell.
-// Appended to the first tab's single FormColumn when the form/entity opts in.
+// The whole Notes SectionIntent — a pre-built section holding the timeline cell and the empty rows that
+// cell spans (the timeline does not render without them). Appended to the first tab's single FormColumn
+// when the form/entity opts in.
function notesSectionIntent(notesClassId) {
return {
name: 'section_notes',
@@ -272,7 +270,7 @@ function notesSectionIntent(notesClassId) {
visible: true,
showLabel: true,
columns: 1,
- rows: [{ cells: [notesCellIntent(notesClassId)] }]
+ rows: timelineRowsIntent(notesClassId)
};
}
@@ -454,11 +452,17 @@ function reorderCellsByAnchors(cells, positions) {
// This is the AUTHORED effective width, not the live one: the reconcile deliberately clamps against
// the section it is writing into (`convergeCellSpans`), which on an existing form can differ.
//
-// Quick Create forms must use single-column sections. Dataverse rejects multi-column
-// (columns="11"/"111") quick-create sections with "Columns in a section must be set to '1'".
+// Quick Create AND Quick View forms must use single-column sections. Dataverse rejects a
+// multi-column section (columns="11"/"111") on either with
+// HTTP 400 … systemforms: Columns in a section must be set to '1'. Found '11'.
+// — measured live on a Quick View whose auto layout had gone to two columns past six fields. The
+// cap used to cover Quick Create only, so a field-heavy Quick View failed the build mid-run.
+const SINGLE_COLUMN_FORM_TYPES = new Set(['QuickCreate', 'QuickView']);
+function maxSectionColumns(formType) {
+ return SINGLE_COLUMN_FORM_TYPES.has(formType) ? 1 : 4;
+}
function sectionGridWidth(section, formType) {
- const maxCols = formType === 'QuickCreate' ? 1 : 4;
- return Math.min((section && section.columns) || 1, maxCols);
+ return Math.min((section && section.columns) || 1, maxSectionColumns(formType));
}
// Compile an App Spec form entry into the SDK's canonical desired-state intent.
@@ -487,10 +491,10 @@ function compileFormIntent(spec, formSpec, opts) {
const entity = entityByLogical(spec, entityLogical);
const formType = formSpec.formType || 'Main';
- // The QuickCreate single-column cap — the same rule `sectionGridWidth` applies to explicit
- // sections; the auto layout below picks its own 1-or-2 within it. It also blocks notes:
- // quick-create forms don't host the timeline.
- const maxCols = formType === 'QuickCreate' ? 1 : 4;
+ // The single-column cap for Quick Create and Quick View forms — the same rule `sectionGridWidth`
+ // applies to explicit sections; the auto layout below picks its own 1-or-2 within it. (Notes are
+ // gated separately below: only a Main form hosts the timeline.)
+ const maxCols = maxSectionColumns(formType);
const explicit = Array.isArray(formSpec.tabs) || formSpec.layout === 'explicit';
// Compute per-field required flag. isRequired is explicit authored intent (the primary
@@ -666,7 +670,7 @@ function compileFormIntent(spec, formSpec, opts) {
// Notes section (opt-in: formSpec.notes or entity.hasNotes) — Main forms only.
// Quick-create / quick-view forms don't host the activity timeline.
// Appended to the first tab's single FormColumn so it renders below the field sections.
- const wantNotes = formType === 'Main' && (formSpec.notes === true || (entity && entity.hasNotes === true));
+ const wantNotes = wantsTimeline(spec, formSpec);
if (wantNotes) {
// notesClassId is an SDK constant supplied by the engine at call time. If not yet
// provided, notesCellIntent(undefined) is still emitted (the section must exist in the
@@ -687,6 +691,9 @@ function compileFormIntent(spec, formSpec, opts) {
description: formSpec.description,
status: 'Active',
tabs: tabs,
+ // Whether this form asks for the Notes timeline (see wantsTimeline). The engine's reconcile reads it to
+ // repair an older host in place and to add one to an auto layout, which has no topology pass to do it.
+ __notes: wantNotes,
// Whether an authored tabs layout was ACTUALLY used, which is NOT the same as `explicit` above.
// `explicit` is also true for `layout: 'explicit'` with no `tabs`, and in that case the compiler
// falls through to the AUTO branch — so reporting it as explicit would tell the engine's
@@ -808,7 +815,15 @@ function sectionRowsPointer(ti, ci, si) {
// fragile and unreadable. Same scan and same non-field-control exclusions as findFieldCellPointer —
// that function is kept as the thin wrapper so existing callers are untouched.
function findFieldCellLocation(formJson, logical) {
+ return findFieldCellLocations(formJson, logical)[0] || null;
+}
+
+// The location (as findFieldCellLocation gives it) of EVERY cell hosting the bound field `logical`, in form
+// order: tabs → columns → sections → rows → cells. A deployed form can hold a field more than once — a maker can
+// place it in a second section — and each placement is a cell of its own, with its own label and control.
+function findFieldCellLocations(formJson, logical) {
const lg = String(logical || '').toLowerCase();
+ const found = [];
const tabs = formJson.tabs || [];
for (let ti = 0; ti < tabs.length; ti++) {
const cols = tabs[ti].columns || [];
@@ -830,7 +845,7 @@ function findFieldCellLocation(formJson, logical) {
const sectionPointer = '/tabs/' + ti + '/columns/' + ci + '/sections/' + si;
const rowsPointer = sectionPointer + '/rows';
const rowPointer = rowsPointer + '/' + ri;
- return {
+ found.push({
sectionPointer,
rowsPointer,
rowPointer,
@@ -840,13 +855,13 @@ function findFieldCellLocation(formJson, logical) {
cellIndex: celli,
flatIndex: flat,
rowCellCount: cells.length,
- };
+ });
}
}
}
}
}
- return null;
+ return found;
}
// A deployed section, located by NAME (case-insensitive) across the WHOLE form, or null.
@@ -859,14 +874,33 @@ function findFieldCellLocation(formJson, logical) {
function findSectionLocation(formJson, sectionName, accept) {
const want = String(sectionName || '').toLowerCase();
if (!want) return null;
+ return findSectionWhere(formJson, (section) => String(section.name || '').toLowerCase() === want && (!accept || accept(section)));
+}
+
+// A deployed section, located by its `id` across the WHOLE form, or null.
+//
+// The id is the one identity of a section that survives everything the build does to the sections around it. A
+// section's INDEX shifts whenever one is added ahead of it in its column or taken out of it, and its NAME is not
+// reliable: a real section and the emptied copy an older build left share one, and a section a maker made may have
+// none. So a caller that holds a section across such a change — the build keeps a field it is adding until every
+// positioning step is done, and the sub-grids are placed in between — finds it again by this. The SDK mints a GUID
+// for every section it adds and keeps the one a fetched form carries; compared as text, case-insensitively.
+function findSectionById(formJson, id) {
+ const want = String(id == null ? '' : id).toLowerCase();
+ if (!want) return null;
+ return findSectionWhere(formJson, (section) => String(section.id == null ? '' : section.id).toLowerCase() === want);
+}
+
+// The first section, in document order, that `matches`, with where it is: { pointer, rowsPointer, tabIndex,
+// columnIndex, sectionIndex, section } — or null. The one walk behind the by-name and by-id lookups.
+function findSectionWhere(formJson, matches) {
const tabs = formJson.tabs || [];
for (let ti = 0; ti < tabs.length; ti++) {
const cols = tabs[ti].columns || [];
for (let ci = 0; ci < cols.length; ci++) {
const sections = cols[ci].sections || [];
for (let si = 0; si < sections.length; si++) {
- if (String(sections[si].name || '').toLowerCase() !== want) continue;
- if (accept && !accept(sections[si])) continue;
+ if (!matches(sections[si])) continue;
const pointer = '/tabs/' + ti + '/columns/' + ci + '/sections/' + si;
return { pointer, rowsPointer: pointer + '/rows', tabIndex: ti, columnIndex: ci, sectionIndex: si, section: sections[si] };
}
@@ -938,7 +972,9 @@ module.exports = {
sectionRowsPointer,
findFieldCellPointer,
findFieldCellLocation,
+ findFieldCellLocations,
findSectionLocation,
+ findSectionById,
declaredSectionByField,
equalColumnWidths,
normalizeFieldEntry,
diff --git a/plugins/model-apps/scripts/lib/cli-failure.js b/plugins/model-apps/scripts/lib/cli-failure.js
index 10ba2c282..eba2ae605 100644
--- a/plugins/model-apps/scripts/lib/cli-failure.js
+++ b/plugins/model-apps/scripts/lib/cli-failure.js
@@ -55,4 +55,90 @@ function azTimeoutAdvice(command, ms = azTimeoutMs()) {
+ `${AZ_TIMEOUT_ENV}=${longer}.`;
}
-module.exports = { AZ_TIMEOUT_ENV, DEFAULT_AZ_TIMEOUT_MS, MIN_AZ_TIMEOUT_MS, MAX_AZ_TIMEOUT_MS, azTimeoutMs, cliFailureKind, azTimeoutAdvice };
+// ── The time one `pac model genpage` call may take ─────────────────────────────────────────────────────────────
+// A page upload once stalled — no CPU, no network — for 17 minutes, until the process was killed by hand; the build then finished. A pac call
+// therefore waits a bounded time (lib/genpage-cli.js runPac ends the whole process tree when it runs out and reports `timedOut`). The bound is
+// generous, because a real upload of a large page is slow and a slow call is not a stalled one:
+// list, download 3 min (a listing takes ~5 s; a download is a few files)
+// upload 10 min (it transpiles the page and writes it through the service)
+// POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS sets the budget of ONE call, for every kind, for a machine or an environment slower than that: 1 s to
+// 60 min. Like the Azure CLI budget it is a tuning knob, so an unusable value keeps the default instead of stopping the work.
+const PAC_TIMEOUT_ENV = 'POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS';
+const DEFAULT_PAC_READ_TIMEOUT_MS = 180000;
+const DEFAULT_PAC_UPLOAD_TIMEOUT_MS = 600000;
+const MIN_PAC_TIMEOUT_MS = 1000;
+const MAX_PAC_TIMEOUT_MS = 3600000;
+
+// The budget for one pac call of `kind` ('upload'; anything else is a read: list, download).
+function pacTimeoutMs(kind, env = process.env) {
+ const n = Number(env && env[PAC_TIMEOUT_ENV]);
+ if (Number.isInteger(n) && n >= MIN_PAC_TIMEOUT_MS && n <= MAX_PAC_TIMEOUT_MS) return n;
+ return kind === 'upload' ? DEFAULT_PAC_UPLOAD_TIMEOUT_MS : DEFAULT_PAC_READ_TIMEOUT_MS;
+}
+
+// The budget to suggest in place of `ms`: one pacTimeoutMs accepts — double, at least 5 min, capped at the maximum — or null once `ms` is the
+// maximum, because nothing larger would be read and the default would quietly come back.
+function pacLongerTimeoutMs(ms) {
+ return ms >= MAX_PAC_TIMEOUT_MS ? null : Math.min(Math.max(ms * 2, 300000), MAX_PAC_TIMEOUT_MS);
+}
+
+// What to tell the user when `command` ran out of time: that it was stopped, and how to allow it longer. As for azTimeoutAdvice, the suggested
+// budget is one pacTimeoutMs accepts, and once the budget is the maximum, more time is not the remedy. For a READ — a listing or a download, which
+// can be made again at no cost; an upload that stalls says what to do about itself (lib/genpage-cli.js), because running it again is not always safe.
+function pacTimeoutAdvice(command, ms) {
+ const ranOut = `\`${command}\` did not finish within ${Math.round(ms / 1000)} s and was stopped.`;
+ const longer = pacLongerTimeoutMs(ms);
+ if (longer === null) {
+ return `${ranOut} That is already the longest ${PAC_TIMEOUT_ENV} allows (${MAX_PAC_TIMEOUT_MS / 60000} min), so waiting longer will not help: `
+ + 'check that the PAC CLI can reach the environment (`pac org who`), then retry.';
+ }
+ return `${ranOut} A stalled call is usually transient — retry, or allow it longer with ${PAC_TIMEOUT_ENV}=${longer}.`;
+}
+
+// One argument of a command that a message tells the user — or the agent driving the skill — to paste, written so that pasting the command hands the
+// program it runs (`node`) exactly this value, as ONE argument, in the shells the skill's own commands are written for: PowerShell (Windows PowerShell 5.1
+// and PowerShell 7) and the POSIX shells (sh, bash, zsh). The skill's instructions quote arguments in single quotes ('<working-dir>/<file>.tsx'); cmd.exe,
+// which reads no single quotes, is not one of them.
+// letters and digits of any script, and `_ . / : -` written bare: no shell reads anything in them
+// (not a leading `-`)
+// anything else single-quoted: inside '…' neither PowerShell nor a POSIX shell expands, substitutes or splits
+// anything, so `;`, `$(…)`, backticks, `|`, `&`, globs, `\` and white space stay literal
+// null — no spelling, so the caller writes a placeholder and names the value outside the command (commandArgOrPlaceholder) — for:
+// a single quote, or one PowerShell reads as one PowerShell doubles a quote, a POSIX shell closes and reopens one: no spelling is literal in both
+// (‘ ’ ‚ ‛), a line break or another control
+// character (a tab is fine)
+// a double quote; white space with a `\` at the Windows PowerShell does not hand a native program its arguments as they are: it joins them into one
+// end; the empty value command line, wrapping a value that holds white space in double quotes and escaping nothing, so the
+// program drops a `"` ('x"y.tsx' arrives as xy.tsx) and reads the closing quote after a final `\` as
+// an escaped one ('C:\Dev User\' arrives as C:\Dev User"); an empty value is not passed at all.
+// PowerShell 7.3 and later pass all three as they are; Windows PowerShell 5.1 is still the one
+// Windows ships.
+// exactly `--%` PowerShell's stop-parsing token: both PowerShells take it for the token even quoted, and drop it
+// Measured on Windows PowerShell 5.1 and PowerShell 7.6 (tests/cli-failure.test.js runs every spelling through each shell it finds and reads node's argv).
+// See https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_parsing#passing-arguments-that-contain-quote-characters and
+// https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_parsing#the-stop-parsing-token.
+// A path can come from an untrusted checkout, so a value is written bare only when it is plain: a file named `x;rm -rf ~;.tsx`, written bare or in double
+// quotes, would run its second half when the advice is pasted.
+const BARE_ARG = /^(?!-)[\p{L}\p{N}_./:-]+$/u;
+const UNQUOTABLE = /['"\u2018\u2019\u201A\u201B\p{Zl}\p{Zp}]|[^\P{Cc}\t]/u;
+function commandArg(value) {
+ const text = String(value);
+ if (BARE_ARG.test(text)) return text;
+ if (UNQUOTABLE.test(text) || text === '' || text === '--%' || (/\s/u.test(text) && text.endsWith('\\'))) return null;
+ return `'${text}'`;
+}
+
+// commandArg's spelling of `value`, or — when it has none — `placeholder` (`<file>`), with the sentence a message adds to name the value as data, never as part of
+// a command.
+function commandArgOrPlaceholder(value, placeholder) {
+ const arg = commandArg(value);
+ if (arg !== null) return { arg, note: '' };
+ return {
+ arg: placeholder,
+ note: `${placeholder} is ${JSON.stringify(String(value))}; it is not written into the command because no way of writing it reaches the command unchanged in both PowerShell and a POSIX shell.`,
+ };
+}
+
+module.exports = { AZ_TIMEOUT_ENV, DEFAULT_AZ_TIMEOUT_MS, MIN_AZ_TIMEOUT_MS, MAX_AZ_TIMEOUT_MS, azTimeoutMs, cliFailureKind, azTimeoutAdvice,
+ PAC_TIMEOUT_ENV, DEFAULT_PAC_READ_TIMEOUT_MS, DEFAULT_PAC_UPLOAD_TIMEOUT_MS, MIN_PAC_TIMEOUT_MS, MAX_PAC_TIMEOUT_MS, pacTimeoutMs, pacLongerTimeoutMs, pacTimeoutAdvice, commandArg,
+ commandArgOrPlaceholder };
diff --git a/plugins/model-apps/scripts/lib/content-hash.js b/plugins/model-apps/scripts/lib/content-hash.js
index c3cf413de..58231a568 100644
--- a/plugins/model-apps/scripts/lib/content-hash.js
+++ b/plugins/model-apps/scripts/lib/content-hash.js
@@ -71,6 +71,16 @@ function annotateContentHashes(spec, readFile) {
return clone;
}
+// The hash annotateContentHashes recorded for the page `key` in `spec` — the annotated spec an earlier apply (or a download) wrote to last-applied.json, read back by
+// deployed-baseline.js readBaseline, which returns it only for the app and environment being built — or null when there is none to compare with: no baseline, no page of that key,
+// an intent page (nothing on disk to hash), or a source that could not be read then (recorded as null, which no hash equals). A page is "the one that was last sent" when its
+// bytes hash to this (sha256 of the raw file, as annotateContentHashes hashes them), and nothing else about the page decides it.
+function recordedContentSha(spec, key) {
+ const pages = spec && Array.isArray(spec.pages) ? spec.pages : [];
+ const page = pages.find((p) => p && typeof p === 'object' && (p.key || p.name) === key);
+ return page && typeof page.__contentSha === 'string' && page.__contentSha ? page.__contentSha : null;
+}
+
// Validate the on-disk half of every implemented page declaration. Schema validation proves a
// `source.kind: "tsx"` page NAMES a confined codeFile; this proves the named file exists and is a
// regular file before lint/preview/dry-run can call the page "implemented". `isFile` is injectable
@@ -122,4 +132,4 @@ function appSourceFileErrors(spec, appDir, deps = {}) {
return [...pageSourceFileErrors(spec, appDir, deps), ...webResourceSourceFileErrors(spec, appDir, deps)];
}
-module.exports = { annotateContentHashes, pageContentPath, pageSourceFileErrors, webResourceSourceFileErrors, appSourceFileErrors };
+module.exports = { annotateContentHashes, recordedContentSha, pageContentPath, pageSourceFileErrors, webResourceSourceFileErrors, appSourceFileErrors };
diff --git a/plugins/model-apps/scripts/lib/dataverse-auth.js b/plugins/model-apps/scripts/lib/dataverse-auth.js
index 2253366f9..f839c2ba9 100644
--- a/plugins/model-apps/scripts/lib/dataverse-auth.js
+++ b/plugins/model-apps/scripts/lib/dataverse-auth.js
@@ -8,7 +8,7 @@
// about what counts as an LCID. app-spec.js does not require this module, so there is no cycle.
const { normalizeLanguageCode } = require('./app-spec.js');
const { nearestName } = require('./nearest-name.js');
-const { execFileAsync, runSync } = require('./process-runner.js');
+const { execFileAsync, runSync, killProcessTree } = require('./process-runner.js');
const { azTimeoutMs, azTimeoutAdvice, cliFailureKind } = require('./cli-failure.js');
// Dataverse environment hosts, one family per cloud (the same families power-pages accepts in
@@ -49,6 +49,54 @@ function requireDataverseOrigin(value) {
return origin;
}
+// Every path handed to `dataverseRequest` must stay under this root. `dataverse-request.js` is an
+// escape hatch an agent drives with free text, so a path such as "../../../XRMServices/…" must not
+// reach another endpoint with the user's token. The origin cannot move: the validated origin is
+// followed by `/api/…`, so everything the caller adds is path, query or fragment (an absolute URL
+// passed as the path stays text under the root). The path can move, in two places:
+// 1. The client. `makeRequest` sends the WHATWG-parsed `pathname`, and the parser resolves `.` and
+// `..` segments, their percent-encoded spellings (`%2e%2e`, `.%2E`) and, for https, `\` as `/`.
+// See https://url.spec.whatwg.org/#double-dot-path-segment
+// 2. The server. Measured on a live environment: Dataverse decodes `%2F` and `%5C` (either case)
+// into separators once, then resolves dot segments again:
+// "..%2Fv9.0%2FWhoAmI" → served /api/data/v9.0/WhoAmI (200)
+// "..%5Cv9.0%5CWhoAmI" → served /api/data/v9.0/WhoAmI (200)
+// "%252e%252e/…" → 404 (decoded once only)
+// `%u002f`, an overlong `%c0%af` and a fullwidth solidus were not read as separators, and a `..`
+// followed by `%00`, `%09`, `%20` or `;` was not read as `..` (400 or 404, never the parent).
+// So both readings are checked. A leading slash stays allowed: Dataverse answers
+// `/api/data/v9.2//WhoAmI` like `/api/data/v9.2/WhoAmI`. A query is not checked, because no
+// endpoint resolves dot segments inside one.
+const WEB_API_ROOT = '/api/data/v9.2/';
+
+/**
+ * The request URL for a path under the Dataverse Web API root; throws when the path, as the client
+ * sends it or as the server then decodes it, would leave that root.
+ * @param {string} origin - a value returned by requireDataverseOrigin
+ * @param {string} apiPath - e.g. "EntityDefinitions(LogicalName='account')"
+ * @returns {string} e.g. "https://contoso.crm.dynamics.com/api/data/v9.2/EntityDefinitions(LogicalName='account')"
+ */
+function webApiUrl(origin, apiPath) {
+ if (typeof apiPath !== 'string') {
+ throw new Error(`A Dataverse Web API path must be text (got ${apiPath === null ? 'null' : typeof apiPath}).`);
+ }
+ const url = `${origin}${WEB_API_ROOT}${apiPath}`;
+ const sent = new URL(url);
+ const served = new URL(origin + sent.pathname.replace(/%2f|%5c/gi, '/')).pathname;
+ const escaped = !sent.pathname.startsWith(WEB_API_ROOT) ? sent.pathname
+ : !served.startsWith(WEB_API_ROOT) ? served
+ : null;
+ if (escaped !== null) {
+ throw new Error(
+ `The path '${apiPath}' leaves the Dataverse Web API root ${WEB_API_ROOT} (it resolves to '${escaped}'). `
+ + `Pass a path relative to that root, for example "EntityDefinitions(LogicalName='account')". `
+ + "A '..' segment cannot step out of it, whether written plainly, percent-encoded (%2e%2e) or "
+ + 'joined by an encoded slash (%2F, %5C).'
+ );
+ }
+ return url;
+}
+
/**
* Gets an Azure CLI access token for the given Dataverse environment URL.
* Returns null if `az` is missing, the user isn't logged in, the resource is unreachable, or the
@@ -93,6 +141,13 @@ function getAuthToken(envUrl, opts = {}) {
}
}
+// `opts.signal` (an AbortSignal) lets a caller that started this read beside other probes cancel it when
+// one of them already decides the run (check-auth: an `az account show` verdict ends it before the token
+// matters). The abort ends the child's whole PROCESS TREE (killProcessTree): on Windows `az` is a batch shim
+// run under cmd.exe, and the signal Node would send on its own reaches only that wrapper, leaving `az`'s Python
+// process running after this one exits — which is why the signal is NOT handed to the child's start. A cancelled
+// read resolves null WITHOUT noting a failure: nothing was wrong with the Azure CLI, and a remembered 'failed'
+// would be reported later as if it were.
function getAuthTokenAsync(envUrl, opts = {}) {
const resource = dataverseOrigin(envUrl);
if (!resource) return Promise.resolve(null);
@@ -100,14 +155,21 @@ function getAuthTokenAsync(envUrl, opts = {}) {
if (!opts.fresh && authTokenMemo.has(resource)) {
return Promise.resolve(authTokenMemo.get(resource));
}
+ if (opts.signal && opts.signal.aborted) return Promise.resolve(null);
return new Promise((resolve) => {
+ let child = null;
+ let settled = false;
+ const stop = () => (opts.killTree || killProcessTree)(child);
+ const stopListening = () => { settled = true; if (opts.signal) opts.signal.removeEventListener('abort', stop); };
try {
- exec(
+ child = exec(
'az',
['account', 'get-access-token', '--resource', resource, '--query', 'accessToken', '-o', 'tsv'],
{ encoding: 'utf8', timeout: azTimeoutMs(), windowsHide: true },
(error, stdout) => {
+ stopListening();
if (error) {
+ if (opts.signal && opts.signal.aborted) { resolve(null); return; }
if (opts.fresh) authTokenMemo.delete(resource);
noteTokenFailure(resource, error);
resolve(null);
@@ -122,7 +184,9 @@ function getAuthTokenAsync(envUrl, opts = {}) {
resolve(token);
}
);
+ if (opts.signal && !settled) opts.signal.addEventListener('abort', stop, { once: true });
} catch (e) {
+ stopListening();
if (opts.fresh) authTokenMemo.delete(resource);
noteTokenFailure(resource, e);
resolve(null);
@@ -379,14 +443,19 @@ function makeRequest({ url, method = 'GET', headers = {}, body = null, includeHe
* @param {boolean} [opts.includeHeaders=false] - Include response headers in result
* @param {object} [opts.extraHeaders={}] - Extra request headers (e.g. Prefer)
* @param {number} [opts.timeout=60000]
+ * @param {boolean} [opts.refreshOn401=true] - On a 401, replace the token (`getAuthToken(.., { fresh: true })` is a
+ * SYNCHRONOUS Azure CLI call: seconds on a cold Windows process, with the whole event loop — every other probe's
+ * timers included — frozen) and send again. `false` hands the 401 back as it is, for a caller that is running
+ * other work alongside and will decide where to retry (check-auth's early WhoAmI).
* @returns {Promise<{status: number, data: any, headers?: object}>}
*/
async function dataverseRequest(envUrl, method, apiPath, body = null, opts = {}) {
- // The validated origin, never the caller's text, is what the token is requested for and sent to.
+ // The validated origin, never the caller's text, is what the token is requested for and sent to,
+ // and the path is checked against the Web API root before a token is even read.
const cleanUrl = requireDataverseOrigin(envUrl);
- const url = `${cleanUrl}/api/data/v9.2/${apiPath}`;
+ const url = webApiUrl(cleanUrl, apiPath);
const bodyStr = body == null ? null : typeof body === 'string' ? body : JSON.stringify(body);
- const { includeHeaders = false, extraHeaders = {}, timeout = 60000, token: presetToken = null } = opts;
+ const { includeHeaders = false, extraHeaders = {}, timeout = 60000, token: presetToken = null, refreshOn401 = true } = opts;
// Test seams, matching `preflightAuth`'s injection style. Without them the token-reuse behaviour
// below could only be exercised against a live Azure CLI and a real org.
const acquireToken = opts.getToken || getAuthToken;
@@ -428,7 +497,7 @@ async function dataverseRequest(envUrl, method, apiPath, body = null, opts = {})
throw new Error(`Request failed: ${res.error}`);
}
- if (res.statusCode === 401 && attempt < maxRetries) {
+ if (res.statusCode === 401 && refreshOn401 && attempt < maxRetries) {
token = acquireToken(cleanUrl, { fresh: true });
if (!token) throw new Error(tokenFailureMessage(cleanUrl, "Token refresh failed. Run 'az login' again."));
continue;
@@ -739,6 +808,17 @@ function readJsonArg(raw) {
return JSON.parse(raw);
}
+/**
+ * `JSON.stringify` with every character above U+007E written as a `\uXXXX` escape: the same document to any JSON
+ * parser, but bytes a console code page cannot garble. Windows PowerShell 5.1 decodes a child's stdout with the OEM
+ * code page, so a raw U+2014 em dash reaches the reader as "ΓÇö" (UTF-8 bytes E2 80 94 read as code page 437).
+ * Each UTF-16 unit is escaped on its own, which is how JSON writes a character outside the BMP too
+ * (https://www.rfc-editor.org/rfc/rfc8259#section-7: a surrogate pair of two escapes).
+ */
+function asciiJson(value) {
+ return JSON.stringify(value).replace(/[^\x00-\x7e]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
+}
+
/**
* Writes a result to stdout and exits.
* ok=true → JSON payload to stdout, exit 0
@@ -746,10 +826,13 @@ 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
+ * `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.)
*/
-function emitResult(ok, payload) {
+function emitResult(ok, payload, options = {}) {
+ const toJson = options && options.ascii ? asciiJson : JSON.stringify;
if (ok) {
- process.stdout.write(JSON.stringify(payload) + '\n');
+ process.stdout.write(toJson(payload) + '\n');
process.exit(0);
}
if (payload instanceof Error) {
@@ -757,7 +840,7 @@ function emitResult(ok, payload) {
} 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(JSON.stringify(payload) + '\n');
+ process.stdout.write(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.
@@ -781,6 +864,7 @@ function emitResult(ok, payload) {
module.exports = {
dataverseOrigin,
requireDataverseOrigin,
+ webApiUrl,
preflightAuth,
azIdentity,
getAuthToken,
diff --git a/plugins/model-apps/scripts/lib/deployed-baseline.js b/plugins/model-apps/scripts/lib/deployed-baseline.js
index bbf363b38..f76f0ea93 100644
--- a/plugins/model-apps/scripts/lib/deployed-baseline.js
+++ b/plugins/model-apps/scripts/lib/deployed-baseline.js
@@ -23,7 +23,7 @@
const fs = require('node:fs');
const path = require('node:path');
-const { annotateContentHashes } = require('./content-hash.js');
+const { annotateContentHashes, recordedContentSha } = require('./content-hash.js');
const { migrateAppSpec } = require('./app-spec.js');
const { writeFileAtomic } = require('./apply-snapshot-store.js');
const { resolveAppSource } = require('./app-source-path.js');
@@ -84,15 +84,43 @@ function deployedIdsFor(spec, { created, previous, fromSpec = false } = {}) {
return { dashboards, pages };
}
+/**
+ * `spec` annotated with the hash of each page's source, as the baseline records it. What a page's `__contentSha` says is "the source an apply SENT", and the build's Griffel check judges a
+ * later source against it (sdk-build.js griffelStanding), so it must not describe bytes the apply never looked at. When the apply measured its pages (`created.pageSourceShas`, the hash of
+ * the source the pages phase READ and checked before it sent the page) that hash is the record. Hashing the files here instead — as the build ENDS — records a page a maker saved while
+ * the build ran as applied, and the next build finds the edit "unchanged".
+ * A page the apply did not send (a changed-only run sends only the pages it selects) keeps the record it had (`previous`): what was last sent is still what is deployed, whatever the file
+ * says by now. With no record to keep it records the file as it is, as before — no record at all would be no stricter: the next build reads a missing record as `unrecorded` and goes on
+ * with a warning (sdk-build.js), where a source that differs from a recorded hash is held. Without `created.pageSourceShas` — a download, whose files ARE the deployed
+ * state, or any caller that measured nothing — every source is hashed as it is on disk.
+ */
+function annotateForBaseline(v2, appDir, { created, previous } = {}) {
+ const annotated = annotateContentHashes(v2, confinedReader(appDir));
+ const sent = created && created.pageSourceShas && typeof created.pageSourceShas === 'object' ? created.pageSourceShas : null;
+ if (!sent || !annotated || !Array.isArray(annotated.pages)) return annotated;
+ return {
+ ...annotated,
+ pages: annotated.pages.map((page) => {
+ // An intent page has no source on disk, so it carries no hash to replace.
+ if (!page || typeof page !== 'object' || !Object.prototype.hasOwnProperty.call(page, '__contentSha')) return page;
+ const key = page.key || page.name;
+ if (Object.prototype.hasOwnProperty.call(sent, key)) return { ...page, __contentSha: typeof sent[key] === 'string' && sent[key] ? sent[key] : null };
+ const earlier = recordedContentSha(previous, key);
+ return earlier === null ? page : { ...page, __contentSha: earlier };
+ }),
+ };
+}
+
/**
* Record `spec` as the state of `appUniqueName` in `environment` (a canonical origin, e.g.
* `https://contoso.crm.dynamics.com`), with the deployed ids `deployedIdsFor` finds from `created`,
- * `previous` and — for a download — `fromSpec`. Throws on a write error; callers treat it as non-fatal.
+ * `previous` and — for a download — `fromSpec`, and each page's source hash as `annotateForBaseline` finds
+ * it. Throws on a write error; callers treat it as non-fatal.
*/
function writeBaseline(workspaceDir, spec, { appDir, environment, appUniqueName, created, previous, fromSpec } = {}) {
const v2 = migrateAppSpec(spec);
const snapshot = {
- ...annotateContentHashes(v2, confinedReader(appDir)),
+ ...annotateForBaseline(v2, appDir, { created, previous }),
[ENVIRONMENT_KEY]: environment || null,
[APP_KEY]: appUniqueName || null,
[IDS_KEY]: deployedIdsFor(v2, { created, previous, fromSpec }),
diff --git a/plugins/model-apps/scripts/lib/entity-provision.js b/plugins/model-apps/scripts/lib/entity-provision.js
index 2c277c2bd..f29a2c09d 100644
--- a/plugins/model-apps/scripts/lib/entity-provision.js
+++ b/plugins/model-apps/scripts/lib/entity-provision.js
@@ -18,7 +18,13 @@ const {
isLocalizedLabelMap,
localizedLabelLcids,
sampleKeyIdentity,
+ lookupLabelFor,
+ lookupParentNeedsEnvironment,
+ isOldLookupColumnLabel,
+ askedPrimaryNameLength,
+ PRIMARY_NAME_MAX_LENGTH,
} = require('./app-spec.js');
+const { readColumnLabels, makeTableLabelReader, lookupKey } = require('./lookup-labels.js');
const { topoOrderEntities, entityByLogical } = require('./_graph.js');
// OData string-literal escaping for spec-controlled values interpolated into $filter (a solution
// uniquename / publisher prefix with a `'` would otherwise break the query or inject a clause).
@@ -273,6 +279,406 @@ function choiceOptions(col) {
return (col.options || []).map((label, i) => ({ value: 100000000 + i, label }));
}
+// What the table's create asks for as its primary name column's length when the spec gives none: 100 — what the previous release
+// always sent, for a plain and an auto-numbered name column alike. It is the SDK's own default for the option, sent explicitly here
+// so that a later change of that default cannot change what a spec without `primaryAttribute.maxLength` gets.
+//
+// What the platform makes of the length it is asked for depends on the environment. Measured on two, as the `MaxLength` of the
+// primary `StringAttributeMetadata` in the request that creates the table:
+// a create with only the primary name attribute, plain text one environment keeps the length asked (100 came back as 100);
+// another IGNORES it — 100 and 120 both came back as 850
+// characters (DatabaseLength 1700)
+// the same, with an auto-numbered primary the length asked is kept — 100 came back as 100 (200)
+// a create that also carries other columns the length asked is kept, even on the environment that ignores it
+// for a create with only the primary attribute — 120 came back as 120
+// more than 850 (in a create that carried other columns) refused, HTTP 400: "The maximum length of Primary attribute
+// 'new_name' is 4000. The maximum allowed limit is 850."
+// a PUT of the finished column (the SDK's updateColumn) honored — 850 -> 120 -> 850, each answered 204; the
+// DatabaseLength stays 1700
+// So the table is created exactly as the previous release created it — one request that carries ONLY the primary name attribute,
+// asking for 100 — which gives the previous release's result on every environment, whichever of the two behaviours it has; the
+// table's ordinary columns follow in a request of their own (createColumnsInOneRequest). A length the spec asks for is asked in that
+// same create; once the data-model phase has made its last labelled create, it is confirmed with one typed read and set with
+// updateColumn where the environment did not keep it (alignPrimaryNameLength, run last by provisionDataModel).
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/create-update-entity-definitions-using-web-api#create-table-definitions
+const DEFAULT_PRIMARY_NAME_LENGTH = 100;
+
+// What the table's create asks for as the primary name column's length: the spec's `primaryAttribute.maxLength`, else the default
+// above. Applied when the table is CREATED (an existing table's column is never rewritten).
+function primaryNameLength(primaryAttribute) {
+ const asked = askedPrimaryNameLength({ primaryAttribute });
+ return asked !== undefined ? asked : DEFAULT_PRIMARY_NAME_LENGTH;
+}
+
+// The MaxLength of one text column, from ONE typed request: MaxLength is a member of StringAttributeMetadata, so the attribute
+// is addressed through that cast and nothing else is selected — no labels, the kind of narrow read the build keeps ahead of
+// its labelled writes (findExistingColumns). Dataverse answers
+// { "@odata.context": "...", "MaxLength": 850, "MetadataId": "..." }
+// The attribute of a table created a moment ago can trail the table (the lag confirmInlineColumns also waits out), so a 404 is
+// asked again, twice; any other answer will not change by asking again. Throws, with the reason, when the length cannot be read.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query-metadata-web-api#retrieve-attributes
+async function readTextColumnLength(provision, tableLogical, columnLogical, { sleep } = {}) {
+ const raw = provision && provision.dataverse;
+ if (!raw || typeof raw.get !== 'function') throw new Error('there is no Dataverse client to read the column with');
+ const wait = typeof sleep === 'function' ? sleep : ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
+ const url = `/EntityDefinitions(LogicalName='${odataLit(tableLogical)}')/Attributes(LogicalName='${odataLit(columnLogical)}')/Microsoft.Dynamics.CRM.StringAttributeMetadata?$select=MaxLength`;
+ let why = 'no answer';
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ if (attempt > 0) await wait(1000);
+ const res = await raw.get(url);
+ if (res && res.status >= 200 && res.status < 300) {
+ if (res.body && Number.isInteger(res.body.MaxLength)) return res.body.MaxLength;
+ throw new Error('the answer to the read of the column\'s length carries no MaxLength');
+ }
+ const detail = res && res.body && res.body.error && res.body.error.message;
+ why = `HTTP ${res && res.status}${detail ? `: ${detail}` : ''}`;
+ if (!res || res.status !== 404) break;
+ }
+ throw new Error(`could not read the column's length (${why})`);
+}
+
+// Sets the primary name column of a table THIS build created to the length the spec asks for. The table is created with a
+// request that carries nothing but that column, and some environments ignore the length asked of a plain text name column in
+// such a request (see DEFAULT_PRIMARY_NAME_LENGTH), so the length is read back — one typed request — and only a column that is not
+// already the asked length is updated, with the SDK's updateColumn (the documented PUT of the typed column). Exactly one narrated
+// step, a skip when nothing needed changing (an environment that keeps the length asked). A read or an update that fails is a
+// FAILED step that names the table, the length asked and the length the platform made, plus a warning, the way a failed column
+// update is reported elsewhere in this file: the build goes on, and the column is never left at the wrong length without saying so.
+//
+// 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
+// WITH its labels, and a label-bearing metadata read ahead of a labelled create is what makes Dataverse keep only the base-language
+// label of what is created (measured live — see findExistingColumns, which is why the reads that precede a create in this file are
+// narrow). That read is inside the SDK and cannot be narrowed, so it goes where nothing labelled is created after it — within one
+// attempt. The build runs a phase that halts on a transient answer (a 429, a lock) again (build-model-app.js): the attempt that
+// created the table has set its length by then, because this runs after a halt too, and the retry finds the table and keeps its
+// name column as it finds it, so the length is set once. What the retry creates — a column or a relationship the halt kept the
+// first attempt from — comes after that attempt's read; the loss was measured only for a create straight after the read, so whether
+// it reaches across the pause between two attempts is not known.
+//
+// `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).
+async function alignPrimaryNameLength({ runner, sdk, provision, entity, logical, asked, warn, sleep, halted = false }) {
+ const primaryLogical = String(entity.primaryAttribute.schemaName).toLowerCase();
+ const label = `primary column length ${entity.schemaName}.${entity.primaryAttribute.schemaName}`;
+ let actual;
+ let unread;
+ try { actual = await readTextColumnLength(provision, logical, primaryLogical, { sleep }); } catch (err) { unread = err; }
+ if (!unread && actual === asked) {
+ runner.skip('data-model', `${label} (already ${asked})`);
+ return;
+ }
+ 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'
+ : 'the rest of the build continues';
+ await runBestEffort(
+ runner,
+ 'data-model',
+ `${label} -> ${asked}`,
+ async () => {
+ if (unread) throw new Error(`asked ${asked}, the length the platform made is unknown: ${(unread && unread.message) || unread}`);
+ try {
+ await sdk.updateColumn(logical, primaryLogical, { maxLength: asked });
+ } catch (err) {
+ throw new Error(`asked ${asked}, the platform made ${actual}: ${(err && err.message) || err}`, { cause: err });
+ }
+ },
+ 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}`
+ );
+}
+
+// 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
+// else created the table first. Nothing shows that THIS build made it, so its column is never written — but the length the spec
+// asks for is compared with the one the table has, from one typed read, and a difference is said out loud instead of passing as a
+// bare skip. (Some environments make a plain text name column created with only that column 850 characters long whatever length
+// was asked, see DEFAULT_PRIMARY_NAME_LENGTH, which is the likely cause.) A read that fails is said too. One narrated step, always
+// a skip, and never a failure of the build: it changes nothing.
+async function reportFoundPrimaryNameLength({ runner, provision, entity, logical, asked, warn, sleep }) {
+ const primaryLogical = String(entity.primaryAttribute.schemaName).toLowerCase();
+ const label = `primary column length ${entity.schemaName}.${entity.primaryAttribute.schemaName}`;
+ const found = 'table found after its create — kept';
+ const why = 'the answer to that create was lost or another maker created the table first, so nothing shows that this build made it and its name column is left alone';
+ let actual;
+ try {
+ actual = await readTextColumnLength(provision, logical, primaryLogical, { sleep });
+ } catch (err) {
+ runner.skip('data-model', `${label} (${found}; its length could not be read)`);
+ if (typeof warn === 'function') warn(`could not read the length of the primary name column ${logical}.${primaryLogical} (${(err && err.message) || err}), so the ${asked} the spec asks for is not confirmed — the table was found after its create, and ${why}`);
+ return;
+ }
+ if (actual === asked) {
+ runner.skip('data-model', `${label} (already ${asked})`);
+ return;
+ }
+ runner.skip('data-model', `${label} (${found} at ${actual}, asked ${asked})`);
+ if (typeof warn === 'function') warn(`the primary name column ${logical}.${primaryLogical} is ${actual} characters long, not the ${asked} the spec asks for — the table was found after its create, and ${why}. Change the column in Maker if the length matters`);
+}
+
+// The ordinary columns of a NEW table are created together, in ONE atomic change set, right after the table — instead of one
+// request per column. A change set is an OData `$batch` whose operations are all POSTs to the table's `Attributes` collection (the
+// vendored SDK's createColumns): Dataverse runs them in the order given, and if any operation fails it rolls back the ones already
+// done, so a refused request has created nothing and the build can take the one-request-per-column path it always had. A batch may
+// hold up to 1,000 requests.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/execute-batch-operations-using-web-api#change-sets
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/execute-batch-operations-using-web-api#handling-errors
+//
+// Why a request of its own and not the table's create request, which Dataverse also accepts — columns may be posted in the
+// `Attributes` array beside the primary name attribute
+// (https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/create-update-column-definitions-using-web-api#create-columns)?
+// Because a table create that carries columns is not a request the previous release ever sent, and what the platform makes of it is
+// not what it makes of the previous release's: an environment that ignores the length asked of a primary name column created alone
+// keeps it when the same create also carries other columns (DEFAULT_PRIMARY_NAME_LENGTH), so no one length asked of such a create
+// gives the previous release's result on every environment. The table is created exactly as before; only these columns are new.
+// Each operation's body is the SAME body createColumn posts — the SDK builds both with one function — and the
+// table-columns-in-create test compares them column by column, so a column comes out as it always did.
+//
+// Only a column whose whole definition is ONE such body qualifies. Left to the per-column path, as they have always been, because
+// each needs something a request of its own provides:
+// Customer a lookup plus two relationships, made by their own action — not an `Attributes` POST at all
+// File, Image each makes companion columns of its own (see inlineColumnsOf), and an Image column is checked against
+// the table's one-primary-image rule
+// Calculated, Rollup a formula may name a column that has not been created yet, so they are made in spec order
+// a choice bound to a global option set the binding refers to a separate record, not to the body
+// A type is in this set only while the platform is not known to create anything beside it that COLUMN_COMPANIONS does not list:
+// Text, Memo, the number types, DateTime and AutoNumber have no companion column at all, and the rest are listed there. (The order
+// rules in inlineColumnsOf do not rely on that list being complete.)
+const INLINE_COLUMN_TYPES = new Set(['Text', 'Memo', 'Integer', 'BigInt', 'Decimal', 'Double', 'Money', 'DateTime', 'Boolean', 'Choice', 'MultiChoice', 'AutoNumber']);
+// At most this many columns go in one change set, so the request — and the one-request-per-column fallback a refusal costs — stays
+// bounded however large a table is; the rest take the per-column path. (The platform allows 1,000 operations in a batch; this is the
+// build's own bound.)
+const INLINE_COLUMN_LIMIT = 25;
+
+// What the platform creates beside a column of the change set, as the suffixes of the column's own name: a Money column's
+// base-currency twin, and the `<name>name` shadow of a Choice, a MultiChoice or a Boolean column. Each companion is a column of its
+// own on the table, marked `AttributeOf` the column it extends. A column of one of these names IN the change set would make the
+// platform refuse the whole of it (see inlineColumnsOf), so the build keeps such a name out up front. A Map, because its key is
+// the spec's column type: an object would answer `constructor` for a spec that says so.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/attributemetadata ("AttributeOf: The name of the attribute that this attribute extends.")
+const COLUMN_COMPANIONS = new Map([
+ ['Money', ['_base']],
+ ['Choice', ['name']],
+ ['MultiChoice', ['name']],
+ ['Boolean', ['name']],
+]);
+
+// Whether a column can be created in the change set at all (INLINE_COLUMN_TYPES, and none of the exceptions listed there).
+const isOrdinaryColumn = (c) => INLINE_COLUMN_TYPES.has(c.type || 'Text') && c.source !== 'Calculated' && c.source !== 'Rollup' && !c.globalChoice;
+
+// The ordinary columns of a NEW table that go in the change set, in spec order.
+//
+// A change set that creates an attribute twice is refused as a whole by the platform — error 0x80060304,
+// "Attribute {0} already exists for entity {1}." — where the one-by-one path meets the same collision in ONE column's
+// own request and skips it. So a column stays out of the change set, and takes that path, when its name is one the
+// platform creates itself or an earlier column already has. Names compare without regard to case, because Dataverse
+// lower-cases logical names:
+// the primary name column the table already has it
+// `<table>id` the table's own primary key
+// a companion a name COLUMN_COMPANIONS lists for a column of the table — for EVERY such column, even one that
+// is past the limit or takes the per-column path (a choice bound to a global option set, a
+// Calculated Money column). Money: `<name>_base`, the hidden twin holding its value in the base
+// currency (download emits that twin as a column of its own when it could not read the Money
+// column). Choice, MultiChoice, Boolean: `<name>name`.
+// a repeat of an earlier name in any case spelling — whatever type the earlier column is, because in spec order it
+// would have created the name first
+// a name that EXTENDS the name of a column made by its own request see below
+// and a column stays out when an EARLIER column has a name that extends its own — the last rule below.
+//
+// The extends rule cannot be a list. A column that takes the per-column path — Customer, File, Image, a Calculated or Rollup column,
+// a choice bound to a global option set — is made AFTER the change set, and the platform makes its companions at that moment,
+// each named after it: `<name>name`, `<name>yominame` and `<name>idtype` beside a Customer column (measured on a polymorphic lookup:
+// each is a stored column marked `AttributeOf` the lookup), `<name>_name` beside a File column, `<name>id`, `<name>_timestamp` and
+// `<name>_url` beside an Image column, `<name>_date` and `<name>_state` beside a rollup column. A column of such a name inside the
+// change set would be made BEFORE its owner, and the owner's own create would then meet it: refused with "already exists",
+// which the build reads as a skip — the owner would vanish from the table without a word, where one by one the owner is made
+// first and the twin is the skip. The build does not claim to know everything the platform makes beside a column, so a column
+// whose name extends such an owner's stays out and is made in spec order, as it always was; for a column that merely happens to
+// start like its neighbour's name (`new_file` and `new_filename`) that costs one request. A column past the limit, or kept out by
+// another rule, is not an owner in this sense: its type has no companion that COLUMN_COMPANIONS does not list.
+//
+// The last rule is the mirror of those two, for the columns that go in the change set themselves. One by one, in spec order, the
+// first column to name something creates it and the next is skipped as already existing — so when a twin is listed BEFORE the column
+// that creates its name as a companion, the twin is the one that is kept and the OWNER is skipped. The change set runs before every
+// per-column create, so an owner in it would be made first and the twin skipped instead: the other column of the pair would vanish
+// from the table, without a word. So a column stays out of the change set when an earlier column of the table has a name that
+// EXTENDS its own — every name creating a column can take is named after it, the ones COLUMN_COMPANIONS lists (a Choice,
+// MultiChoice, Boolean or Money column's) and the ones the platform may make that the build does not know — and is made after that
+// column, in spec order. For a twin listed AFTER its owner nothing changes: the owner goes first either way, and the twin stays out
+// by the rules above. A column kept out for this is made by its own request like any other owner, so a LATER column whose name
+// extends its own stays out too; an earlier one is created before it either way and need not. Where an earlier column merely starts
+// like a later one's name, that costs one request.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/web-service-error-codes
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/attributemetadata
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/file-column-data#file-name-column
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/image-column-data#download-url
+// See: https://learn.microsoft.com/en-us/power-apps/maker/data-platform/define-rollup-fields
+function inlineColumnsOf(buildable, { primaryName, tableLogical }) {
+ const names = buildable.map((c) => c.schemaName.toLowerCase());
+ const taken = new Set([String(primaryName || '').toLowerCase(), `${tableLogical}id`]);
+ // The names of the columns made by their own request, each with the position after which a name that extends it stays out: any
+ // position (-1) for a column that cannot go in the change set at all, only a later one for a column kept out by the last rule.
+ const ownRequest = [];
+ const lateOwners = new Set();
+ buildable.forEach((c, i) => {
+ const name = names[i];
+ for (const suffix of COLUMN_COMPANIONS.get(c.type) || []) taken.add(`${name}${suffix}`);
+ if (!isOrdinaryColumn(c)) {
+ ownRequest.push({ name, after: -1 });
+ return;
+ }
+ // Every name a column's creation can take — a companion listed for it, or one the build does not know — is named after the column,
+ // so one test covers them all: an earlier column whose name extends this one's.
+ if (names.slice(0, i).some((earlier) => earlier.length > name.length && earlier.startsWith(name))) {
+ lateOwners.add(c);
+ ownRequest.push({ name, after: i });
+ }
+ });
+ const seen = new Set();
+ const inline = [];
+ buildable.forEach((c, i) => {
+ const name = names[i];
+ const repeat = seen.has(name);
+ seen.add(name);
+ const extendsOwner = ownRequest.some((owner) => i > owner.after && name.length > owner.name.length && name.startsWith(owner.name));
+ if (!repeat && !taken.has(name) && !extendsOwner && !lateOwners.has(c) && isOrdinaryColumn(c) && inline.length < INLINE_COLUMN_LIMIT) inline.push(c);
+ });
+ return inline;
+}
+
+// Creates the table with the primary name attribute and nothing else — the request the previous release sent. Its ordinary columns
+// follow in a change set of their own (createColumnsInOneRequest).
+//
+// TABLE_METADATA_NOT_VISIBLE is the SDK's own statement that the table WAS created and must not be created again, so it is the
+// caller's. A length the spec asked for is reported as unconfirmed before the build stops (`askedLength`): some environments make
+// a plain text name column created this way 850 characters long whatever length is asked (DEFAULT_PRIMARY_NAME_LENGTH), and the
+// re-run that follows leaves an existing table's name column as it is. Nothing is said for an auto-numbered name column, which
+// keeps the length asked, or for the longest length there is (850), which the column comes out as either way.
+async function createNewTable(sdk, createOpts, { warn, askedLength } = {}) {
+ try {
+ return await sdk.createTable(createOpts);
+ } catch (err) {
+ if (err && err.code === 'TABLE_METADATA_NOT_VISIBLE' && askedLength !== undefined && askedLength !== PRIMARY_NAME_MAX_LENGTH
+ && !createOpts.primaryColumnAutoNumberFormat && typeof warn === 'function') {
+ warn(`table ${createOpts.schemaName} was created, but its metadata could not be read back yet, so the build stops here — the spec asks for a primary name column length of ${askedLength}, which may not have been applied (some environments make a name column created this way ${PRIMARY_NAME_MAX_LENGTH} characters long), and a re-run leaves an existing table's name column as it is: after the re-run, check ${String(createOpts.primaryColumnSchemaName).toLowerCase()} in Maker and set its length there if it matters`);
+ }
+ throw err;
+ }
+}
+
+// One line saying why a request failed. When the platform answers a `$batch` with its multipart envelope, the SDK's error carries
+// that whole answer as its message, e.g. (line breaks shown as \r\n)
+// HTTP 400 from https://contoso.crm.dynamics.com/api/data/v9.2/$batch: --batchresponse_1\r\nContent-Type: multipart/mixed; boundary=changesetresponse_1\r\n\r\n--changesetresponse_1\r\nContent-Type: application/http\r\nContent-ID: 3\r\n\r\nHTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\n\r\n{"error":{"code":"0x80060304","message":"Attribute createdon already exists for entity new_ticket."}}\r\n--changesetresponse_1--\r\n--batchresponse_1--
+// so the platform's own message is taken out of it when there is one (with the status that opens the SDK's), and anything else
+// is cut to a line.
+function briefReason(err) {
+ const text = String((err && err.message) || err);
+ const status = /^HTTP (\d{3})\b/.exec(text);
+ const platform = /"message"\s*:\s*("(?:[^"\\]|\\.)*")/.exec(text);
+ let reason = text;
+ if (platform) {
+ try { reason = `${status ? `HTTP ${status[1]}: ` : ''}${JSON.parse(platform[1])}`; } catch { /* keep the whole text */ }
+ }
+ reason = reason.replace(/\s+/g, ' ').trim();
+ return reason.length > 300 ? `${reason.slice(0, 297)}...` : reason;
+}
+
+// Whether an error from the change set leaves what it did UNKNOWN, rather than saying it was refused: the answer never arrived (a
+// transport failure, which the SDK reports as a ConnectionError with status 0), was a server error, or could not be read although the
+// platform answered with a success status ("cannot be confirmed"). A change set can commit behind each of those. A 4xx is a refusal —
+// nothing was created — and so is anything the SDK raises before it sends (an error that is not a ConnectionError).
+function outcomeUnknown(err) {
+ if (!err || err.code !== 'CONNECTION_ERROR') return false;
+ const status = err.statusCode;
+ return !status || status >= 500 || (status >= 200 && status < 300);
+}
+
+// Creates a new table's ordinary columns in ONE atomic change set (the SDK's createColumns) and answers the ones the table is then
+// confirmed to have (confirmInlineColumns). `table` is `{ metadataId, logicalName }` as the SDK answered the create of the table.
+//
+// The change set is all or nothing, so an error means the request was refused and no column was created — and the build goes on the
+// way it always did, one request per column, with `warn` saying why. The SDK itself refuses a transport that cannot send the body of
+// a change set verbatim (HttpClient.postRaw, which DataverseClient.supportsAtomicBatch reports; lib/sdk-http-client.js has it),
+// before anything is sent: one more refusal of the same kind. An error is not always a refusal — a request whose answer was lost or
+// could not be read may have created the columns after all (outcomeUnknown) — so the table is read before anything is assumed: when
+// it has every column the change set committed, and each column is answered as it would have been had the answer arrived, with its
+// id. A table that lacks any of them is treated as a refusal, and the one-by-one path covers every other case: a column that is
+// already there answers "already exists" and is skipped, so a lost answer costs requests, never a column or a duplicate.
+// The HTTP client sends this change set again only when the answer is a 429 — the platform refused it, so nothing in it committed (the
+// change set is atomic)
+// (isColumnCreateBatch, lib/sdk-http-client.js) — on the schedule of any other throttled write, honouring `Retry-After`: the table
+// was created a moment ago, and its customization lock can still be held, which one column's own POST rides out the same way. It
+// 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 }) {
+ 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 (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).
+ const found = await confirmInlineColumns(provision, table, columns, { sleep, attempts: 1 });
+ if (found.size === columns.length) {
+ if (typeof warn === 'function') warn(`the answer to the request that creates the ${columns.length} ordinary column(s) of table ${tableSchemaName} was lost or could not be read (${briefReason(err)}), but the table has every one of them`);
+ return found;
+ }
+ }
+ if (typeof warn === 'function') {
+ // A ConnectionError carries `.statusCode`; any other error may wrap one as its `cause`.
+ const status = err && (err.statusCode || err.status || (err.cause && (err.cause.statusCode || err.cause.status)));
+ warn(status === 429
+ ? `table ${tableSchemaName} was throttled (${briefReason(err)}), so its ${columns.length} ordinary column(s) are created one by one instead of in one request`
+ : `could not create the ${columns.length} ordinary column(s) of table ${tableSchemaName} in one request (${briefReason(err)}) — creating them one by one`);
+ }
+ return new Map();
+ }
+ return confirmInlineColumns(provision, table, columns, { warn, sleep });
+}
+
+// Which of a new table's columns that went in the change set the table really has, with the MetadataId each createColumn answer
+// would have carried (a change set answers none), from ONE read of the table's `Attributes`, keyed by the column object — never
+// by its name, because two columns of a spec can share one and only the one that went in the request was created by it. `table` is
+// `{ metadataId, logicalName }`: a created table is read by its id, or by its logical name when the SDK's answer carries no id.
+// Only ids and names are selected — no labels, the kind of narrow read that already precedes labelled creates in this file
+// (findExistingColumns) because a label-bearing metadata read is what strips non-base languages.
+//
+// Nothing is assumed: a column this read does not show — it failed, or the answer lags the create, or the platform
+// ignored a posted column — is left out of the result and made by the column loop the per-column way, where an
+// "already exists" answer is a skip. So a lagging read costs requests, never a missing column. Never throws.
+// A short answer is read again, up to `attempts` times (3 unless told otherwise, 1 second apart).
+async function confirmInlineColumns(provision, table, columns, { warn, sleep, attempts = 3 } = {}) {
+ const confirmed = new Map();
+ const raw = provision && provision.dataverse;
+ const byId = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(String(table && table.metadataId));
+ if (!columns.length || !raw || typeof raw.get !== 'function' || (!byId && !(table && table.logicalName))) return confirmed;
+ const tableKey = byId ? `(${table.metadataId})` : `(LogicalName='${odataLit(table.logicalName)}')`;
+ const wait = typeof sleep === 'function' ? sleep : ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
+ const idByLogical = new Map();
+ // The table is readable as soon as it exists; its attribute collection can trail it by a moment
+ // (the metadata-read lag the relationship create also waits out), so a short answer is read again.
+ for (let attempt = 0; attempt < attempts && columns.some((c) => !idByLogical.has(c.schemaName.toLowerCase())); attempt += 1) {
+ if (attempt > 0) await wait(1000);
+ try {
+ const res = await raw.get(`/EntityDefinitions${tableKey}/Attributes?$select=MetadataId,LogicalName`);
+ if (res && res.status >= 200 && res.status < 300 && res.body && Array.isArray(res.body.value)) {
+ for (const a of res.body.value) {
+ if (a && a.LogicalName && a.MetadataId) idByLogical.set(String(a.LogicalName).toLowerCase(), String(a.MetadataId));
+ }
+ }
+ } catch { /* read again, then fall back to the per-column path */ }
+ }
+ for (const c of columns) {
+ const logicalName = c.schemaName.toLowerCase();
+ if (idByLogical.has(logicalName)) confirmed.set(c, { logicalName, metadataId: idByLogical.get(logicalName) });
+ }
+ if (confirmed.size < columns.length && typeof warn === 'function') {
+ warn(`${columns.length} column(s) were created in one request, but ${confirmed.size} could be read back — creating the other ${columns.length - confirmed.size} one by one`);
+ }
+ return confirmed;
+}
+
const STATE_CODE = { Active: 0, Inactive: 1 };
class BuildHalt extends Error {
@@ -546,18 +952,27 @@ async function runBestEffort(runner, phase, label, fn, warn, warning) {
// found no row yet and created the same view a second time under a new id, which the next fetch
// then refused as an ambiguous match. Only the first error is rethrown; a later in-flight failure is
// the same phase failing again and adds nothing the first did not already report.
-async function mapLimit(items, limit, fn) {
+//
+// `firstInOrder` picks WHICH failure is reported when several in-flight items fail: the one of the
+// lowest-indexed item rather than the first to settle. Items start in index order, so every item below
+// a failed one has already started, and once they have drained the reported error is the one a
+// sequential loop over the same items would have met first — independent of response timing. Read-only
+// fan-outs whose report must not depend on which request answered first (verify, download) opt in; the
+// build's write fan-outs keep the first failure in time, which is the one that stopped the phase.
+async function mapLimit(items, limit, fn, { firstInOrder = false } = {}) {
const out = new Array(items.length);
let i = 0;
let failed = false;
let firstError;
+ let firstErrorIndex = -1;
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
while (!failed && i < items.length) {
const idx = i++;
try {
out[idx] = await fn(items[idx], idx);
} catch (err) {
- if (!failed) { failed = true; firstError = err; }
+ if (!failed) { failed = true; firstError = err; firstErrorIndex = idx; }
+ else if (firstInOrder && idx < firstErrorIndex) { firstError = err; firstErrorIndex = idx; }
return;
}
}
@@ -656,6 +1071,11 @@ function operatorRemedy(err) {
// every caller that reacts to a failed push decides "failed" exactly as the halt does.
function pushFailed(result) {
if (!result) return false;
+ // `createRecovery: 'adoptExact'` (build-model-app.js): a create whose answer was lost had already
+ // committed, and the SDK proved the row is exactly what this push would have written, so it adopted it
+ // locally. It says `saved: false` because THIS attempt wrote nothing — but nothing failed. Only the
+ // boolean the SDK sets, and only with no error beside it.
+ if (result.adoptedExisting === true && !result.error) return false;
const committed = result.saved !== undefined ? result.saved : result.success;
return committed === false || (committed === undefined && Boolean(result.error));
}
@@ -740,6 +1160,11 @@ function reportPartialPush(result, what, warn) {
if (!result || typeof warn !== 'function') return result;
const label = what || result.type || 'artifact';
const st = result.publish;
+ // An adoption writes nothing, so there is nothing to confirm — but a build that quietly took over a row it
+ // did not create this attempt would leave the operator unable to tell why the create was never logged.
+ if (result.adoptedExisting === true) {
+ warn(`${label} was already created by an earlier attempt whose answer was lost, and the row is exactly what this build would have written, so it was adopted — nothing was written again`);
+ }
if (st && st.kind === 'failed') {
warn(`publish ${label} FAILED: ${(st.error && st.error.message) || 'unknown error'} — the change is SAVED but the runtime still serves the previously published copy; the build is idempotent, so re-run it once the cause is cleared`);
} else if (st && st.kind === 'unverifiable') {
@@ -863,8 +1288,41 @@ async function findExistingTable(provision, schemaName, { hasLocalizedLabels = f
return (hits || []).find((t) => t.logicalName === logical) || null;
}
-async function provisionDataModel({ sdk, provision, runner, spec, apply, languageCode, warn, provisionedLanguages, preResolvedLanguageCode, sleep }) {
- const result = { entities: {}, globalChoiceIds: {}, statusReasonValues: {}, columns: {}, relationships: [] };
+// The data-model phase (provisionDataModelSteps) and then — whatever the steps did, a halt included — the one step that has to come
+// after every labelled create of it: setting the primary name column's length of each table THIS run created whose spec asks for
+// one (alignPrimaryNameLength).
+//
+// Last, because that step's read carries labels, and nothing labelled may be created after a read like that (see
+// alignPrimaryNameLength).
+//
+// In a `finally`, because the length is set only for a table this run created: a re-run finds the table and leaves an existing
+// table's name column as it is (a rebuild must not shorten a column that may hold data), so a table created by a run that then
+// halted — a relationship refused, a column rejected, a lock that outlasted the retries — would keep the length the environment made
+// of the create for good. A table this run did not create, or found after a create whose answer was lost, is never queued
+// (provisionDataModelSteps). alignPrimaryNameLength does not throw — a step that cannot set the length is a failed, warned step — so
+// it cannot replace the error that stopped the phase.
+async function provisionDataModel(args) {
+ const createdWithLength = [];
+ let halted = false;
+ try {
+ return await provisionDataModelSteps(args, createdWithLength);
+ } catch (err) {
+ halted = true;
+ throw err;
+ } finally {
+ for (const { entity, logical, asked } of createdWithLength) {
+ await alignPrimaryNameLength({ runner: args.runner, sdk: args.sdk, provision: args.provision, entity, logical, asked, warn: args.warn, sleep: args.sleep, halted });
+ }
+ }
+}
+
+// `createdWithLength` collects `{ entity, logical, asked }` for each table this run creates whose spec asks for a primary name
+// column length, in creation order, for provisionDataModel to set once the phase is done.
+async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, languageCode, warn, provisionedLanguages, preResolvedLanguageCode, sleep, reconcileLookupLabels = false, inlineColumns = true }, createdWithLength) {
+ // `lookupLabels` records the label each spec lookup column carries once this phase is done
+ // (`<referencing>|<lookup logical>` -> { label }), so a later phase that repairs something derived
+ // from it — an existing form's cell label — repairs it to what the column now says.
+ const result = { entities: {}, globalChoiceIds: {}, statusReasonValues: {}, columns: {}, relationships: [], lookupLabels: {} };
// The CLI resolves the authoring LCID BEFORE constructing the SDK, because
// `MakerSdkOptions.languageCode` is a construction-time option (#455) — the App/Form/Dashboard
// adapters bake it in. Re-resolving here would repeat the org read and the provisioned-languages
@@ -881,6 +1339,10 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag
const globalChoiceIds = result.globalChoiceIds;
const statusReasonValues = result.statusReasonValues;
+ // The declared tables (lower-case logical names) this run found already in the environment, as opposed
+ // to the ones it created. A lookup to one that sets no displayName of its own is named by the
+ // environment (lookupParentNeedsEnvironment), which only the table loop below can know.
+ const reusedTables = new Set();
// 2a. Global option sets (shared choices) — built before columns that bind to them. The SDK's
// createGlobalOptionSet is now IDEMPOTENT: it probes by Name and REUSES an existing set (returning
@@ -905,10 +1367,31 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag
const entityIsLocalized = localizedLabelLcidsInSpec({ entities: [e] }).length > 0;
const hits = await findExistingTable(provision, e.schemaName, { hasLocalizedLabels: entityIsLocalized });
const existingTable = hits;
+ // Every buildable column: all scalar types + Customer (a Lookup comes from a relationship).
+ const buildable = (e.columns || []).filter((c) => SDK_COLUMN_TYPE[c.type || 'Text'] || c.type === 'Customer');
+ // The new table's ordinary columns are created together, in ONE change set right after the table, when the SDK has
+ // `createColumns` and a read can confirm them afterwards (createColumnsInOneRequest). `inlineColumns: false` is the
+ // one-request-per-column path, which is also the oracle the table-columns-in-create tests compare to.
+ const inlineEnabled = inlineColumns !== false && !!sdk && typeof sdk.createColumns === 'function'
+ && !!provision && !!provision.dataverse && typeof provision.dataverse.get === 'function';
+ // Which of the columns that went in the change set the table was then confirmed to have, keyed by the column object (never
+ // by its name: two columns of a spec can share one, and only the one that went in the request was created by it), each with
+ // the id createColumn would have returned.
+ let inlineConfirmed = new Map();
let existingCols = new Set();
let existingColRows = [];
+ // The spec's primary name column length is asked in the table's own create. For a table THIS build creates (`createdTable`) it
+ // is then read back and set where the environment did not keep it — at the end of the phase, once nothing labelled is left to
+ // create (provisionDataModel, alignPrimaryNameLength). It is never WRITTEN for a table the build did not create: an existing
+ // table's column is left as it is, and so is one found after a create whose answer was lost, where nothing shows that this
+ // build, and not someone else, made it — but the length of that one is read, and a difference from the spec's is reported
+ // (reportFoundPrimaryNameLength).
+ let createdTable = null;
+ let foundAfterCreate = false;
+ const askedLength = askedPrimaryNameLength(e);
if (existingTable) {
runner.skip('data-model', `table ${e.schemaName} (exists — reuse)`);
+ reusedTables.add(logical);
result.entities[e.schemaName] = { logicalName: logical, entitySetName: existingTable.entitySetName };
existingColRows = await findExistingColumns(provision, logical, warn);
existingCols = new Set(existingColRows.map((c) => String(c.logicalName || c.schemaName || '').toLowerCase()));
@@ -934,15 +1417,19 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag
? e.displayName
: (labelText(e.displayName, resolvedLanguageCode) || e.schemaName);
const createOpts = { schemaName: e.schemaName, displayName: tableDisplayName, pluralName: e.pluralName || `${labelText(tableDisplayName, resolvedLanguageCode) || e.schemaName}s`,
- primaryColumnSchemaName: e.primaryAttribute.schemaName, primaryColumnDisplayName: e.primaryAttribute.displayName || 'Name', hasNotes: e.hasNotes === true, languageCode: 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.
+ primaryColumnMaxLength: primaryNameLength(e.primaryAttribute) };
// AutoNumber the primary/title column when requested (the order number IS the identity).
if (e.primaryAttribute.autoNumberFormat) createOpts.primaryColumnAutoNumberFormat = e.primaryAttribute.autoNumberFormat;
// Same reasoning as columns: set the description at CREATE time, and omit it when absent so
// a rebuild never blanks a description someone added in the maker.
if (e.description) createOpts.description = String(e.description);
try {
- const t = await sdk.createTable(createOpts);
+ const t = await createNewTable(sdk, createOpts, { warn, askedLength });
result.entities[e.schemaName] = { logicalName: (t.logicalName || logical), entitySetName: t.entitySetName, metadataId: t.metadataId };
+ createdTable = t;
} catch (err) {
if (!isAlreadyExists(err)) throw err;
// First POST likely succeeded server-side; a transient-network retry hit "already exists".
@@ -951,9 +1438,19 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag
const found = await findExistingTable(provision, e.schemaName);
if (!found) throw err;
result.entities[e.schemaName] = { logicalName: logical, entitySetName: found.entitySetName };
+ foundAfterCreate = true;
}
}, { recoverable: true });
}
+ // The primary name column's length, when the spec asks for one: one narrated step in every case (the plan counts it). For a
+ // table this build created the step is queued here and runs at the end of the phase (provisionDataModel) — a label-bearing
+ // read must not come before a labelled create. For a table found after its create the length is read and compared here, and
+ // for a table that existed before the step is a skip.
+ if (askedLength !== undefined) {
+ if (createdTable) createdWithLength.push({ entity: e, logical, asked: askedLength });
+ else if (foundAfterCreate) await reportFoundPrimaryNameLength({ runner, provision, entity: e, logical, asked: askedLength, warn, sleep });
+ else runner.skip('data-model', `primary column length ${e.schemaName}.${e.primaryAttribute.schemaName} (table exists — kept)`);
+ }
// Enable "Allow quick create" on the table when the spec opts in (explicit `entities[].quickCreate`
// OR an authored `formType: 'QuickCreate'` form — see quickCreateEnabledFor). Runs for BOTH a fresh
// and an existing table and is idempotent: `IsQuickCreateEnabled` is a plain Edm.Boolean flag, so
@@ -965,13 +1462,30 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag
await sdk.updateTable(logical, { quickCreateEnabled: true });
});
}
+ // A table THIS build created gets its ordinary columns in one change set (createColumnsInOneRequest). A table found after its
+ // create is not given one: nothing shows what it already holds, and the per-column path below skips what exists.
+ if (createdTable && inlineEnabled) {
+ const inlineSet = inlineColumnsOf(buildable, { primaryName: e.primaryAttribute && e.primaryAttribute.schemaName, tableLogical: logical });
+ if (inlineSet.length) {
+ inlineConfirmed = await createColumnsInOneRequest({
+ sdk,
+ provision,
+ table: { metadataId: createdTable.metadataId, logicalName: createdTable.logicalName || logical },
+ tableSchemaName: e.schemaName,
+ columns: inlineSet,
+ optionsFor: (c) => columnOptions(c, globalChoiceIds, spec.globalChoices, resolvedLanguageCode),
+ warn,
+ sleep,
+ });
+ }
+ }
// columns: every buildable column (all scalar types + Customer; Lookup comes from a
// relationship). Existing ones emit a skip; missing ones are created SERIALLY: Dataverse
// takes a per-entity exclusive [EntityCustomization] lock, so two Attribute POSTs on the
// same table collide with HTTP 429 ("Cannot start another [EntityCustomization]..."). The
// outer entity loop is already sequential, so serial columns here means one metadata
- // customization is in flight per entity at a time — the only order Dataverse permits.
- const buildable = (e.columns || []).filter((c) => SDK_COLUMN_TYPE[c.type || 'Text'] || c.type === 'Customer');
+ // customization is in flight per entity at a time — the only order Dataverse permits. A column the change set above
+ // created needs no request of its own: its step is narrated here, in spec order, with the id the read-back gave it.
const requiredDeclared = [
e.primaryAttribute,
...buildable,
@@ -982,9 +1496,9 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag
for (const c of buildable) if (existingCols.has(c.schemaName.toLowerCase())) runner.skip('data-model', `column ${e.schemaName}.${c.schemaName} (exists)`);
const toCreate = buildable.filter((c) => !existingCols.has(c.schemaName.toLowerCase()));
const colResults = await runner.mapLimit(toCreate, 1, (c) => runner.run('data-model', `column ${e.schemaName}.${c.schemaName} (${c.type || 'Text'})`,
- () => c.type === 'Customer'
+ () => inlineConfirmed.get(c) || (c.type === 'Customer'
? sdk.createCustomerColumn(logical, { schemaName: c.schemaName, displayName: c.displayName || c.schemaName, required: REQUIRED(c), languageCode: resolvedLanguageCode })
- : sdk.createColumn(logical, columnOptions(c, globalChoiceIds, spec.globalChoices, resolvedLanguageCode)),
+ : sdk.createColumn(logical, columnOptions(c, globalChoiceIds, spec.globalChoices, resolvedLanguageCode))),
{ skipIf: isAlreadyExists }));
if (existingTable) {
const existingColMeta = new Map(existingColRows.map((c) => [String(c.logicalName || c.schemaName || '').toLowerCase(), c]));
@@ -1156,16 +1670,32 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag
// schema name, so a second 1:N on the same pair, or an N:N that derived the 1:N's name, must
// halt rather than be reported as already created.
const publisherPrefix = spec.solution && spec.solution.publisherPrefix;
- for (const rel of spec.relationships || []) {
- if (rel.type !== 'OneToMany' && rel.type !== 'ManyToMany') continue;
+ // Reads the display name of a parent table the spec cannot name, once per table (ADO 6691205). Null when
+ // there is no raw client to read with — callers then use the humanized name without pretending to have asked.
+ const readParentLabel = makeTableLabelReader({ provision, languageCode: resolvedLanguageCode, warn });
+ // Lookups this run CREATED, `<referencing>|<lookup logical>`: the rebuild repair below must not touch
+ // (or even read) a column that was just given the right label.
+ const createdLookups = new Set();
+ // In the order relationshipsInCreateOrder gives: every relationship whose lookup label is LOCALIZED before any
+ // other. The parent-label read below carries labels — the read documented on relationshipExists as making
+ // Dataverse keep only the base-language label of a multi-language create that FOLLOWS it. Each read sits right
+ // before its own single-language create, which is the create it can only harm harmlessly; but a localized create
+ // later in this loop would still have a label-bearing read ahead of it. With every localized lookup created first,
+ // nothing localized follows any such read, whichever order the spec declared the relationships in. Order is
+ // otherwise free: a relationship needs only its two tables, which the loops above have already made.
+ for (const rel of relationshipsInCreateOrder(spec)) {
const schema = rel.type === 'OneToMany' ? relationshipSchemaName(rel, publisherPrefix) : manyToManySchemaName(rel, publisherPrefix);
const entityLogical = (rel.type === 'OneToMany' ? rel.referenced : rel.entity1).toLowerCase();
const label = rel.type === 'OneToMany'
? `relationship 1:N ${rel.referenced}->${rel.referencing}`
: `relationship N:N ${rel.entity1}<->${rel.entity2}`;
const declared = Object.assign({}, rel, { schemaName: rel.schemaName || schema });
+ // What the lookup column will be labelled. Decided BEFORE the existence probe because it decides how
+ // that probe may fall back: a LOCALIZED label — authored, or inherited from a localized parent table —
+ // must never be preceded by the broad metadata read (see relationshipExists).
+ const lookupLabel = rel.type === 'OneToMany' ? lookupLabelFor(spec, rel) : null;
const exists = await relationshipExists(provision, entityLogical, schema, rel.type, {
- hasLocalizedLabels: rel.type === 'OneToMany' && localizedLabelLcids(rel.lookup && rel.lookup.displayName).length > 0,
+ hasLocalizedLabels: !!lookupLabel && localizedLabelLcids(lookupLabel.label).length > 0,
declared,
});
if (exists === true) { runner.skip('data-model', `relationship ${schema} (exists)`); continue; }
@@ -1177,8 +1707,21 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag
halt.transient = false;
throw halt;
}
+ // A parent whose name the spec cannot give — a table it does not declare (account, contact,
+ // systemuser…), or one it declares without a displayName that the build did not create (an
+ // `existing: true` incident is "Case", not "Incident") — is asked of the environment rather than
+ // guessed from the table's logical name. The read is made HERE — after the probe, immediately before
+ // the create it feeds, and only when a create is going to happen. It is label-bearing, which is the
+ // read documented on relationshipExists as making Dataverse keep only the base-language label of the
+ // create that follows; that create carries one single-language label, so nothing can be stripped, and
+ // it must stay next to it rather than drift into the middle of a localized one.
+ let createLabel = lookupLabel;
+ if (createLabel && createLabel.source === 'derived' && readParentLabel && lookupParentNeedsEnvironment(spec, rel, { reused: reusedTables })) {
+ const live = await readParentLabel(rel.referenced);
+ if (live) createLabel = lookupLabelFor(spec, rel, { liveReferencedLabel: live });
+ }
const createOpts = rel.type === 'OneToMany'
- ? { type: 'OneToMany', schemaName: schema, referencedEntity: rel.referenced.toLowerCase(), referencingEntity: rel.referencing.toLowerCase(), lookupSchemaName: rel.lookup.schemaName, lookupDisplayName: rel.lookup.displayName, languageCode: resolvedLanguageCode }
+ ? { type: 'OneToMany', schemaName: schema, referencedEntity: rel.referenced.toLowerCase(), referencingEntity: rel.referencing.toLowerCase(), lookupSchemaName: rel.lookup.schemaName, lookupDisplayName: createLabel.label, languageCode: resolvedLanguageCode }
: { type: 'ManyToMany', schemaName: schema, entity1: rel.entity1.toLowerCase(), entity2: rel.entity2.toLowerCase(), intersectEntityName: rel.intersectEntityName, languageCode: resolvedLanguageCode };
await runner.run('data-model', label, async () => {
try {
@@ -1186,6 +1729,11 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag
result.relationships.push(rel.type === 'OneToMany'
? { schemaName: res.schemaName || schema, metadataId: res.metadataId, kind: '1n', lookupLogicalName: res.lookupLogicalName }
: { schemaName: res.schemaName || schema, metadataId: res.metadataId, kind: 'nn' });
+ if (rel.type === 'OneToMany') {
+ const key = lookupKey(rel);
+ createdLookups.add(key);
+ result.lookupLabels[key] = { label: labelText(createLabel.label, resolvedLanguageCode) };
+ }
} catch (err) {
if (!isAlreadyExists(err)) throw err;
// skipIf is synchronous, so classify the holder here and rethrow a marked error. The
@@ -1257,10 +1805,171 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply, languag
}, { skipIf: (e) => isAlreadyExists(e) && e.sameRelationshipExists === true });
}
+ // A rebuild repairs a lookup column an older build labelled with its old default (opt-in: only the app
+ // build budgets the steps this emits — see planFor).
+ if (reconcileLookupLabels) {
+ await reconcileLookupLabelsPass({ spec, sdk, provision, runner, warn, languageCode: resolvedLanguageCode, createdLookups, readParentLabel, reusedTables, result });
+ }
return result;
}
+// The lookups whose label the build owns — the spec sets none (ADO 6691205). One predicate shared by
+// the repair pass and planFor, so the steps the pass emits are exactly the steps the plan budgets.
+function lookupsWithDefaultLabel(spec) {
+ return ((spec && spec.relationships) || []).filter((rel) => rel && rel.type === 'OneToMany' && rel.lookup && rel.lookup.schemaName
+ && lookupLabelFor(spec, rel).source !== 'explicit');
+}
+
+// The relationships, in the order the data-model phase creates them: those whose lookup label is LOCALIZED —
+// an LCID map, authored or inherited from a localized parent table — first, every other relationship after
+// them, each group in declared order. A label that needs a read of the parent's name is never localized (it is
+// the environment's one string), so the reads that precede a create all belong to the second group — see the
+// loop in provisionDataModel for why that matters. planFor lists the relationships in this order too, so the
+// plan shows what the build does.
+function relationshipsInCreateOrder(spec) {
+ const relationships = ((spec && spec.relationships) || []).filter((rel) => rel && (rel.type === 'OneToMany' || rel.type === 'ManyToMany'));
+ const localized = (rel) => {
+ const lookupLabel = rel.type === 'OneToMany' ? lookupLabelFor(spec, rel) : null;
+ return !!lookupLabel && localizedLabelLcids(lookupLabel.label).length > 0;
+ };
+ return [...relationships.filter(localized), ...relationships.filter((rel) => !localized(rel))];
+}
+
+// Repair, on a REBUILD, a lookup column an older build labelled with the vendored SDK's default — the
+// referenced table's logical name (ADO 6691205).
+//
+// Only when ALL of these hold, so a label a maker chose is never touched:
+// * the spec sets no `lookup.displayName` (an explicit label is the author's, and is never reapplied);
+// * the relationship already existed (a column created this run already has the right label);
+// * the column carries exactly ONE label — the old default was written in one language, so a second
+// means somebody edited it since — and that language is the BUILD's own. An old default in another
+// language is left alone: the write below would add the build's language next to it, leaving two
+// languages of which one is still an identifier, and every later rebuild would then see "several
+// languages" and skip the column for good;
+// * that label is exactly the old default: the lower-case logical name of the referenced table, case-sensitive
+// (isOldLookupColumnLabel) — the only label a build ever wrote on a COLUMN.
+// The new label is the one a fresh build would write — lookupLabelFor — but written in ONE language
+// (the authoring one) even when the parent's name is localized: this is an UPDATE preceded by a
+// label-bearing read, and a multi-language write there is exactly the shape the documented base-language
+// hazard strips, so it is not risked for a repair. The other languages of a localized parent come with
+// a fresh build or Maker.
+//
+// Exactly one event per lookup the build owns, so the [n/total] the plan promised holds: planFor budgets
+// the same predicate (lookupsWithDefaultLabel). The labels are read once per CHILD TABLE, not once per
+// lookup, and only for the lookups this run did not just create.
+async function reconcileLookupLabelsPass({ spec, sdk, provision, runner, warn, languageCode, createdLookups, readParentLabel, reusedTables, result }) {
+ const client = provision && provision.dataverse;
+ const owned = lookupsWithDefaultLabel(spec);
+ // child -> the lookup columns of it that need reading, so one request answers for all of them.
+ const toRead = new Map();
+ for (const rel of owned) {
+ if (createdLookups.has(lookupKey(rel))) continue;
+ const child = String(rel.referencing).toLowerCase();
+ if (!toRead.has(child)) toRead.set(child, []);
+ toRead.get(child).push(String(rel.lookup.schemaName).toLowerCase());
+ }
+ const reads = new Map();
+ const labelsOfChild = (child) => {
+ if (!reads.has(child)) {
+ reads.set(child, readColumnLabels(client, child, toRead.get(child)).then((got) => {
+ if (got.state === 'error' && typeof warn === 'function') {
+ warn(`could not read the label of lookup(s) ${toRead.get(child).map((c) => `'${child}.${c}'`).join(', ')} (${got.why}), so a label an older build left on them was not checked. Re-run to retry.`);
+ }
+ return got;
+ }));
+ }
+ return reads.get(child);
+ };
+ const buildLanguage = String(languageCode);
+ // The tables whose lookups this pass relabelled, published below in one envelope.
+ const relabelled = new Set();
+
+ for (const rel of owned) {
+ const child = String(rel.referencing).toLowerCase();
+ const lookupLogical = String(rel.lookup.schemaName).toLowerCase();
+ const step = `lookup label ${child}.${rel.lookup.schemaName}`;
+ const key = lookupKey(rel);
+ if (createdLookups.has(key)) { runner.skip('data-model', `${step} (set when the relationship was created)`); continue; }
+ if (!client || typeof client.get !== 'function') { runner.skip('data-model', `${step} (no metadata client — left as it is)`); continue; }
+ const read = await labelsOfChild(child);
+ if (read.state === 'error') { runner.skip('data-model', `${step} (could not be read — left as it is)`); continue; }
+ const labels = read.state === 'ok' ? read.byColumn.get(lookupLogical) : undefined;
+ if (!labels) { runner.skip('data-model', `${step} (column not found — left as it is)`); continue; }
+
+ const languages = Object.keys(labels);
+ const only = languages.length === 1 ? languages[0] : null;
+ const current = only ? labels[only] : undefined;
+ const shown = labelText(labels, languageCode);
+ if (current === undefined || !isOldLookupColumnLabel(rel, current)) {
+ runner.skip('data-model', `${step} (${languages.length > 1 ? 'labelled in several languages' : `labelled "${shown}"`} — left as it is)`);
+ if (shown) result.lookupLabels[key] = { label: shown };
+ continue;
+ }
+ if (only !== buildLanguage) {
+ runner.skip('data-model', `${step} (the old default "${current}" is in language ${only}, not the build's ${buildLanguage} — left as it is)`);
+ if (typeof warn === 'function') {
+ warn(`lookup '${child}.${lookupLogical}' still carries the old default label "${current}" in language ${only}, and this build writes language ${buildLanguage}: relabelling it would leave two languages side by side, one of them still the old default, so it was left as it is. Rename the column in Maker to relabel it: a build changes an existing lookup's label only where it is the old default in the build's own language, and lookup.displayName names only a lookup the build creates.`);
+ }
+ result.lookupLabels[key] = { label: current };
+ continue;
+ }
+ let want = lookupLabelFor(spec, rel);
+ if (want.source === 'derived' && readParentLabel && lookupParentNeedsEnvironment(spec, rel, { reused: reusedTables })) {
+ const parentLabel = await readParentLabel(rel.referenced);
+ if (parentLabel) want = lookupLabelFor(spec, rel, { liveReferencedLabel: parentLabel });
+ }
+ const next = labelText(want.label, languageCode);
+ if (!next || next === current) {
+ runner.skip('data-model', `${step} (already "${current}")`);
+ result.lookupLabels[key] = { label: current };
+ continue;
+ }
+ await runBestEffort(runner, 'data-model', `${step}: "${current}" -> "${next}"`, async () => {
+ await sdk.updateColumn(child, lookupLogical, { displayName: next, languageCode });
+ result.lookupLabels[key] = { label: next };
+ relabelled.add(child);
+ }, warn, `could not relabel lookup '${child}.${lookupLogical}' from its old default "${current}" to "${next}" — the rest of the build continues`);
+ }
+ if (relabelled.size) await publishRelabelledTables(client, [...relabelled], warn);
+}
+
+// A column's label is part of its table's definition, and a table or column definition change reaches model-driven apps
+// only once it is published: "When you update a table or column definition, use the PublishXml Action before the
+// changes you make are applied to the model-driven applications"
+// (https://learn.microsoft.com/power-apps/developer/data-platform/webapi/create-update-entity-definitions-using-web-api#update-table-definitions).
+// No metadata read shows the difference: measured live, RetrieveEntity returns the new label right after the PUT even
+// with RetrieveAsIfPublished=false, so a live check of this publish has to trace the request, not read the label.
+// Nothing else in the build is sure to publish the child table. Its other table publishes follow from what the spec
+// puts on a table — a form, view, chart or icon, or its enriched default views — and a downloaded spec, whose lookups
+// the download leaves without a label precisely so that this pass repairs them, carries no forms, views, charts or
+// table icons and marks every table existing: true, whose default views the build leaves alone. A rebuild of one would
+// save the new label and leave it to whatever publishes that table next, while reporting the repair done; a re-run
+// finds the label already changed. So the pass publishes the tables it relabelled itself, in ONE envelope, at once —
+// with or without --publish, as the reconcile paths publish what they change — and in the data-model phase, before
+// anything publishes the app: a PublishXml naming only the app, sent after a form's label change and before its table's
+// own publish, leaves the form's labels unpublished for good (measured for forms; see publishReconciledTables,
+// sdk-build.js), and a relabelled table is published first here for the same reason.
+// The request:
+// POST /PublishXml { ParameterXml: "<importexportxml><entities><entity>contoso_task</entity></entities></importexportxml>" }
+// Best-effort: the labels are saved whatever it answers, so a failure is a warning that says how to show them.
+async function publishRelabelledTables(client, tables, warn) {
+ const notLive = (why) => {
+ if (typeof warn !== 'function') return;
+ const which = tables.length > 1 ? `tables ${tables.join(', ')}` : `table ${tables[0]}`;
+ warn(`the new lookup label(s) on ${which} are saved but not published (${why}), so the app still shows the old ones: publish ${tables.length > 1 ? 'those tables' : 'that table'} in Power Apps`);
+ };
+ if (!client || typeof client.post !== 'function') { notLive('no client to publish with'); return; }
+ try {
+ const response = await client.post('/PublishXml', {
+ ParameterXml: `<importexportxml><entities>${tables.map((t) => `<entity>${t}</entity>`).join('')}</entities></importexportxml>`,
+ });
+ if (!response || response.status < 200 || response.status >= 300) notLive(`PublishXml answered HTTP ${response && response.status}`);
+ } catch (e) {
+ notLive((e && e.message) || String(e));
+ }
+}
+
// Factory for entity-set resolver: fresh tables cached in `entities` (from data-model
// phase); existing ones via fetchEntityMetadata. Returns async (logical) => entitySetName.
function makeEntitySetResolver({ spec, entities, provision }) {
@@ -1521,4 +2230,4 @@ async function provisionSampleData({ sdk, provision, runner, spec, dataModel })
return { records: result.records, entitySetFor };
}
-module.exports = { makeRunner, runBestEffort, requireSuccessfulPush, pushFailed, reportPartialPush, errorCodeChain, RESET_WORKSPACE, makeEntitySetResolver, resolveLanguageCode, resolveAuthoringLanguage, provisionSolution, provisionDataModel, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE, isVisualizationUnsupported, localizedLabelLcidsInSpec, checkLocalizedLabelLanguages, findExistingTable, findExistingColumns, relationshipExists };
+module.exports = { makeRunner, mapLimit, runBestEffort, requireSuccessfulPush, pushFailed, reportPartialPush, errorCodeChain, RESET_WORKSPACE, makeEntitySetResolver, resolveLanguageCode, resolveAuthoringLanguage, provisionSolution, provisionDataModel, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE, isVisualizationUnsupported, localizedLabelLcidsInSpec, checkLocalizedLabelLanguages, findExistingTable, findExistingColumns, relationshipExists, lookupsWithDefaultLabel, relationshipsInCreateOrder };
diff --git a/plugins/model-apps/scripts/lib/form-preview.js b/plugins/model-apps/scripts/lib/form-preview.js
index f5db651c7..676f5c59f 100644
--- a/plugins/model-apps/scripts/lib/form-preview.js
+++ b/plugins/model-apps/scripts/lib/form-preview.js
@@ -5,7 +5,8 @@
// interactive authoring turn before approving it. Pure (no I/O); the CLI is preview-form.js.
const { compileFormIntent } = require('./artifact-intent.js');
const { entityByLogical } = require('./_graph.js');
-const { labelText } = require('./app-spec.js');
+const { labelText, formLayoutNames, lookupColumnsFor } = require('./app-spec.js');
+const { splitSubgrids, columnItems } = require('./form-subgrid-placement.js');
const INNER = 63; // content width inside the box borders
@@ -64,11 +65,15 @@ const BOTTOM = `└${'─'.repeat(INNER + 2)}┘`;
// Display label for a field logical name. compileFormIntent emits push-ready cells that OMIT the
// label (the SDK adapter derives it from attribute metadata at push, per T4), so the preview
// resolves the display name itself from the spec entity (falling back to the logical name).
-function labelFor(entity, fn, lang) {
+//
+// A relationship's lookup is not in entities[].columns, so `lookups` (logical -> label, from
+// lookupColumnsFor — the same rule the build labels the column by) answers for it; without that a
+// lookup field read as its logical name here, which is exactly the label the bug put on the real form.
+function labelFor(entity, fn, lang, lookups) {
if (!entity) return fn;
if (entity.primaryAttribute && entity.primaryAttribute.schemaName.toLowerCase() === fn) return labelText(entity.primaryAttribute.displayName, lang) || 'Name';
const c = (entity.columns || []).find((x) => x.schemaName.toLowerCase() === fn);
- return (c && (labelText(c.displayName, lang) || c.schemaName)) || fn;
+ return (c && (labelText(c.displayName, lang) || c.schemaName)) || (lookups && lookups.get(fn)) || fn;
}
// The authored, non-default state of one cell, as the suffix that is appended to its label.
@@ -98,12 +103,12 @@ function stateTag(cell) {
//
// When even that is not enough — the tag alone is wider than the column — the ROW renderer stacks
// the cells at full width instead of calling this with an impossible `avail`.
-function fieldLabel(entity, cell, lang, avail) {
+function fieldLabel(entity, cell, lang, avail, lookups) {
const fn = cell.control.fieldName;
const req = cell.control.isRequired ? ' *' : '';
const widget = WIDGET[fieldType(entity, fn)] || WIDGET.Text;
const tag = stateTag(cell);
- const name = cell.control.label || labelFor(entity, fn, lang);
+ const name = cell.control.label || labelFor(entity, fn, lang, lookups);
const full = `${name}${req}${tag} ${widget}`;
if (!tag || !avail || vwidth(full) <= avail) return full;
const noWidget = `${name}${req}${tag}`;
@@ -114,6 +119,8 @@ function fieldLabel(entity, cell, lang, avail) {
// Render one form to an ASCII wireframe string.
function renderFormWireframe(spec, f) {
const entity = entityByLogical(spec, f.entity || '');
+ // logical -> label for the table's relationship lookups, which are not in entities[].columns.
+ const lookups = new Map(lookupColumnsFor(spec, f.entity || '').map((l) => [l.logical, l.displayName]));
// compileFormIntent is the single source of form topology (new SDK shape
// tabs[].columns[].sections[]). notesClassId is irrelevant to the preview (it keys the notes
// section by name, not classId), so a placeholder is fine.
@@ -122,6 +129,11 @@ function renderFormWireframe(spec, f) {
const typeTag = def.formType && def.formType !== 'Main' ? ` [${def.formType}]` : '';
lines.push(topBorder(`${def.name || f.entity}${typeTag}`));
+ // A sub-grid that says where it goes (`tab` / `column` / `after` / `before`) is drawn there, among the sections;
+ // the others stay in the block after the last tab, where the build leaves them too (lib/form-subgrid-placement.js).
+ const layout = formLayoutNames(f);
+ const { placed, unplaced } = splitSubgrids(layout, f.subgrids);
+
const tabLabels = def.tabs.map((t) => t.label || 'General');
if (tabLabels.length > 1) {
lines.push(row(`Tabs: ${tabLabels.map((t, i) => (i === 0 ? `‹${t}›` : t)).join(' ')}`));
@@ -129,6 +141,7 @@ function renderFormWireframe(spec, f) {
}
for (const tab of def.tabs) {
+ const ti = def.tabs.indexOf(tab);
// The banner carries the tab's authored STATE, so it must render whenever that state is not the
// default — not only when there are several tabs to tell apart. A single tab that is collapsed or
// hidden would otherwise preview as an ordinary open tab, and the wireframe IS the approval gate:
@@ -144,8 +157,16 @@ function renderFormWireframe(spec, f) {
// need column-aware wrapping of every section; naming the split keeps the preview honest
// about the structure without pretending to be a pixel layout.
if (cols.length > 1) lines.push(row(` ╷ column ${ci + 1} of ${cols.length}${col.width ? ` (${col.width})` : ''}`));
- for (const sec of col.sections || []) {
- if (sec.name === 'section_notes') {
+ for (const item of columnItems(layout, ti, ci, col.sections, placed)) {
+ if (item.subgrid) {
+ lines.push(rule(`▦ ${item.subgrid.label || item.subgrid.childEntity}`));
+ lines.push(row(` (sub-grid → ${item.subgrid.childEntity})`));
+ continue;
+ }
+ const sec = item.section;
+ // The Notes section is the one the compiler added: a layout may declare a section named `section_notes` too,
+ // and that one is drawn with its fields like any other (columnItems says which is which, by place).
+ if (item.engine && sec.name === 'section_notes') {
lines.push(rule('▤ Notes / Timeline'));
lines.push(row(' (activity timeline + notes — type to add a note)'));
continue;
@@ -171,23 +192,22 @@ function renderFormWireframe(spec, f) {
const mustStack = cells.length > 1 && cells.some((c) => stateTag(c) && needed(c) > colW);
if (mustStack) {
for (const c of cells) {
- lines.push(row(clip(` ${fieldLabel(entity, c, spec && spec.languageCode, INNER - 2)}`, INNER)));
+ lines.push(row(clip(` ${fieldLabel(entity, c, spec && spec.languageCode, INNER - 2, lookups)}`, INNER)));
}
continue;
}
// `colW - 2` is the room left after the two-space cell indent below, and is what
// fieldLabel needs in order to protect the state annotation from being clipped.
- const parts = cells.map((c) => vpad(clip(` ${fieldLabel(entity, c, spec && spec.languageCode, colW - 2)}`, colW), colW));
+ const parts = cells.map((c) => vpad(clip(` ${fieldLabel(entity, c, spec && spec.languageCode, colW - 2, lookups)}`, colW), colW));
lines.push(row(parts.join('')));
}
}
}
}
- const subgrids = f.subgrids || [];
- if (subgrids.length) {
+ if (unplaced.length) {
lines.push(rule('▦ Sub-grids'));
- for (const sg of subgrids) lines.push(row(` • ${sg.label || sg.childEntity} → ${sg.childEntity}`));
+ for (const sg of unplaced) lines.push(row(` • ${sg.label || sg.childEntity} → ${sg.childEntity}`));
}
const events = f.events || [];
if (events.length) {
diff --git a/plugins/model-apps/scripts/lib/form-subgrid-placement.js b/plugins/model-apps/scripts/lib/form-subgrid-placement.js
new file mode 100644
index 000000000..3467498a4
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/form-subgrid-placement.js
@@ -0,0 +1,200 @@
+'use strict';
+// Where a form's sub-grid sections go — forms[].subgrids[].tab / column / after / before.
+//
+// PURE: no I/O, no SDK. The spec gate (app-spec.js), the build (sdk-build.js), `--verify` (verify-spec.js) and
+// the wireframe (form-preview.js) all read placement through this module, so none of them can disagree about
+// what a placement means. The layout it works against is the list of tabs, form-columns and sections a form
+// DECLARES, under the names the compiler gives them (`formLayoutNames`, app-spec.js, which owns the
+// generated-name rules); an auto layout is its one tab, `tab_general`, holding one section, `section_general`.
+//
+// What a placement says:
+// after / before the grid's section sits in the form-column of the named section, DIRECTLY after / directly
+// before it: nothing sits between them but the grids that share the anchor and are declared
+// ahead of it, which keep the order they are declared in. A build puts a new grid there, and a
+// rebuild moves one that is elsewhere — the GRID moves; no section of the layout, a maker's own
+// section or the Notes section is ever moved to make room, so those that sat between are
+// simply left behind it. It is where a fresh build puts the grid, so a rebuilt form and a new
+// one agree.
+// tab [+ column] the grid's section is in that tab — in form-column `column` when given, else any — and
+// is put at the END of that column when it is created or has to be moved there. Within the
+// column it is left where it is.
+// (nothing) as before this existed: the end of the first tab's first form-column, and never moved.
+// Only the engine's own grid section for a relationship is ever moved to honour a placement.
+
+const { isEngineHostSection } = require('./form-container-match.js');
+
+// The names the compiler gives an auto layout's only tab and section (artifact-intent.js writes the same
+// literals; a test pins the two together).
+const AUTO_TAB_NAME = 'tab_general';
+const AUTO_SECTION_NAME = 'section_general';
+// The platform's class id for the sub-grid control (the SDK's ControlClassIds.SubgridControl).
+const SUBGRID_CLASS_ID = 'E7A81278-8635-4D9E-8D4D-59480B391C5B';
+
+const sameId = (a, b) => String(a == null ? '' : a).replace(/[{}]/g, '').trim().toLowerCase()
+ === String(b == null ? '' : b).replace(/[{}]/g, '').trim().toLowerCase();
+
+// The relationship a sub-grid control shows, whichever tree shape the control comes from: the SDK's form artifact
+// keeps it in `parameters.RelationshipName`, verify's parse of published FormXML in `relationshipName` (read from
+// <control classid="{E7A81278-…}"><parameters><RelationshipName>new_customer_new_ticket</RelationshipName>…).
+const relationshipOf = (control) => String((control && (control.relationshipName
+ || (control.parameters && control.parameters.RelationshipName))) || '');
+
+// The section a form holds the sub-grid for `relationshipName` in — the first, with the engine's own `section_grid_…`
+// host preferred when several hold it — and where it is: { ti, ci, si, section, engine }, or null. `engine` says the
+// build owns the section (a host, see isEngineHostSection); a grid a maker put in a section of their own is found
+// too, but is not the build's to move. `tabs` is the form's tabs array in either tree shape.
+function findGridSection(tabs, relationshipName) {
+ const want = String(relationshipName).toLowerCase();
+ let found = null;
+ (tabs || []).forEach((tab, ti) => ((tab && tab.columns) || []).forEach((column, ci) => ((column && column.sections) || []).forEach((section, si) => {
+ const holds = ((section && section.rows) || []).some((row) => ((row && row.cells) || []).some((cell) => {
+ const control = cell && cell.control;
+ return !!control && sameId(control.classId, SUBGRID_CLASS_ID) && relationshipOf(control).toLowerCase() === want;
+ }));
+ if (!holds) return;
+ const hit = { ti, ci, si, section, engine: isEngineHostSection(section) };
+ if (!found || (hit.engine && !found.engine)) found = hit;
+ })));
+ return found;
+}
+
+// What an entry declares, normalized: names lower-cased (every container comparison is), `column` a whole
+// number. Anything else is ignored here — the spec gate reports it; the build never sees it. `null` when the
+// entry declares no placement at all, which is what keeps a spec without these keys on the original path.
+function placementOf(sg) {
+ if (!sg || typeof sg !== 'object' || Array.isArray(sg)) return null;
+ const name = (v) => (typeof v === 'string' && v.trim() ? v.trim().toLowerCase() : undefined);
+ const out = {};
+ if (name(sg.tab) !== undefined) out.tab = name(sg.tab);
+ if (Number.isInteger(sg.column) && sg.column >= 0) out.column = sg.column;
+ if (name(sg.after) !== undefined) out.after = name(sg.after);
+ if (name(sg.before) !== undefined) out.before = name(sg.before);
+ return Object.keys(out).length ? out : null;
+}
+
+const anchorOf = (placement) => (placement && placement.after ? { name: placement.after, side: 'after' }
+ : placement && placement.before ? { name: placement.before, side: 'before' } : null);
+
+// Resolve a placement against a layout (`[{ name, columns: [{ sections: [name…] }] }]`, names lower-cased).
+// ok → { ok: true, tabIndex, columnIndex, anchor }
+// `columnIndex` is the column the placement is about: the anchor's, or the one `column` names.
+// Without an anchor and without `column` it is `undefined` ("any column of the tab") and
+// `createColumn` (0) is where a new grid goes.
+// not ok → { ok: false, code, … } — what is wrong, as data the caller words.
+function resolvePlacement(layout, placement) {
+ const tabs = Array.isArray(layout) ? layout : [];
+ const p = placement || {};
+ const anchor = anchorOf(p);
+ if (p.after && p.before) return { ok: false, code: 'both' };
+ if (anchor) {
+ for (let ti = 0; ti < tabs.length; ti += 1) {
+ for (let ci = 0; ci < tabs[ti].columns.length; ci += 1) {
+ if (!tabs[ti].columns[ci].sections.includes(anchor.name)) continue;
+ if (p.tab !== undefined && p.tab !== tabs[ti].name) return { ok: false, code: 'anchor-tab', anchor, actualTab: tabs[ti].name };
+ if (p.column !== undefined && p.column !== ci) return { ok: false, code: 'anchor-column', anchor, actualColumn: ci };
+ return { ok: true, tabIndex: ti, columnIndex: ci, createColumn: ci, anchor };
+ }
+ }
+ return { ok: false, code: 'anchor', anchor };
+ }
+ const tabIndex = p.tab === undefined ? 0 : tabs.findIndex((t) => t.name === p.tab);
+ if (tabIndex < 0 || tabIndex >= tabs.length) return { ok: false, code: 'tab' };
+ if (p.column !== undefined && p.column >= tabs[tabIndex].columns.length) return { ok: false, code: 'column', tabIndex, columns: tabs[tabIndex].columns.length };
+ return { ok: true, tabIndex, columnIndex: p.column, createColumn: p.column === undefined ? 0 : p.column, anchor: null };
+}
+
+// The relative order of one form-column's sections of the layout and the grids anchored in it.
+// authored the column's section names in the layout's order (lower-cased)
+// grids [{ key, after?, before? }] — the anchored grids placed in this column, in declared order
+// Returns tokens `{ section, at }` | `{ grid, after?, before? }`; `at` is the section's place in `authored`, which is
+// its place in the compiled column too (columnItems reads the column by it). A grid goes right after (before) its
+// anchor, and after (before) the grids already put there, so grids sharing an anchor stay in declared order. A grid
+// whose anchor is not in this column — a case the spec gate refuses — goes last rather than being dropped.
+function columnSequence(authored, grids) {
+ const seq = (authored || []).map((name, at) => ({ section: name, at }));
+ for (const g of grids || []) {
+ const token = { grid: g.key };
+ if (g.after) token.after = g.after;
+ if (g.before) token.before = g.before;
+ const anchorName = g.after || g.before;
+ const at = seq.findIndex((t) => t.section === anchorName);
+ if (at < 0) { seq.push(token); continue; }
+ if (g.after) {
+ let i = at + 1;
+ while (i < seq.length && seq[i].grid !== undefined && seq[i].after === g.after) i += 1;
+ seq.splice(i, 0, token);
+ } else {
+ seq.splice(at, 0, token);
+ }
+ }
+ return seq;
+}
+
+// A token's name for a message: a section by name, a grid by what it shows.
+const tokenLabel = (token, gridLabel) => (token.section !== undefined ? `section '${token.section}'` : `sub-grid '${gridLabel ? gridLabel(token.grid) : token.grid}'`);
+
+// The token an ANCHORED grid must sit directly beside, and on which side: for an `after` grid the nearest token
+// before it in `seq` that `present(token)` says is on the form, for a `before` grid the nearest one after it.
+// "Nearest" because what sits between a grid and its anchor in the sequence is only the grids that share the
+// anchor and are declared ahead of it — and a form may not have one of those (no relationship, no view), in which
+// case the grid sits beside the anchor itself. Build and `--verify` both ask this, so they cannot disagree about
+// the place a grid has. null when nothing toward the anchor is present, i.e. the anchor is not on the form.
+function neighbourOf(seq, gridKey, present) {
+ const list = seq || [];
+ const k = list.findIndex((t) => t.grid === gridKey);
+ if (k < 0) return null;
+ const side = list[k].after ? 'after' : 'before';
+ const step = side === 'after' ? -1 : 1;
+ for (let j = k + step; j >= 0 && j < list.length; j += step) {
+ if (present(list[j])) return { token: list[j], side };
+ }
+ return null;
+}
+
+// A form's sub-grids split into those that say where they go — and whose placement the layout resolves, each with
+// its resolution and its position in the list — and the rest, which a build leaves at the end of the first tab's
+// first form-column. A placement the layout cannot resolve is one the spec gate refuses and a build ignores, so it
+// does not place a grid here either.
+function splitSubgrids(layout, subgrids) {
+ const placed = [];
+ const unplaced = [];
+ (subgrids || []).forEach((sg, index) => {
+ const raw = placementOf(sg);
+ const resolved = raw ? resolvePlacement(layout, raw) : null;
+ if (resolved && resolved.ok) placed.push({ index, sg, resolved });
+ else unplaced.push(sg);
+ });
+ return { placed, unplaced };
+}
+
+// One compiled form-column's sections in the order a build leaves them, with the placed grids set among them:
+// · the layout's own sections and the anchored grids, in columnSequence's order;
+// · then whatever the compiler added after the authored sections (the Notes section);
+// · then the grids that name only a tab (and column), which a build appends to the end of the column.
+// Returns [{ section, engine } | { subgrid }]. For the consumers that draw or synthesize the layout a spec asks for
+// rather than read a deployed one — the wireframe and the offline verify reader.
+//
+// The compiled column lists the layout's sections first, in the layout's order, and then what the compiler added, so
+// a section is told from another by its PLACE in that list and never by its name: a layout may declare a section
+// named `section_notes` (a natural name for a section of note fields) and the compiler's own Notes section carries
+// the same one. Matching by name would find the layout's for both and drop the compiler's from the column — and with
+// it the timeline the form asks for. `engine` says the compiler added the section (it is not the layout's).
+function columnItems(layout, tabIndex, columnIndex, sections, placed) {
+ const list = sections || [];
+ const authored = (((layout[tabIndex] || {}).columns || [])[columnIndex] || { sections: [] }).sections;
+ const item = (section, at) => ({ section, engine: at >= authored.length });
+ const here = (placed || []).filter((p) => p.resolved.tabIndex === tabIndex
+ && (p.resolved.anchor ? p.resolved.columnIndex : p.resolved.createColumn) === columnIndex);
+ if (!here.length) return list.map(item);
+ const anchored = here.filter((p) => p.resolved.anchor).map((p) => ({ key: p.index, [p.resolved.anchor.side]: p.resolved.anchor.name }));
+ const items = [];
+ for (const token of columnSequence(authored, anchored)) {
+ if (token.section === undefined) items.push({ subgrid: here.find((p) => p.index === token.grid).sg });
+ else if (list[token.at]) items.push(item(list[token.at], token.at));
+ }
+ list.forEach((section, at) => { if (at >= authored.length) items.push(item(section, at)); });
+ for (const p of here) if (!p.resolved.anchor) items.push({ subgrid: p.sg });
+ return items;
+}
+
+module.exports = { AUTO_TAB_NAME, AUTO_SECTION_NAME, SUBGRID_CLASS_ID, relationshipOf, findGridSection, placementOf, anchorOf, resolvePlacement, columnSequence, neighbourOf, tokenLabel, splitSubgrids, columnItems };
diff --git a/plugins/model-apps/scripts/lib/form-timeline.js b/plugins/model-apps/scripts/lib/form-timeline.js
new file mode 100644
index 000000000..70389d424
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/form-timeline.js
@@ -0,0 +1,308 @@
+'use strict';
+// The shape Dynamics renders a form's Timeline (activity timeline + notes) control in. One definition,
+// shared by the compiler (artifact-intent.js), the build's in-place repair of a host an older version
+// wrote (sdk-build.js) and `--verify` (verify-spec.js), so the three cannot disagree about what a working
+// timeline looks like.
+//
+// WHY it is more than "one control in a cell". The Notes section used to carry the timeline as an
+// ordinary unbound control:
+// <cell id="{…}" showlabel="false" visible="true" colspan="1" rowspan="1"><labels>…</labels>
+// <control id="{generated-guid}" classid="{06375649-C143-495E-A496-C962E5B4488E}" disabled="false" isrequired="false" /></cell>
+// Dynamics published that and never rendered it. The timeline on every platform form (Account, Contact, …)
+// instead has the FIXED control id `notescontrol`, sits in a cell with `showlabel="false"` that is TALL, and is
+// followed by empty spacer rows the cell spans — a cell of `rowspan` N is followed by N-1 empty rows:
+// <row><cell id="{…}" showlabel="false" colspan="1" rowspan="23" auto="false"><labels>…</labels>
+// <control id="notescontrol" classid="{06375649-C143-495E-A496-C962E5B4488E}" disabled="false" /></cell></row>
+// <row /><row /> … 22 empty rows
+// N is not fixed: platform forms use 5, 20, 23 and others, and a maker can resize the timeline in the designer.
+// `auto="false"` is on some platform timelines and absent on others, and `colspan` is 1 or 2. So what is shared —
+// and what is judged and converged here — is the id, a span of two rows or more, and the rows that back the span;
+// the build writes 23 and `auto="false"` for a host it creates, the shape known to render, and
+// never overrides a span or a width a maker chose.
+// Changing only the control id, the cell (`rowspan="23"`, `auto="false"`) and the spacer rows on a generated
+// form made the timeline render at once, so those are the parts written here. `auto` is a documented boolean
+// on a section cell, but the schema says nothing about what it means:
+// https://learn.microsoft.com/en-us/power-apps/developer/model-driven-apps/form-xml-schema
+//
+// PURE: no I/O, no SDK. The helpers read both tree shapes this plugin handles — the SDK's form artifact
+// (tabs → columns → sections → rows → cells, a cell's own attributes in `bag.a`) and verify's parse of
+// published FormXML (the same nesting, a cell's `auto` as a plain property) — because both name the parts
+// they share the same way.
+
+const { entityByLogical } = require('./_graph.js');
+
+// The platform's class id for the Timeline control (the SDK's ControlClassIds.TimelineControl).
+const TIMELINE_CLASS_ID = '06375649-C143-495E-A496-C962E5B4488E';
+// The one control id Dynamics renders a timeline under.
+const TIMELINE_CONTROL_ID = 'notescontrol';
+// A timeline cell spans this many rows: its own and TIMELINE_ROWSPAN - 1 empty spacer rows after it.
+const TIMELINE_ROWSPAN = 23;
+// What the build writes for the cell's `auto` attribute.
+const TIMELINE_AUTO = 'false';
+
+// A class id as compared: the SDK projects `classid` without braces in its original case, FormXML carries
+// it in braces, and the compiler writes the constant in upper case.
+const sameId = (a, b) => String(a == null ? '' : a).replace(/[{}]/g, '').trim().toLowerCase()
+ === String(b == null ? '' : b).replace(/[{}]/g, '').trim().toLowerCase();
+
+// An unbound control of the timeline's class. A bound control's class id comes from its attribute's type,
+// so an unbound one with this class id is the timeline itself.
+function isTimelineControl(control) {
+ return !!control && !control.fieldName && sameId(control.classId, TIMELINE_CLASS_ID);
+}
+
+// The cell the compiler writes for the timeline, as the SDK's generic surface takes it.
+//
+// The control id and the row span are typed fields the SDK honours as given (it only mints an id when one is
+// absent). `auto` is not modelled by a cell, so it travels in the cell's bag of own attributes — and the
+// moment a bag carries ANY attribute the SDK treats the cell as fetched: it keeps the bag verbatim and omits
+// every typed attribute that equals its default (`showlabel="false"`, `colspan="1"`). The platform's forms
+// spell those out, so they are written into the bag too; the typed values agree with them, and where a
+// typed value ever differs, the typed one wins on serialize.
+function timelineCellIntent(classId) {
+ return {
+ rowspan: TIMELINE_ROWSPAN,
+ bag: {
+ a: [['showlabel', 'false'], ['colspan', '1'], ['rowspan', String(TIMELINE_ROWSPAN)], ['auto', TIMELINE_AUTO]],
+ c: [],
+ },
+ control: {
+ id: TIMELINE_CONTROL_ID,
+ classId: String(classId),
+ fieldName: null,
+ label: 'Notes',
+ showLabel: false,
+ parameters: {},
+ },
+ };
+}
+
+// The rows of a new timeline host: the timeline's row, then the empty rows its cell spans. An empty
+// `{ cells: [] }` serializes as `<row />`, which is how the platform's forms write a spacer row.
+function timelineRowsIntent(classId) {
+ const rows = [{ cells: [timelineCellIntent(classId)] }];
+ for (let i = 1; i < TIMELINE_ROWSPAN; i += 1) rows.push({ cells: [] });
+ return rows;
+}
+
+// Whether a form asks for the timeline: its own `notes: true`, or `hasNotes: true` on its table. Main forms
+// only — the platform's quick-create and quick-view forms do not host one.
+function wantsTimeline(spec, formSpec) {
+ if (!formSpec || (formSpec.formType || 'Main') !== 'Main') return false;
+ if (formSpec.notes === true) return true;
+ const entity = entityByLogical(spec, String(formSpec.entity || '').toLowerCase());
+ return !!(entity && entity.hasNotes === true);
+}
+
+// A cell's own `auto` attribute, whichever tree shape it comes from.
+function cellAuto(cell) {
+ if (!cell) return undefined;
+ if (cell.auto !== undefined) return String(cell.auto);
+ const pair = ((cell.bag && cell.bag.a) || []).find((p) => Array.isArray(p) && p[0] === 'auto');
+ return pair ? String(pair[1]) : undefined;
+}
+
+// Where the timeline control sits in one section, or null. `others` are the section's other cells and `onlyCell`
+// says there are none, the one shape the build repairs in place; `rowsBelow` counts the rows after the timeline's own.
+function timelineInSection(section) {
+ const rows = (section && section.rows) || [];
+ let found = null;
+ const cells = [];
+ rows.forEach((row, rowIndex) => {
+ ((row && row.cells) || []).forEach((cell, cellIndex) => {
+ cells.push(cell);
+ if (!found && cell && isTimelineControl(cell.control)) {
+ found = { rowIndex, cellIndex, cell, control: cell.control, rowspan: Number(cell.rowspan) || 1, auto: cellAuto(cell), id: cell.control.id };
+ }
+ });
+ });
+ if (!found) return null;
+ const others = cells.filter((cell) => cell !== found.cell);
+ return Object.assign(found, { rowsBelow: rows.length - 1 - found.rowIndex, onlyCell: others.length === 0, others });
+}
+
+// Every timeline control on a form, in document order, each with where it is: { ti, ci, si, section, … }
+// plus what timelineInSection reports. `tabs` is the form's tabs array in either tree shape.
+function timelinesOf(tabs) {
+ const out = [];
+ (tabs || []).forEach((tab, ti) => ((tab && tab.columns) || []).forEach((column, ci) => ((column && column.sections) || []).forEach((section, si) => {
+ const found = timelineInSection(section);
+ if (found) out.push(Object.assign({ ti, ci, si, section }, found));
+ })));
+ return out;
+}
+
+// Whether any control on the form (a timeline or not) already uses `id`, other than `except`. Control ids are
+// names the platform's scripts and designer address, so a second `notescontrol` would be a duplicate.
+function controlIdTaken(tabs, id, except) {
+ const want = String(id).toLowerCase();
+ for (const tab of tabs || []) for (const column of (tab && tab.columns) || []) for (const section of (column && column.sections) || []) {
+ for (const row of (section && section.rows) || []) for (const cell of (row && row.cells) || []) {
+ const control = cell && cell.control;
+ if (control && control !== except && String(control.id == null ? '' : control.id).toLowerCase() === want) return true;
+ }
+ }
+ return false;
+}
+
+// What a timeline still lacks of the platform's shape, as the build writes it: `{}` when it has all of it.
+// id the control id to write
+// rowspan the cell span to write — kept when the cell is already tall (a maker may have sized it)
+// addRows empty rows to append after the timeline's row so the span is backed by rows
+// auto the `auto` attribute to write
+// Any span of two rows or more is a working height: platform forms differ (5, 20, 23, …) and a maker may resize
+// the timeline, so a cell of N rows with the N-1 rows under it lacks nothing, and only a one-row cell is raised
+// to the platform's 23. Rows are only ever ADDED, up to what the span needs — an extra row a resize left behind
+// is not the build's to delete.
+function timelineRepairPlan(found) {
+ const plan = {};
+ if (found.id !== TIMELINE_CONTROL_ID) plan.id = TIMELINE_CONTROL_ID;
+ const rowspan = found.rowspan >= 2 ? found.rowspan : TIMELINE_ROWSPAN;
+ if (rowspan !== found.rowspan) plan.rowspan = rowspan;
+ if (found.rowsBelow < rowspan - 1) plan.addRows = rowspan - 1 - found.rowsBelow;
+ // `auto="false"` is on some platform timelines and not on others, so its absence is no defect and never a reason
+ // to write by itself. It goes in WITH the conversion of a cell an older build wrote (a new id or a new span) —
+ // the shape known to render — and a cell that only lacks rows is otherwise left as it is.
+ if ((plan.id !== undefined || plan.rowspan !== undefined) && found.auto !== TIMELINE_AUTO) plan.auto = TIMELINE_AUTO;
+ return plan;
+}
+
+// Why a published timeline does not render, or '' when it does: its control id is not the one Dynamics renders a
+// timeline under, or its cell spans a single row. Any span of two rows or more renders, whatever its height.
+// For the engine's OWN host (`host: true` — the section the build owns) the rows that back the span are part of
+// the verdict too: the build converges them, so a cell of N rows without the N-1 rows under it is a fix not
+// applied. A timeline a maker added is judged by the id and the span alone — the build never edits it, so a
+// verdict on its rows could never be put right — and `auto` is in neither verdict.
+function timelineProblem(found, { host = false } = {}) {
+ const why = [];
+ if (found.id !== TIMELINE_CONTROL_ID) why.push(`the control id is '${found.id === undefined || found.id === '' ? '(none)' : found.id}', not '${TIMELINE_CONTROL_ID}'`);
+ if (found.rowspan < 2) why.push('its cell spans 1 row');
+ else if (host && found.rowsBelow < found.rowspan - 1) why.push(`its cell spans ${found.rowspan} rows but only ${found.rowsBelow} row(s) follow it`);
+ return why.join(' and ');
+}
+
+// What a build will do with a timeline host that is not in the shape Dynamics renders: repair it in place, or decline.
+// `null` when there is nothing to repair or the repair can be made; otherwise why not:
+// 'other-controls' the section holds more than the timeline — the rows its cell needs would have to be inserted
+// between the timeline and the other control, which would move it
+// 'id-taken' the host needs the id `notescontrol` and another control on the form already holds it
+// One rule, applied to two different trees. The build judges the form as its field passes leave it (sdk-build.js,
+// repairTimelineHost) — the fields the layout prunes or places elsewhere are gone from the host by then — so it passes
+// nothing and every other cell counts. `--verify` reads the published form BEFORE any build, so it passes `leaving`: the
+// cells it predicts those passes take out (verify-spec.js, notesHostInspector), which are no obstacle — and the cells it
+// cannot predict, which it does not call an obstacle either, since a build may well take them out (timelineVerifyProblem
+// says that it cannot tell). The section's other controls are judged first, as the build does.
+function timelineRefusal(tabs, found, { leaving = [] } = {}) {
+ const plan = timelineRepairPlan(found);
+ if (!Object.keys(plan).length) return null;
+ if (found.others.some((cell) => !leaving.includes(cell))) return 'other-controls';
+ if (plan.id && controlIdTaken(tabs, TIMELINE_CONTROL_ID, found.control)) return 'id-taken';
+ return null;
+}
+
+// How a form that asks for the timeline is told to put it right. A build of a spec that has not changed is skipped
+// outright by `--changed-only` ("nothing to apply"), so a form an older version left — which no change to the spec
+// reaches — is only repaired by a full build, and the advice has to say so or it sends the maker round in a loop.
+const FULL_BUILD = 'a full build of the spec (not --changed-only, which skips a spec that has not changed)';
+
+// "a", "a and b", "a, b and c" — items for a sentence; `word` is the conjunction ("or" for alternatives).
+const joinList = (items, word = 'and') => (items.length < 2 ? items.join('') : `${items.slice(0, -1).join(', ')} ${word} ${items[items.length - 1]}`);
+
+// What `--verify` reports for a form that asks for the timeline, or '' when it carries one that renders: why none does
+// and what to do about it, which depends on what a build WILL do about that form — so it says what the build will do,
+// and for a form it declines to touch, what the maker has to do first.
+// tabs the published form's tree (verify's parse of its FormXML)
+// isHost whether a section is the engine's own Notes host, the one section a build repairs
+// inspect optional, `(cell) → { name?, goes?, unsure?, destructive? }`: what a build does with each other cell of the host
+// BEFORE it judges the section. A build takes out of the section the fields the layout prunes or places elsewhere
+// first, so a cell it takes out is not in the way, and sending the maker to move it by hand would be work the
+// build does itself. `goes` says why the build takes the cell out (a clause), `destructive` that it removes
+// it (which a build only does with --allow-destructive), `name` how to call it. `unsure` is for a cell verify
+// cannot predict (a field the form has more than once, or one anchored to such a field, of which a build acts on
+// only one cell): it says why, and the advice says it cannot tell rather than promise a repair or send the maker
+// to do the build's work — in every shape of the advice, the taken-id one included, since freeing the id does not
+// decide what the build then does with the cell.
+// Without an inspector every other cell counts, as it does for a form nothing is known about.
+function timelineVerifyProblem(tabs, isHost, { inspect } = {}) {
+ const timelines = timelinesOf(tabs);
+ const judged = (t) => timelineProblem(t, { host: isHost(t.section) });
+ if (timelines.some((t) => !judged(t))) return '';
+ const idTaken = controlIdTaken(tabs, TIMELINE_CONTROL_ID);
+ const host = timelines.find((t) => isHost(t.section));
+ if (host) {
+ const doesNot = `the deployed form's timeline does not render: ${judged(host)}`;
+ const cells = host.others.map((cell) => Object.assign({ cell }, inspect ? inspect(cell) : {}));
+ const leaving = cells.filter((c) => c.goes);
+ const unsure = cells.filter((c) => !c.goes && c.unsure);
+ const staying = cells.filter((c) => !c.goes && !c.unsure);
+ // What the build does first, so the maker is not surprised by it — least of all by a removal.
+ const firstTakes = leaving.length
+ ? `; the build first takes ${joinList(leaving.map((c) => `${c.name || 'a control'} (${c.goes})`))} out of the Notes section${leaving.some((c) => c.destructive) ? ', and removing a field needs --allow-destructive' : ''}`
+ : '';
+ // What it cannot tell. Such a cell is not counted as in the way below — the build may well take it out, and saying
+ // otherwise would send the maker to do by hand what it does — and it is not promised to go either: it may stay, and the
+ // maker is told what that looks like and what to do then.
+ const names = [...new Set(unsure.map((c) => `${c.name || 'a control'} (${c.unsure})`))];
+ const whichCell = 'a build acts on one cell of such a field, and which one depends on how it arranges the form';
+ const ifLeft = `If its report says the timeline was left as it is, move ${unsure.length === 1 ? 'that cell' : 'those cells'} out of the section in the maker and run a full build again${unsure.some((c) => c.destructive) ? ' (removing a field needs --allow-destructive)' : ''}`;
+ // Where the advice is not "a full build repairs it" — the section holds something that stays, or another control holds the
+ // id — what verify cannot tell is whether the build takes the cell out. `also`: the advice has already said what the build
+ // takes out first, and this is more of it. Freeing the id does not decide the cell, so the taken-id advice says it too.
+ const cannotTell = (also) => (unsure.length
+ ? `; verify cannot tell whether the build ${also ? 'also ' : ''}takes ${joinList(names)} out of the Notes section first — ${whichCell}. ${ifLeft}`
+ : '');
+ // Where a full build WOULD repair the host but for what verify cannot tell, the advice leads with that condition. "Run a full
+ // build to repair it in place" would promise what may not happen — and be printed again, word for word, after a build that
+ // has already left the timeline.
+ const mayLeave = unsure.length
+ ? `; the build repairs the timeline in place unless it leaves ${joinList(names, 'or')} in the Notes section, and verify cannot tell whether it does — ${whichCell}. ${ifLeft}`
+ : '';
+ switch (timelineRefusal(tabs, host, { leaving: leaving.concat(unsure).map((c) => c.cell) })) {
+ case 'other-controls': {
+ // Without an inspector nothing is known about those cells, so every one is in the way and none can be named.
+ if (!inspect) return `${doesNot} — the Notes section also holds other controls, so a build leaves it as it is; move them out of it, or delete the section, in the maker, then run ${FULL_BUILD}`;
+ // With one, the ones in the way are exactly those a build does not take out, and they are named when they can be.
+ const named = staying.map((c) => c.name).filter(Boolean);
+ const unnamed = staying.length - named.length;
+ const what = joinList(named.concat(unnamed ? [`${unnamed} other control${unnamed === 1 ? '' : 's'}`] : []));
+ return `${doesNot} — the Notes section also holds ${what}, which a build does not remove, so the build leaves the section as it is; move ${staying.length === 1 ? 'it' : 'them'} out of it, or delete the section, in the maker, then run ${FULL_BUILD}${firstTakes}${cannotTell(leaving.length > 0)}`;
+ }
+ case 'id-taken':
+ // What a build takes out first is not said here, so what it cannot tell is not "also" taken out.
+ return `${doesNot} — another control on the form already uses the id '${TIMELINE_CONTROL_ID}', so a build cannot give this timeline that id; remove or rename one of the two in the maker, then run ${FULL_BUILD}${cannotTell(false)}`;
+ default:
+ return `${doesNot} — run ${FULL_BUILD}${unsure.length ? '' : ' to repair it in place'}${firstTakes}${mayLeave}`;
+ }
+ }
+ // A timeline a maker added: a build never edits it, and adds a Notes section of its own beside it — unless a control
+ // already holds the id, since a second `notescontrol` would be a duplicate.
+ if (timelines.length) {
+ const doesNot = `the deployed form's timeline does not render: ${judged(timelines[0])} — it is a timeline the build did not add, so a build leaves it as it is`;
+ return idTaken
+ ? `${doesNot}, and adds no Notes section while a control uses the id '${TIMELINE_CONTROL_ID}'; fix it in the maker (the id '${TIMELINE_CONTROL_ID}' and a cell spanning more than one row) or delete it, then run ${FULL_BUILD}`
+ : `${doesNot}; run ${FULL_BUILD} to add the Notes section beside it`;
+ }
+ const none = 'the spec asks for the Notes timeline, but the deployed form has no timeline control';
+ return idTaken
+ ? `${none}, and another control already uses the id '${TIMELINE_CONTROL_ID}' that a timeline needs, so a build adds none — remove or rename that control in the maker, then run ${FULL_BUILD}`
+ : `${none} — run ${FULL_BUILD} to add it`;
+}
+
+module.exports = {
+ TIMELINE_CLASS_ID,
+ TIMELINE_CONTROL_ID,
+ TIMELINE_ROWSPAN,
+ TIMELINE_AUTO,
+ isTimelineControl,
+ timelineCellIntent,
+ timelineRowsIntent,
+ wantsTimeline,
+ timelineInSection,
+ timelinesOf,
+ controlIdTaken,
+ timelineRepairPlan,
+ timelineProblem,
+ timelineRefusal,
+ timelineVerifyProblem,
+ FULL_BUILD,
+};
diff --git a/plugins/model-apps/scripts/lib/genpage-cli.js b/plugins/model-apps/scripts/lib/genpage-cli.js
index b2fdc00f4..0876c971b 100644
--- a/plugins/model-apps/scripts/lib/genpage-cli.js
+++ b/plugins/model-apps/scripts/lib/genpage-cli.js
@@ -2,7 +2,8 @@
// Injectable wrapper around `pac model genpage upload/list` — the seam the build's pages phase uses
// to author/deploy generative pages. Page CONTENT only: uploads run WITHOUT --add-to-sitemap because
// the SDK owns the sitemap (it writes the GenPage subareas). Real impl spawns pac; tests inject `run`.
-const { invocation, spawnProcess } = require('./process-runner.js');
+const { invocation, spawnProcess, killProcessTree } = require('./process-runner.js');
+const { pacTimeoutMs, pacTimeoutAdvice, pacLongerTimeoutMs, PAC_TIMEOUT_ENV, commandArgOrPlaceholder } = require('./cli-failure.js');
const { dataverseRequest } = require('./dataverse-auth.js');
const fs = require('node:fs');
const os = require('node:os');
@@ -22,7 +23,33 @@ const cleanPacArgs = (args) => args.map((a) => String(a).replace(/\r\n|[\r\n]/g,
function buildPacInvocation(args, deps = {}) {
return invocation('pac', cleanPacArgs(args), deps);
}
-function runPac(args) {
+const REAL_CLOCK = { setTimeout, clearTimeout };
+
+// An error that must never be answered by trying again. The build re-runs a whole phase when a halt looks transient (isTransientHalt in build-model-app.js), and it decides that from
+// the error's TEXT — which quotes the page's name (user text: "SQL Timeouts", "Concurrent Deletes") and pac's own diagnostic ("… try again later") — so such an error says so with
+// `transient: false`, which that check reads on the error and on its cause. Every error that follows an upload that was SENT, unless what it did is known to be nothing, is one: the
+// re-run would send it again — a second create, with the first one's page, if it landed, left beside the new one outside the app's navigation; or a second update.
+function neverRetriedError(message, options) {
+ return Object.assign(new Error(message, options), { transient: false });
+}
+
+// How many times a READ (a listing, a download) that keeps timing out is made: the first, and one retry. A call that stalls once usually answers the next time,
+// but each try can cost the whole budget (3 min), so a third is not offered however many attempts an ordinary failure gets. An upload is never retried after a
+// timeout: see makeGenpageCli for what each kind of call does with one, and why.
+const TIMED_OUT_ATTEMPTS = 2;
+
+// What a pac run reports when its caller ended it (`runPac`'s `signal`), in the failed result's stderr.
+const PAC_ENDED = 'pac was ended: its answer is no longer needed';
+
+// Runs `pac <args>` and waits at most `timeoutMs` for it. When the time is up the whole process tree is ended (killTree: `pac.cmd` → cmd.exe → pac.exe is
+// three processes on Windows, and ending the shim alone would leave the stalled one running) and the result says so — `status: null, timedOut: true,
+// timeoutMs, command` — which no exit code is, so a caller can tell a stalled call from a failed one. Output printed before the stall is kept.
+// `spawn`, `killTree` and `clock` are seams for the tests; a call with no budget gets the read one, so no pac call is ever unbounded.
+//
+// `signal` (an AbortSignal) ends the run too: pac AND everything it started are killed — through the same `killTree` as a timeout — and the result is a failed one
+// marked `ended: true` with no output, since a half-read listing must never be parsed. A caller that ended a run is not waiting for it, which is not what
+// a stall is: `ended` is for the caller to treat as it treats `timedOut` wherever a re-send could do harm. A signal that has already aborted starts nothing.
+function runPac(args, { timeoutMs = pacTimeoutMs('list'), spawn = spawnProcess, killTree = killProcessTree, clock = REAL_CLOCK, signal } = {}) {
// Asynchronous, and it NEVER rejects. It was spawnSync, which froze the whole process for the
// length of every pac call — about five seconds for one `pac model genpage list` — so two
// independent listings could not overlap even when a caller awaited them together (an update in
@@ -38,22 +65,33 @@ function runPac(args) {
const out = [];
const err = [];
let settled = false;
- const finish = (status, launchError) => {
+ let timer = null;
+ // Settles ONCE, whichever of the child's 'close', its 'error', the deadline and the caller's signal comes first: a child that is killed at the deadline or on
+ // the signal still closes, and that close must not resolve the call a second time or turn the timeout into an exit code.
+ // `how` is 'timedOut' (the deadline passed) or 'ended' (the caller's signal ended the run), otherwise null.
+ const finish = (status, launchError, how = null) => {
if (settled) return;
settled = true;
+ if (timer !== null) clock.clearTimeout(timer);
const stderr = Buffer.concat(err).toString('utf8');
resolve({
- status: status == null ? 1 : status,
- stdout: Buffer.concat(out).toString('utf8'),
+ status: how === 'timedOut' ? null : (status == null ? 1 : status),
+ stdout: how === 'ended' ? '' : Buffer.concat(out).toString('utf8'),
// POSIX reports a missing pac as a spawn 'error' (ENOENT) with nothing on stderr; carry its
// message so the diagnostic says why instead of "pac exited 1 with no output".
stderr: stderr || (launchError ? String(launchError.message || launchError) : ''),
+ ...(how === 'timedOut' ? { timedOut: true, timeoutMs, command: ['pac', ...args.slice(0, 3)].join(' ') } : {}),
+ ...(how === 'ended' ? { ended: true } : {}),
});
};
+ if (signal && signal.aborted) {
+ finish(1, new Error(PAC_ENDED), 'ended');
+ return;
+ }
let child;
try {
// Resolution and argument checks throw here too, and resolve as a failed result like a launch error.
- child = spawnProcess('pac', cleanPacArgs(args), { stdio: ['ignore', 'pipe', 'pipe'] });
+ child = spawn('pac', cleanPacArgs(args), { stdio: ['ignore', 'pipe', 'pipe'] });
} catch (e) {
finish(1, e);
return;
@@ -68,6 +106,31 @@ function runPac(args) {
// after its parent exited was captured by spawnSync and 'close', and missed by 'exit').
child.on('error', (e) => finish(1, e));
child.on('close', (code) => finish(code));
+ if (timeoutMs > 0) {
+ timer = clock.setTimeout(() => {
+ // End the tree first, so pac is gone before the caller acts on the result — the retry of a read, or the check an upload's message sends the user to, must not race the call it gave up on.
+ try { killTree(child); } catch { /* the call is reported as stalled either way */ }
+ finish(null, null, 'timedOut');
+ // A process that outlived the kill (or one the kill missed) holds these pipes open, and a pipe nobody has finished reading keeps this process alive
+ // at exit: release them, and the child's own handle, now that the result is out.
+ for (const stream of [child.stdout, child.stderr]) {
+ try { if (stream) stream.destroy(); } catch { /* already closed */ }
+ }
+ if (typeof child.unref === 'function') child.unref();
+ }, timeoutMs);
+ // The child's handle keeps the loop alive while pac runs; the deadline must not be what keeps a process running once it does not.
+ if (timer && typeof timer.unref === 'function') timer.unref();
+ }
+ if (signal) {
+ // Settled here rather than at 'close': a caller that stopped waiting must not wait for the pipes of a process that
+ // is on its way out. On Windows taskkill has finished by the time killTree returns; elsewhere the signal is sent.
+ const end = () => {
+ try { killTree(child); } catch { /* the run is reported as ended either way */ }
+ finish(1, new Error(PAC_ENDED), 'ended');
+ };
+ signal.addEventListener('abort', end, { once: true });
+ child.on('close', () => signal.removeEventListener('abort', end));
+ }
});
}
@@ -238,9 +301,84 @@ function classifyListOutput(stdout) {
}
function makeGenpageCli(env, deps = {}) {
- const run = deps.run || runPac;
+ // The pac runs this client has in flight, one controller each, so that `abort()` can end them: pac has no timeout of its
+ // own, and a verify pass that stopped needing its answers must not leave it running.
+ const inFlight = new Set();
+ // Bumped by abort(); see runForCall.
+ let abortEpoch = 0;
+ // Forwards a call's own options (its time budget: `budget(kind)`) beside the controller that lets abort() end the run.
+ const startRun = deps.run || ((args, options = {}) => {
+ const controller = new AbortController();
+ inFlight.add(controller);
+ const call = runPac(args, { ...options, signal: controller.signal });
+ const forget = () => inFlight.delete(controller);
+ call.then(forget, forget);
+ return call;
+ });
+ // The `run` that ONE call of this client — an enumeration, an upload, a download — starts its pac runs with. abort() ends the
+ // runs in flight, but a call that is PAUSED between two attempts (a listing that failed once waits before it asks again) has
+ // none in flight: when the pause ends, its next attempt would start a pac that nothing ever ends. So a call remembers how many
+ // aborts there had been when it began, and once there has been another, every run it asks for answers `ended` — what a run
+ // ended in flight answers — without starting anything. No retry loop needs a check of its own that way, and one added later is
+ // covered by making its runs with this. A call that begins after the abort is an ordinary one: the client stays usable.
+ const runForCall = () => {
+ const epoch = abortEpoch;
+ return (...callArgs) => (abortEpoch === epoch
+ ? startRun(...callArgs)
+ : Promise.resolve({ status: 1, stdout: '', stderr: PAC_ENDED, ended: true }));
+ };
const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
const attempts = deps.attempts || 3; // pac genpage upload/list flake intermittently (transient help-dump exits)
+ // The budget of ONE pac call of this kind (lib/cli-failure.js pacTimeoutMs: 3 min to list or download, 10 min to upload, or
+ // POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS), read when the call is made. `run` ends a call that runs out of it and answers `{ status: null, timedOut: true }`.
+ //
+ // What each kind of call does about a timeout follows from what it can have done to the environment before it was stopped. pac's `genpage upload` is a
+ // SEQUENCE (pac 2.12.2): it writes the page's files in one batch, then makes two requests that record the prompt and the agent message in the page's
+ // conversation history, then prints `Page ID: <id>`, then publishes the page and registers its tables. A call that is stopped has therefore done anything from
+ // nothing to all but the last step, and nothing outside says which: a stall with no CPU and no network is most likely a long server call, such as the publish,
+ // with everything before it already written.
+ // list, download read only, so a second attempt costs nothing but time: retried ONCE (TIMED_OUT_ATTEMPTS), however many attempts an ordinary failure gets.
+ // upload, UPDATE NOT retried, though it names a page that exists. A second send goes to the same page id and is still not harmless. If the first had written
+ // the page and stalled in the publish, the second records the prompt and the agent message AGAIN (the two requests carry no client id to
+ // dedupe on, and a later download's prompt.txt then holds the duplicate). And it goes out minutes after the caller's own checks —
+ // genpage-upload.js compares the page with its base marker once, before it calls upload() — so it can overwrite a change the maker saved in
+ // between. The call is reported as timed out and as one that MAY HAVE LANDED, and a re-run goes back through the caller's own guards. What the
+ // message sends the reader to look at depends on the caller (upload()'s `caller`): see lookFirst there.
+ // An update that FAILS is not sent again either, for the same reason: a non-zero exit, or an exit 0 with no Page ID, can come anywhere in that
+ // sequence — in the publish, after everything else is written. Only a failure pac reports for its own arguments or input files (isDeterministic),
+ // with no Page ID printed, is an ordinary one: pac checks those before it sends anything, so nothing can have landed.
+ // upload, CREATE an UNCERTAIN create, and never run again: it may have created the page, may be creating it, or may never have started. A Page ID pac had
+ // already printed names the page it created, whether it then stalled or failed; otherwise the env-wide id diff reports any page that is already
+ // visible; and a page that is not visible YET proves nothing, because a second create is exactly how a duplicate is made. Each error that ends
+ // such a create carries `transient: false` (neverRetriedError), so the build's own re-run of a halt it takes for transient never sends it again.
+ // a run that was ENDED (`ended`: abort(), see runForCall) says as little as one that timed out, so an upload it ends is never sent again either: an UPDATE fails with
+ // `transient: false` and the advice to look at the page first, and a CREATE is judged like one that stalled. A listing or a download that was ended is just reported.
+ const processEnv = deps.processEnv || process.env;
+ const budget = (kind) => ({ timeoutMs: pacTimeoutMs(kind, processEnv) });
+ // A pac run that stops without an answer: it ran out of its budget (`timedOut`) or its caller ended it (`ended`). Neither says what the call did before it stopped.
+ const unanswered = (r) => !!(r && (r.timedOut || r.ended));
+ // How a stopped upload is told. pacTimeoutAdvice, which a stopped READ gets, ends in "retry" — not what to say about an upload.
+ const stoppedAfter = (r) => (r.ended ? 'was ended before it answered' : `timed out after ${Math.round((r.timeoutMs || 0) / 1000)} s and was stopped`);
+ // A message's command is one the user — or the agent — pastes, and a path can hold a space ("C:\Users\Dev User\...") or, from an untrusted checkout, shell syntax:
+ // keep it ONE argument that no shell reads anything in, or write a placeholder and name the path as data (lib/cli-failure.js commandArg).
+ const argOrPlaceholder = commandArgOrPlaceholder;
+ const allowLonger = (r) => {
+ // A run that was ended did not run out of time, so a longer budget would not have changed it.
+ if (r.ended) return '';
+ const longer = pacLongerTimeoutMs(r.timeoutMs || pacTimeoutMs('upload', processEnv));
+ return longer === null ? '' : ` ${PAC_TIMEOUT_ENV}=${longer} allows a slow upload longer.`;
+ };
+ // The way on from a page that a stopped create left behind. pac makes the page, then publishes it, and only when asked adds it to the app's navigation, so a
+ // create stopped part way leaves a page that EXISTS and is not in the app's navigation. genpage-upload.js refuses to UPDATE such a page (it is not in the app's
+ // navigation, and no base marker records it), the build cannot bind it (an id nothing proves is this app's is `unproven-manifest-id`), and a second create would
+ // make a duplicate. So the page is placed first: `pac model genpage add` attaches an existing page to an app's sitemap without uploading it again, and its
+ // `--page-id` is then a page the app's navigation proves — which the build binds from the App Spec's `pageId`.
+ const finishPage = (id, appId) => `add page ${id} to the app's navigation — in Maker, or with \`pac model genpage add --environment ${env} --app-id ${appId} --page-id ${id} --publish\` — `
+ + `and then re-run the upload as an update with --page-id ${id} (a build: set that page's pageId to ${id} in the App Spec); or delete page ${id} and re-run the create`;
+ // What to do about a create that may have made a page nothing has shown yet — one that stalled, or whose result could not be checked: look for the page before anything is created
+ // again. It is the way on whenever the page's id is not known, because a second create is how a duplicate is made.
+ const lookForThePage = (appId) => `Wait a few minutes, then run \`pac model genpage list --environment ${env} --include-unpublished\`: if a new page with this name appears and it is yours, ${finishPage('<its id>', appId)}; `
+ + 'if none appears, re-run the create.';
// The DIAGNOSTIC pac actually produced, not merely its last line.
//
// MEASURED shape of a real failure (`pac model genpage download` with no --app-id):
@@ -270,6 +408,8 @@ function makeGenpageCli(env, deps = {}) {
const BANNER_RE = /^(?:Microsoft PowerPlatform CLI|Version:|Online documentation:|Feedback, Suggestions, Issues:|Usage:|Connected as)/i;
const FLAG_HELP_RE = /^\s+-{1,2}\S/; // an indented " --flag description" row from the help dump
const pacDiagnostic = (r) => {
+ // A call that ran out of time has no exit code and may have printed nothing: say it was stopped, and how to allow it longer.
+ if (r && r.timedOut) return pacTimeoutAdvice(r.command || 'pac', r.timeoutMs || pacTimeoutMs('list', processEnv));
const raw = `${String(r && r.stderr || '')}\n${String(r && r.stdout || '')}`;
const lines = raw.split(/\r?\n/).map((l) => l.replace(/\s+$/, '')).filter((l) => l.trim());
if (!lines.length) return `pac exited ${r && r.status}` + ' with no output';
@@ -306,24 +446,33 @@ function makeGenpageCli(env, deps = {}) {
// List the pages already in the app (parsed from its sitemap by pac). Returns [{ pageId, name }].
async function listPages(appId) {
- const r = await run(['model', 'genpage', 'list', '--environment', env, '--app-id', appId]);
+ const run = runForCall();
+ const r = await run(['model', 'genpage', 'list', '--environment', env, '--app-id', appId], budget('list'));
return r.status === 0 ? parseList(r.stdout) : [];
}
// Fail-closed page enumeration (design §9, I2). Retries up to `attempts` times (pac genpage list
- // flakes with transient help-dump exits on some PAC CLI builds). Returns:
+ // flakes with transient help-dump exits on some PAC CLI builds), but a listing that times out is
+ // tried twice at most. Returns:
// { ok: true, pages, empty: true } — app genuinely has no pages ("Found 0" or no-pages phrase)
// { ok: true, pages: [...] } — COMPLETE listing: count matches, all pages named
// { ok: false, pages: [], error } — persistent non-zero exit OR a persistent zero-exit
// UNRECOGNIZED/INCOMPLETE output (count mismatch, blank,
- // help banner, unnamed page) — never masquerade as empty.
+ // help banner, unnamed page) OR a call that kept timing out
+ // — never masquerade as empty.
// Callers that drive a create decision MUST check ok before trusting pages:[] as "truly empty".
async function enumeratePages(appId, options = {}) {
+ const run = runForCall();
let lastErr = '';
+ let tried = 0;
+ let timedOut = 0;
for (let i = 0; i < attempts; i += 1) {
const args = ['model', 'genpage', 'list', '--environment', env, '--app-id', appId];
if (options && options.includeUnpublished === true) args.push('--include-unpublished');
- const r = await run(args);
+ const r = await run(args, budget('list'));
+ tried += 1;
+ // A run the caller ended is not a flake to retry: nobody is waiting for the answer any more.
+ if (r.ended) return { ok: false, pages: [], error: `pac genpage list was ended: ${r.stderr}` };
if (r.status === 0) {
const c = classifyListOutput(r.stdout);
if (c.kind !== 'unrecognized') return { ok: true, pages: c.pages, empty: c.kind === 'empty' };
@@ -333,9 +482,10 @@ function makeGenpageCli(env, deps = {}) {
} else {
lastErr = pacDiagnostic(r);
}
+ if (r.timedOut && (timedOut += 1) >= TIMED_OUT_ATTEMPTS) break;
if (i < attempts - 1) await sleep(500 * (i + 1));
}
- return { ok: false, pages: [], error: `pac genpage list failed after ${attempts} attempt(s): ${lastErr}` };
+ return { ok: false, pages: [], error: `pac genpage list failed after ${tried} attempt(s): ${lastErr}` };
}
// Env-WIDE EXISTENCE enumeration (NO --app-id): returns the set of ALL generative-page ids that exist
@@ -345,10 +495,17 @@ function makeGenpageCli(env, deps = {}) {
// discoverable before placement. Enumeration itself grants no ownership or update authority.
// Reuses classifyListOutput (fail-closed): an unrecognized/incomplete listing NEVER
// masquerades as an empty environment. `ids` are lower-cased for case-insensitive set membership.
- async function enumerateEnv() {
+ // `run` is the one a caller already inside a call of this client (upload, below) makes its runs with; a listing of its own
+ // makes its own.
+ async function enumerateEnv(run = runForCall()) {
let lastErr = '';
+ let tried = 0;
+ let timedOut = 0;
for (let i = 0; i < attempts; i += 1) {
- const r = await run(['model', 'genpage', 'list', '--environment', env, '--include-unpublished']);
+ const r = await run(['model', 'genpage', 'list', '--environment', env, '--include-unpublished'], budget('list'));
+ tried += 1;
+ // A run the caller ended is not a flake to retry: nobody is waiting for the answer any more.
+ if (r.ended) return { ok: false, ids: [], error: `pac genpage list (env-wide) was ended: ${r.stderr}` };
if (r.status === 0) {
const c = classifyListOutput(r.stdout);
if (c.kind !== 'unrecognized') {
@@ -359,9 +516,10 @@ function makeGenpageCli(env, deps = {}) {
} else {
lastErr = pacDiagnostic(r);
}
+ if (r.timedOut && (timedOut += 1) >= TIMED_OUT_ATTEMPTS) break;
if (i < attempts - 1) await sleep(500 * (i + 1));
}
- return { ok: false, ids: [], error: `pac genpage list (env-wide) failed after ${attempts} attempt(s): ${lastErr}` };
+ return { ok: false, ids: [], error: `pac genpage list (env-wide) failed after ${tried} attempt(s): ${lastErr}` };
}
async function readPageRow(pageId, select) {
@@ -375,16 +533,24 @@ function makeGenpageCli(env, deps = {}) {
}
return {
- // Create (no pageId) or update (with pageId) a page's content. Returns { pageId }. Retries transient
- // pac failures. On an UNCERTAIN CREATE (non-zero, or zero-exit with no Page ID) resolves via a
+ // Create (no pageId) or update (with pageId) a page's content. Returns { pageId }. Retries a CREATE
+ // that failed outright and left nothing behind — never an UPDATE that pac may have started (any failure but a refusal of its arguments), and never anything that
+ // TIMED OUT (the policy at the top of makeGenpageCli). On an UNCERTAIN CREATE (non-zero, or zero-exit with no Page ID) resolves via a
// STRICT ENV-WIDE before/after id diff: the env-wide id set
// is snapshotted BEFORE the first CREATE so the diff reveals exactly which id appeared.
+ // a Page ID pac printed → that page was created, whether the call then stalled or failed: report it and stop (a create is never run again)
// newIds.length >= 1 → report stored details and stop; only the user can confirm ownership
- // newIds.length === 0 → CREATE did NOT land → safe to retry
+ // newIds.length === 0 → the failed CREATE did NOT land → safe to retry (not after a timeout: the service may still be creating the page)
// Names and dates describe candidates, never establish identity. Read failures also stop,
// with the candidate id retained in the diagnostic. No uncertain result changes the command to UPDATE.
- async upload({ appId, pageId, codeFile, compiledCodeFile, name, prompt, agentMessage, dataSources,
- addToSitemap, model, connectors, actions }) {
+ // `caller` is 'build' when the App Spec build (lib/sdk-build.js) is the one uploading, and anything else for the standalone upload script: it only changes the advice
+ // given for an UPDATE that timed out or failed (lookFirst, below), never what is sent or when. `sourceFile` is the file the caller knows the page as when `codeFile` is a copy of it — the
+ // upload script sends pac a copy of the bytes it checked, removed once pac answers — and is the file that advice names; pac only ever reads `codeFile`.
+ async upload({ appId, pageId, codeFile, sourceFile, compiledCodeFile, name, prompt, agentMessage, dataSources,
+ addToSitemap, model, connectors, actions, caller }) {
+ // Every pac run of this upload — its snapshots and listings included — is made with the one `run`, so an abort() that lands
+ // while the upload pauses between attempts starts nothing more (see runForCall).
+ const run = runForCall();
// pac REQUIRES both a prompt and an agent-message for a new page. Resolve the effective text
// (preserving the historical defaults) ONCE, then hand both to pac BY FILE via --prompt-file /
// --agent-message-file rather than inline --prompt / --agent-message. A downloaded page prompt is
@@ -439,7 +605,7 @@ function makeGenpageCli(env, deps = {}) {
// "use --page-id, omit --add-to-sitemap" — enforcing it here keeps every caller honest
// instead of repeating the rule in prose at each call site.
if (addToSitemap && !pid) args.push('--add-to-sitemap');
- return run(args);
+ return run(args, budget('upload'));
};
const pid = pageId;
let lastErr = '';
@@ -447,9 +613,31 @@ function makeGenpageCli(env, deps = {}) {
// to the exact env state before this operation. Fail-closed: if we can't snapshot, we can't
// safely attribute a later uncertain result — halt to prevent a blind duplicate.
let beforeIds = null;
+ const label = name || '(unnamed)';
+ // What to look at before anything is sent again, for an UPDATE that MAY HAVE LANDED (one that timed out, or failed). What is deployed decides what happens next, and
+ // which look works depends on who is asking:
+ // the upload script compares the page with the base marker it keeps beside the code file, and a re-run goes back through that comparison — the
+ // file it names is `sourceFile`, the one the marker belongs to, not the copy pac read;
+ // the build keeps no base marker, so `genpage-base.js check` could only say "unknown" about what is deployed, and its `--file` would be
+ // the staging copy the build deletes when it ends (every page is sent from one) — the advised command would fail on a missing file. It is
+ // told to read the deployed page with the download it already uses (the `pac model genpage download` that verify-model-app.js and
+ // download-model-app.js run), and that running the build again sends this page once more to the same id, with what that costs.
+ // `how` names the send that stopped: 'stalled' or 'failed'.
+ const lookFirst = (id, how) => {
+ if (caller === 'build') {
+ return `First see what is deployed: pac model genpage download --environment ${env} --app-id ${appId} --page-id ${id} --output-directory <folder>, then read the page.tsx in the folder under <folder> that is named for the page id `
+ + '(pac writes the id in its own letter case, so look for it without regard to case; a page that links to another shows that page\'s id where its source in the app folder has a PAGEREF_ name). '
+ + `Then run the build again: it sends this page once more, to the same page id, so nothing new is created — but if the ${how} send did land, the page's history now records its prompt a second time, `
+ + 'and anything saved to the page in Maker since is replaced by the app folder\'s version. Look first if either matters.';
+ }
+ const file = argOrPlaceholder(sourceFile || codeFile, '<file>');
+ return `First see what is deployed: node scripts/genpage-base.js check --env ${env} --app-id ${appId} --page-id ${id} --file ${file.arg} ("contentSame": true means the update landed; "deployed": "unchanged" means it did not). `
+ + (file.note ? `${file.note} ` : '')
+ + 'Then re-run the upload: its own checks decide whether it may go ahead.';
+ };
for (let i = 0; i < attempts; i += 1) {
if (!pid && beforeIds === null) {
- const before = await enumerateEnv();
+ const before = await enumerateEnv(run);
if (!before.ok) {
throw new Error(
`pac genpage upload for '${name || '(unnamed)'}': cannot snapshot the environment before create (${before.error}) — refusing to create (would risk a duplicate)`
@@ -458,6 +646,18 @@ function makeGenpageCli(env, deps = {}) {
beforeIds = new Set(before.ids);
}
const r = await once(pid);
+ // An UPDATE that timed out is not sent again, and is not told as an ordinary failure: it may have landed (the policy at the top of makeGenpageCli). What
+ // is deployed decides what happens next, so the message sends the reader to look (lookFirst).
+ if (r.timedOut && pid) {
+ throw neverRetriedError(
+ `pac genpage upload for '${label}' ${stoppedAfter(r)} — the UPDATE of page ${pid} MAY HAVE LANDED: `
+ + (parsePageId(r.stdout)
+ ? 'pac had printed the Page ID, which it does once the page and its messages are written, so the stall came while it was publishing. '
+ : 'pac writes the page, then records the prompt and the agent message, then publishes, so the stall can have come after any of those with nothing reported. ')
+ + 'It was NOT sent again: a second send can record the prompt twice, and would overwrite a change made to the page since. '
+ + `${lookFirst(pid, 'stalled')}${allowLonger(r)}`
+ );
+ }
if (r.status === 0) {
const id = parsePageId(r.stdout);
if (id) {
@@ -465,8 +665,9 @@ function makeGenpageCli(env, deps = {}) {
// the pid we used. A mismatch
// means pac silently operated on a different page — halt rather than let a wrong record persist.
// Case-insensitive: PAC can normalize GUID casing across writes.
+ // `transient: false`: the send did something, so the build's own re-run of a halt it takes for transient (the page's name is in the text) must not repeat it.
if (pid && id.toLowerCase() !== pid.toLowerCase()) {
- throw new Error(
+ throw neverRetriedError(
`pac genpage upload for '${name || '(unnamed)'}': UPDATE returned an unexpected Page ID (got ${id}, expected ${pid}) — refusing to persist a mismatched update`
);
}
@@ -476,14 +677,30 @@ function makeGenpageCli(env, deps = {}) {
} else {
lastErr = pacDiagnostic(r);
}
- // Uncertain CREATE: no caller pid and result was non-zero or zero-without-Page-ID.
+ // Uncertain CREATE: no caller pid and result was non-zero, zero-without-Page-ID, or TIMED OUT.
// The env-wide diff discovers candidates, not ownership. A concurrent create can have
// the same name and date, so even a single candidate cannot authorize an automatic UPDATE.
if (!pid) {
- const after = await enumerateEnv();
+ // A create that printed the Page ID has created that page, whether it then stalled or failed: pac prints the id once the page and its messages are written, before it
+ // publishes and before it adds the page to the app's navigation. Nothing needs listing to know the page exists — and a listing need not show it yet — and running the
+ // create again would make a second one. (A create that printed it and exited 0 has returned above; a malformed id is not one: parsePageId.)
+ const created = parsePageId(r.stdout);
+ if (created) {
+ throw neverRetriedError(
+ r.timedOut
+ ? `pac genpage upload for '${label}' ${stoppedAfter(r)} after it had CREATED the page as ${created} (pac prints the Page ID once the page is written) — `
+ + 'it stalled before the page was published, and before it was added to the app\'s navigation if that was asked for. '
+ + `The create was NOT run again: a second create would make a duplicate page. To finish it, ${finishPage(created, appId)}.${allowLonger(r)}`
+ : `pac genpage upload for '${label}' failed after it had CREATED the page as ${created} (pac prints the Page ID once the page is written) — `
+ + `it stopped before the page was published, or before it was added to the app's navigation if that was asked for (${lastErr}). `
+ + `The create was NOT run again: a second create would make a duplicate page. To finish it, ${finishPage(created, appId)}.`
+ );
+ }
+ const after = await enumerateEnv(run);
if (!after.ok) {
- throw new Error(
- `pac genpage upload for '${name || '(unnamed)'}' had an uncertain result and env enumeration failed — refusing to retry (would risk a duplicate): ${after.error}`
+ throw neverRetriedError(
+ `pac genpage upload for '${name || '(unnamed)'}' ${unanswered(r) ? `${stoppedAfter(r)}, and ` : ''}had an uncertain result and env enumeration failed — refusing to retry (would risk a duplicate): ${String(after.error).replace(/[.\s]+$/, '')}. `
+ + `The create may have made a page. ${lookForThePage(appId)}${r.timedOut ? allowLonger(r) : ''}`
);
}
const newIds = after.ids.filter((id) => !beforeIds.has(id));
@@ -504,10 +721,22 @@ function makeGenpageCli(env, deps = {}) {
details.push(`${candidate}: stored name [unreadable], createdon [unreadable]; read failed (${(e && e.message) || e})`);
}
}
- throw new Error(`pac genpage upload for '${name || '(unnamed)'}' had an uncertain create (ambiguous ownership). Candidates: ${details.join('; ')}. Refusing to adopt or update any candidate. If it is yours, re-run the upload as an update with ${newIds.map((id) => `--page-id ${id}`).join(' or ')}; otherwise leave it and re-run the create.`, readFailure ? { cause: readFailure } : undefined);
- } else {
- // CREATE did NOT land → safe to retry (pid stays undefined; beforeIds unchanged)
+ // Whatever stopped the create — a stall or a failure — pac makes the page, publishes it, and only when asked adds it to the app's navigation, so a candidate it
+ // left is most likely NOT in the app's navigation: an update of it is refused (not in the app's navigation, no base marker), and `finishPage` is the way on. A
+ // failure after pac printed `Page ID` is the same state as a stall after it: the page is written, and the publish or the placement did not finish.
+ const way = `If one is yours, ${finishPage(newIds.length === 1 ? newIds[0] : '<its id>', appId)}; otherwise leave them and re-run the create.`;
+ throw neverRetriedError(`pac genpage upload for '${name || '(unnamed)'}' ${r.timedOut ? 'timed out and was stopped, and ' : (r.ended ? 'was ended before it answered, and ' : '')}had an uncertain create (ambiguous ownership). Candidates: ${details.join('; ')}. Refusing to adopt or update any candidate. ${way}`, readFailure ? { cause: readFailure } : undefined);
}
+ // A create that TIMED OUT, or was ENDED, is never run again, even with nothing in the diff: the request may still be in flight on the service, and the page not
+ // visible YET. Re-running it is how a duplicate is made.
+ if (unanswered(r)) {
+ throw neverRetriedError(
+ `pac genpage upload for '${label}' ${stoppedAfter(r)} — an UNCERTAIN create: `
+ + 'no new page is visible in the environment yet, but the service may still be creating it. Refusing to re-run the create (a second create would risk a duplicate page). '
+ + `${lookForThePage(appId)}${allowLonger(r)}`
+ );
+ }
+ // Only a CREATE that failed outright reaches here (one that timed out or was ended has thrown above), and it left nothing behind → did NOT land → safe to retry (pid stays undefined; beforeIds unchanged)
}
// A DETERMINISTIC failure will repeat for the same inputs, so retrying it only burns the
// caller's time and buries the real message under "after 3 attempt(s)". Break out and
@@ -515,6 +744,33 @@ function makeGenpageCli(env, deps = {}) {
//
// The next attempt always uses the same explicit id (or remains CREATE); recovery
// never changes command identity, so deterministic failures must stop in both modes.
+ //
+ // A run that was ENDED (abort()) is no flake either: nobody is waiting for the answer, and every attempt after it answers
+ // "ended" at once, so pausing for them would only delay the failure. (A CREATE that was ended has already been judged above, like one
+ // that timed out, so what reaches here is an UPDATE.) What it did before it was ended is unknown, as it is after a timeout, so it is
+ // never sent again — not by this loop, and not by the build's own re-run of a halt it takes for transient (`transient: false`).
+ if (r.ended) {
+ throw neverRetriedError(
+ `pac genpage upload failed for '${name || '(unnamed)'}': ${lastErr}`
+ + (pid ? ` — the UPDATE of page ${pid} may have landed before it was ended, and it was NOT sent again: look at the page before running it again` : '')
+ );
+ }
+ // An UPDATE that FAILED is not sent again either — not by this loop, and not by the build's own re-run (`transient: false`) — unless pac refused its arguments or
+ // input files (isDeterministic, on a non-zero exit, with no Page ID printed), which it checks before it sends anything. Any other failure, a non-zero exit or an exit 0
+ // with no Page ID, can come after pac wrote the page and recorded the prompt and the agent message — in the publish — so a second send would record them again and
+ // can overwrite a change saved in between, as after a stall (the policy at the top of makeGenpageCli). A Page ID pac printed proves that much was written whatever its
+ // error says: after it, pac's only step is the publish, whose error carries the server's own text, and that text can read like a refused file. Only a CREATE that
+ // failed outright and left nothing behind reaches the retry below.
+ if (pid && (r.status === 0 || parsePageId(r.stdout) || !isDeterministic(lastErr))) {
+ throw neverRetriedError(
+ `pac genpage upload for '${label}' failed (${lastErr}) — the UPDATE of page ${pid} MAY HAVE LANDED: `
+ + (parsePageId(r.stdout)
+ ? 'pac had printed the Page ID, which it does once the page and its messages are written, so the failure came while it was publishing. '
+ : 'pac writes the page, then records the prompt and the agent message, then publishes, so the failure can have come after any of those. ')
+ + 'It was NOT sent again: a second send can record the prompt twice, and would overwrite a change made to the page since. '
+ + lookFirst(pid, 'failed')
+ );
+ }
if (isDeterministic(lastErr)) break;
if (i < attempts - 1) await sleep(500 * (i + 1));
}
@@ -545,14 +801,29 @@ function makeGenpageCli(env, deps = {}) {
enumerateEnv() {
return enumerateEnv();
},
+ // Ends every pac run this client started that has not finished, with the whole process tree of each (see runPac), and
+ // keeps every call that is still going — one paused between two attempts, say — from starting another (see runForCall).
+ // A call that begins afterwards is not affected: the client stays usable.
+ abort() {
+ abortEpoch += 1;
+ for (const controller of [...inFlight]) controller.abort();
+ },
// Download page CONTENT into `outputDir/<pageId>/{page.tsx,page.js,config.json,prompt.txt}`. With
// `pageIds` (non-empty) pull exactly those pages via `--page-id <comma>` — the sitemap's id set,
// so download is headless-free and fetches only real app content. Omit `pageIds` to download all
// app pages (back-compat for any legacy caller that does not provide the sitemap id set).
async download({ appId, outputDir, pageIds }) {
+ // A single run today; a retry added here must make its runs with this `run`, which starts none once abort() has come.
+ const run = runForCall();
const args = ['model', 'genpage', 'download', '--environment', env, '--app-id', appId, '--output-directory', outputDir];
if (pageIds && pageIds.length) args.push('--page-id', pageIds.join(','));
- const r = await run(args);
+ // Read only, so a call that times out is simply made again (once); any other failure is reported at once, as it always was.
+ let r;
+ for (let i = 0; i < TIMED_OUT_ATTEMPTS; i += 1) {
+ r = await run(args, budget('download'));
+ if (!r.timedOut) break;
+ if (i < TIMED_OUT_ATTEMPTS - 1) await sleep(500 * (i + 1));
+ }
if (r.status !== 0) throw new Error(`pac genpage download failed: ${pacDiagnostic(r)}`);
return true;
},
diff --git a/plugins/model-apps/scripts/lib/griffel-styles.js b/plugins/model-apps/scripts/lib/griffel-styles.js
new file mode 100644
index 000000000..3aaf2a953
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/griffel-styles.js
@@ -0,0 +1,1353 @@
+'use strict';
+// Finds the style keys Griffel drops at runtime in a generated page's `makeStyles` calls (AB#6691124).
+//
+// WHY THIS EXISTS. The pages use @fluentui/react-components, whose styles are Griffel's. Griffel does not support a few CSS shorthands: `resolveStyleRules` skips
+// the property and, in the browser, logs
+// @griffel/react: You are using unsupported shorthand CSS property "borderWidth". Please check your "makeStyles" calls, there *should not* be following: ...
+// Nothing earlier notices. The page type-checks, `pac model genpage transpile` does not execute `makeStyles`, and the deploy succeeds — the page then renders
+// without the border, the colour or the reset the author wrote. The only guard used to be an agent grepping the page for `borderWidth`, which covers one of the
+// ten properties and, as a text search, reads a string, a comment and an inline `style={{ … }}` the same as a style key.
+//
+// The set is Griffel's own UNSUPPORTED_CSS_PROPERTIES (packages/core/src/constants.ts in https://github.com/microsoft/griffel, read from @griffel/core 1.19 and
+// 1.20): exactly these ten. Griffel's guide describes the limit for three of them, `borderColor`, `borderStyle` and `borderWidth`, and suggests its `shorthands.*`
+// helpers (https://griffel.js.org/react/guides/limitations, "Some of CSS shorthands are not supported"); the page its runtime message points to is
+// https://aka.ms/griffel-css-shorthands. Every other shorthand (`padding`, `margin`, `border`, `gap`, `borderRadius`, `outline`, …) IS supported
+// and is not reported. The check is deliberately this narrow: a key Griffel accepts must never be refused.
+//
+// WHAT IS CHECKED, and what is not:
+// * `makeStyles({ <slot>: { <key>: <value>, … } })` — every key of every slot's style object, at any depth: `':hover'`, `'@media …'`, `'& .child'` and the other
+// nested selectors and at-rules are style objects too, and resolveStyleRules checks each (the check runs on the key alone, before the value is looked at).
+// The slot names themselves are not properties and are not checked: a slot may be called `all`.
+// * An object written inline in a spread — `...(narrow && { borderColor: 'red' })` — is a style object once Griffel has spread it, so it is read too.
+// * The value of `animationName` in a style object is NOT a style object: its keyframes are serialized as written (compileKeyframeRule), so
+// `from: { borderColor: … }` is fine there and is not reported. A SLOT called `animationName` is a slot like any other, and its object is read.
+// * `makeResetStyles` is NOT checked, though the work item names it. Its keys are written to one CSS rule as they stand (resolveResetStyleRules →
+// createStringFromStyles, which never imports UNSUPPORTED_CSS_PROPERTIES), and the unsupported set is consulted only by resolveStyleRules, which makeStyles calls
+// and makeResetStyles does not — verified by running both over `borderColor: 'red'`: makeStyles drops it, makeResetStyles emits `border-color:red;`. Reporting
+// those keys would refuse a page that works. To check it too, add `['makeResetStyles', { slots: false }]` to STYLE_FUNCTIONS: its argument is one style object, with no slots.
+// * Inline React styles (`style={{ borderColor: … }}`) are not Griffel at all — the browser's own CSS handles them — and are not reported; rules.md recommends them.
+// `...shorthands.borderColor('red')` is Fluent's helper that expands to longhands; it is a call, not a key, and is not reported.
+// * The same names in a string, a comment, a template literal or a regex are text, not keys, and are not reported.
+// The keys have to be written where the checker can see them, and a style object it cannot see is never reported as clean. `makeStyles(styles)` — an object built
+// elsewhere — a slot or a nested selector whose object is a variable (`root: base`, `':hover': hover`), and a spread of anything but an object written inline
+// (`...base`, `...helper()`) are each an `unread-style-object` problem: the keys behind them may be any of the ten, and a gate that let them through would deploy
+// exactly what it exists to stop. Written inline, the same keys are checked, so the remedy is always to write them there. So is a getter that runs, whatever key
+// it defines (`get root() { return … }`, `get color() { … }`): Griffel calls it as it reads the key, and a spread as it copies its object, and its body is code the
+// check does not read, which may return any value and change what else its object holds before Griffel reads that (ranGetter). And so is a computed key the check
+// cannot read as one string (`[key]`, `['border' + 'Width']`), which may name any of the ten, or a selector whose object it does not read — unless it is a template
+// whose text before its first `${` no one of the ten begins with (`--${name}`, `& .${className}`, `@media (min-width: ${width}px)`): what that names can be told
+// from its start, and the object under one that starts as Griffel's nested keys do (`:`, `[`, `>`, `&`, `@`) is read as any selector's is. What a spread or a
+// prototype (`__proto__: { … }`) brings into an object is read at that object's level — slots beside slots — because Griffel's `for … in` sees it there, and an
+// object is resolved as JavaScript resolves it (heldMembers): a key's last definition is the property, own keys hide inherited ones, a spread copies only its
+// object's own keys, and a key is the string JavaScript makes of it (a CR LF or a lone CR written in a template is one LF, however the file ends its lines; U+2028
+// and U+2029 stay as written), so a definition the check can prove never reaches Griffel is not checked, while one it cannot (a spread a condition chooses, a key
+// computed at run time) is. A function member — a getter, a setter or a method — ends where its body closes, not at a comma of its type parameters or return type.
+// A value is read when it is an object literal
+// or object literals chosen by a condition — `cond && { … }`, `cond ? { … } : { … }` — through what changes nothing at run time: parentheses, a non-null `!`, and
+// `as`/`satisfies` with a type the check reads — `as const`, or a type name with or without type arguments (typeEnd; no page wrote a cast in makeStyles at all) —
+// after which what follows is code again (`x as T && y` can be `y`). Any other type leaves the value unread, so a type is never read as a value; `a || b`, which
+// can be `a`, is not read either. The call's own argument is read the same way. Two spreads are read as safe without their keys, alone or chosen by a condition,
+// both only as VALUE imports from a Griffel module that the page never declares again (a parameter or a variable of the same name takes the trust away; a read of
+// it after `=` or `typeof` does not): Fluent's `shorthands.*(…)`, which writes the longhands and is the remedy itself (https://griffel.js.org/react/api/shorthands),
+// and `typographyStyles.*`, whose every entry is `fontFamily`, `fontSize`, `fontWeight` and `lineHeight`
+// (https://github.com/microsoft/fluentui/blob/master/packages/tokens/src/global/typographyStyles.ts) — each by its own export names only (STYLE_HELPERS), never by a
+// name it inherits: `shorthands.constructor(x)` is `Object(x)`, which hands x back as it is; and `shorthands.transition` only where it builds its own array, since given
+// one array it returns what that array's own `reduce` returns. MEASURED before this rule: across 59 distinct pages that call
+// `makeStyles` — the plugin's samples, eval fixtures and pages generated on real environments — no style object was written anywhere but inline, no key was
+// computed, no getter was written, and the only spreads in `makeStyles` were `shorthands.*(…)`.
+//
+// WHAT CODE CAN CHANGE. The check reads what the style objects hold as written, and code written in them changes that only through the object it runs on: a
+// getter's `this` is the object Griffel is reading, or the one a spread is copying, so a getter that runs there is reported (ranGetter). Code that writes shared
+// state — `Object.prototype.borderWidth = …`, a property of an import such as `typographyStyles.body1`, a variable — changes what every object holds, as a
+// statement anywhere else in the page could, and no check of the style objects can see it; the check does not follow it, wherever it runs (a getter's body, a
+// Proxy's trap or a `toString` that Griffel calls on a fallback value, a template's substitution). So a getter whose object never reaches Griffel — in a value a
+// later definition replaces, in a prototype a spread does not copy, in an animation's keyframes — is not reported, even where a spread has run it: what it can
+// change there is that object alone. The gate checks what a page asks Griffel for; it is not a sandbox for code written to get past it.
+//
+// WHICH `makeStyles`. The unaliased name; any name the page imports it under from a Griffel module (`import { makeStyles as ms } from '@fluentui/react-components'`);
+// and `<ns>.makeStyles` for a namespace import of one. A `makeStyles` imported from anywhere else is somebody else's function and is left alone. A local function that
+// happens to be named `makeStyles` and is not imported is not told apart from Griffel's — nothing in a page does that.
+//
+// HOW IT READS THE SOURCE. With the plugin's own lexer (source-literals.js), not a second tokenizer: blankLiterals gives a mask of the file in which every
+// comment, string body, template, regex and run of JSX text is blank and every offset is the original's, so a key is found where code has one and a quoted key is
+// read back from the source at the same offsets. The lexer is a lexer, not a parser, and where it guesses what a `/` or `<` is it says so (`onAmbiguity`): the checker
+// takes the earliest such offset as a frontier — the trust frontier the navigation oracle uses (pageref-resolver.js) — and does not trust a call that reaches it, or
+// a `makeStyles(` in the raw text at or after it that the mask shows as text, which a wrong guess may have blanked: see `unverifiable-style-call` below.
+const { blankLiterals, blankNonCodePreservingTemplateExpressions, isTrivia, trimTrivia, WS } = require('./source-literals.js');
+
+// Griffel's UNSUPPORTED_CSS_PROPERTIES, each with the longhands to write instead. The logical-property shorthands expand to the width, style and colour of
+// each side, because those are the longhands CSS defines for them (border-block-start-width, …); `all` is every property, so it has no longhand list.
+const SIDES = ['Top', 'Right', 'Bottom', 'Left'];
+const logical = (edge) => ['Width', 'Style', 'Color'].map((part) => `border${edge}${part}`);
+const UNSUPPORTED_GRIFFEL_SHORTHANDS = new Map([
+ ['all', []],
+ ['borderColor', SIDES.map((side) => `border${side}Color`)],
+ ['borderStyle', SIDES.map((side) => `border${side}Style`)],
+ ['borderWidth', SIDES.map((side) => `border${side}Width`)],
+ ['borderBlock', [...logical('BlockStart'), ...logical('BlockEnd')]],
+ ['borderBlockStart', logical('BlockStart')],
+ ['borderBlockEnd', logical('BlockEnd')],
+ ['borderInline', [...logical('InlineStart'), ...logical('InlineEnd')]],
+ ['borderInlineStart', logical('InlineStart')],
+ ['borderInlineEnd', logical('InlineEnd')],
+]);
+
+// The packages that export Griffel's makeStyles: `@fluentui/react-components` re-exports it from `@griffel/react`, which wraps `@griffel/core`.
+const GRIFFEL_MODULES = new Set(['@fluentui/react-components', '@griffel/react', '@griffel/core']);
+
+// The Griffel functions whose style objects are read, by the name they are exported under. `slots` says the argument is an object of slots, each holding a style
+// object (makeStyles); see the header for why makeResetStyles is not here.
+const STYLE_FUNCTIONS = new Map([['makeStyles', { slots: true }]]);
+
+// The Griffel-module exports a style object may be SPREAD from without its keys being read (see the header): `call` is spread as a call (`...shorthands.borderColor('red')`),
+// `member` as a member (`...typographyStyles.body1`), and only by a name in `members`, the helper's own exports. Each helper is a plain object, so it also answers to the
+// names it inherits from Object.prototype, and those are not helpers: `shorthands.constructor(x)` is `Object(x)`, which hands x back unexpanded, keys, getters and all.
+// `shorthands`: Griffel's 23 helpers, each of which writes longhands from the values it is given (https://github.com/microsoft/griffel/blob/main/packages/core/src/shorthands/index.ts;
+// the same 23 in @griffel/core 1.20.3, which Fluent 9 re-exports) — but `transition` given ONE argument that is an array returns what that array's own `reduce`
+// returns (its normalizeTransitionInputs hands the array on: https://github.com/microsoft/griffel/blob/main/packages/core/src/shorthands/transition.ts), and an array
+// can bring its own `reduce` (`new (class extends Array { reduce() { … } })()`), so `transition` is `guarded`: trusted only where it builds its own array
+// (transitionBuildsItsOwnArray). `typographyStyles`: Fluent 9's 17 entries (the header's link). A name either one gains later is held until it is added here, as any
+// spread the check cannot read is. Trusted only under a name imported from a Griffel module, or through a namespace import of one — never by the bare name, which a
+// page could bind to anything.
+const STYLE_HELPERS = new Map([
+ ['shorthands', {
+ kind: 'call',
+ members: new Set(['border', 'borderLeft', 'borderBottom', 'borderRight', 'borderTop', 'borderColor', 'borderStyle', 'borderRadius', 'borderWidth', 'flex', 'gap',
+ 'gridArea', 'margin', 'marginBlock', 'marginInline', 'padding', 'paddingBlock', 'paddingInline', 'overflow', 'inset', 'outline', 'transition', 'textDecoration']),
+ guarded: new Set(['transition']),
+ }],
+ ['typographyStyles', {
+ kind: 'member',
+ members: new Set(['body1', 'body1Strong', 'body1Stronger', 'body2', 'caption1', 'caption1Strong', 'caption1Stronger', 'caption2', 'caption2Strong', 'subtitle1',
+ 'subtitle2', 'subtitle2Stronger', 'title1', 'title2', 'title3', 'largeTitle', 'display']),
+ }],
+]);
+
+const IDENTIFIER_SOURCE = '[\\p{ID_Start}$_][\\p{ID_Continue}$\\u200c\\u200d]*';
+const ID_START = /[\p{ID_Start}$_]/u;
+const ID_PART = /[\p{ID_Continue}$\u200c\u200d]/u;
+const IDENTIFIER = new RegExp(IDENTIFIER_SOURCE, 'uy');
+const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+
+// ─── Source positions ───────────────────────────────────────────────────────────────────────────────────────────────────────────
+// A line ends at LF, CR LF or a lone CR, and a column is in UTF-16 units, as an editor counts them, so a report names the place a maker sees in the file.
+function lineStarts(src) {
+ const starts = [0];
+ for (const m of src.matchAll(/\r\n|\r|\n/g)) starts.push(m.index + m[0].length);
+ return starts;
+}
+function locate(starts, at) {
+ let lo = 0;
+ let hi = starts.length - 1;
+ while (lo < hi) {
+ const mid = (lo + hi + 1) >> 1;
+ if (starts[mid] <= at) lo = mid;
+ else hi = mid - 1;
+ }
+ return { line: lo + 1, column: at - starts[lo] + 1 };
+}
+
+// ─── Reading the mask ───────────────────────────────────────────────────────────────────────────────────────────────────────────
+// The matching bracket of every `{`, `(` and `[` and of every `}`, `)` and `]` (-1 where there is none), computed once. Each kind has its own stack, so a stray
+// `)` cannot unbalance a brace. The mask holds no bracket from a string, comment, template or regex, so every bracket in it is code.
+function matchBrackets(mask) {
+ const match = new Int32Array(mask.length).fill(-1);
+ const stacks = { '{': [], '(': [], '[': [] };
+ const openOf = { '}': '{', ')': '(', ']': '[' };
+ for (let i = 0; i < mask.length; i += 1) {
+ const c = mask[i];
+ if (stacks[c]) stacks[c].push(i);
+ else if (openOf[c]) {
+ const open = stacks[openOf[c]].pop();
+ if (open !== undefined) { match[open] = i; match[i] = open; }
+ }
+ }
+ return match;
+}
+
+function skipSpace(mask, i) {
+ while (i < mask.length && isTrivia(mask[i])) i += 1;
+ return i;
+}
+// The index of the last character before `i` that is not white space (the mask holds a comment as white space), or -1.
+function previousSignificant(mask, i) {
+ let j = i - 1;
+ while (j >= 0 && isTrivia(mask[j])) j -= 1;
+ return j;
+}
+
+function readIdentifier(mask, i) {
+ IDENTIFIER.lastIndex = i;
+ const m = IDENTIFIER.exec(mask);
+ return m ? { name: m[0], end: i + m[0].length } : null;
+}
+// The identifier that ends right before `end`, as { name, start }, or null.
+function identifierEndingAt(mask, end) {
+ let start = end;
+ while (start > 0 && ID_PART.test(mask[start - 1])) start -= 1;
+ if (start === end || !ID_START.test(mask[start])) return null;
+ return { name: mask.slice(start, end), start };
+}
+// The index just past the `>` that closes the type arguments whose `<` is at `i` (the `>` of an arrow `=>` is not one), or the end of the mask when they never close.
+function skipTypeArguments(mask, i) {
+ let depth = 0;
+ for (let k = i; k < mask.length; k += 1) {
+ if (mask[k] === '<') depth += 1;
+ else if (mask[k] === '>' && mask[k - 1] !== '=') {
+ depth -= 1;
+ if (depth === 0) return k + 1;
+ }
+ }
+ return mask.length;
+}
+
+// The value of the string literal src[from, to) — quotes included — with JavaScript's escapes read as JavaScript reads them, or null when it is not a complete
+// literal or holds a malformed escape. A quoted key is read from the source, because the mask blanks every string body.
+function decodeStringLiteral(src, from, to) {
+ const quote = src[from];
+ if ((quote !== '"' && quote !== "'" && quote !== '`') || src[to - 1] !== quote) return null;
+ const simple = { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', v: '\v', 0: '\0' };
+ let value = '';
+ for (let i = from + 1; i < to - 1; i += 1) {
+ const c = src[i];
+ // A line break written in a template is read as JavaScript reads it: CR LF and a lone CR are each one LF (a template character's TV is the TRV of its
+ // LineTerminatorSequence, https://tc39.es/ecma262/#sec-static-semantics-trv), so a key that a file saved with CRLF breaks across lines is the key a quoted
+ // '\n' names, not the one '\r\n' names. U+2028 and U+2029 are kept as written, in a template and in a string alike (a string may hold them as written since
+ // ES2019, though never a CR or an LF); a backslash before any line break is a continuation, which adds nothing (read below).
+ if (c === '\r') {
+ value += '\n';
+ if (src[i + 1] === '\n') i += 1;
+ continue;
+ }
+ if (c !== '\\') { value += c; continue; }
+ i += 1;
+ const e = src[i];
+ if (e === '\r' && src[i + 1] === '\n') { i += 1; continue; }
+ if (e === '\n' || e === '\r' || e === '\u2028' || e === '\u2029') continue; // a line continuation adds no character
+ if (e === 'x') {
+ const hex = src.slice(i + 1, i + 3);
+ if (!/^[0-9A-Fa-f]{2}$/.test(hex)) return null;
+ value += String.fromCharCode(parseInt(hex, 16));
+ i += 2;
+ } else if (e === 'u') {
+ if (src[i + 1] === '{') {
+ const close = src.indexOf('}', i + 2);
+ const hex = close === -1 ? '' : src.slice(i + 2, close);
+ if (close === -1 || close >= to - 1 || !/^[0-9A-Fa-f]{1,6}$/.test(hex) || parseInt(hex, 16) > 0x10ffff) return null;
+ value += String.fromCodePoint(parseInt(hex, 16));
+ i = close;
+ } else {
+ const hex = src.slice(i + 1, i + 5);
+ if (!/^[0-9A-Fa-f]{4}$/.test(hex)) return null;
+ value += String.fromCharCode(parseInt(hex, 16));
+ i += 4;
+ }
+ } else {
+ value += Object.prototype.hasOwnProperty.call(simple, e) ? simple[e] : e;
+ }
+ }
+ return value;
+}
+
+// ─── Which calls are Griffel's ──────────────────────────────────────────────────────────────────────────────────────────────────
+// The names a page gives Griffel's style functions, from its import declarations. Shapes, in the mask (a module name is a blanked string there, so it is read from
+// the source at the same offsets):
+// import { makeStyles, tokens } from '@fluentui/react-components'; → makeStyles
+// import { makeStyles as ms, type GriffelStyle } from '@griffel/react'; → ms
+// import * as Fluent from '@fluentui/react-components'; → Fluent.makeStyles(…)
+// import { makeStyles } from './styles'; → not Griffel's: the bare name is somebody else's here
+// import './styles.css'; import('x'); import.meta → no names
+// `local` maps a name to the function it is — the unaliased names unless the page imports THAT name from a module that is not Griffel's — `namespaces` holds the
+// local names of `import * as <ns>` from a Griffel module, and `helpers` maps a name imported from a Griffel module to its STYLE_HELPERS entry, with
+// `helperNamespaces` the namespaces a helper may be reached through. A helper is trusted only as a VALUE import (not `import type`, not a `type` specifier: those
+// bind nothing at run time) and only when the page uses the name nowhere but as `name.member` outside its import (onlyMemberUse): a parameter, a variable or a
+// destructured name that declares it again is a use of another kind, so a page that rebinds the name loses the trust instead of lending it to its own object.
+const FROM_QUOTE = new RegExp(`\\bfrom${WS}*(["'])`, 'g');
+const NAMESPACE_IMPORT = new RegExp(`\\*${WS}*as${WS}+(${IDENTIFIER_SOURCE})`, 'u');
+const AS_SEPARATOR = new RegExp(`${WS}+as${WS}+`);
+const TYPE_PREFIX = new RegExp(`^type${WS}+(?=${IDENTIFIER_SOURCE})`, 'u');
+// `import type { … }`, `import type * as ns`, `import type Name` — but not `import type from '…'`, whose default import is named `type`.
+const TYPE_ONLY_CLAUSE = new RegExp(`^type${WS}*(?:[{*]|${WS}${IDENTIFIER_SOURCE})`, 'u');
+function styleFunctionBindings(mask, src) {
+ const local = new Map(STYLE_FUNCTIONS);
+ const namespaces = new Set();
+ const helpers = new Map();
+ const helperNamespaces = new Set();
+ const imports = [];
+ const importRe = /\bimport\b/g;
+ for (let m = importRe.exec(mask); m; m = importRe.exec(mask)) {
+ const before = previousSignificant(mask, m.index);
+ if (before >= 0 && mask[before] === '.') continue; // a property named import
+ const clauseStart = skipSpace(mask, m.index + m[0].length);
+ if (['(', '.', '"', "'"].includes(mask[clauseStart])) continue;
+ // The clause runs to the `from` that is followed by the module's quote.
+ FROM_QUOTE.lastIndex = clauseStart;
+ const from = FROM_QUOTE.exec(mask);
+ if (!from) continue;
+ const clause = mask.slice(clauseStart, from.index);
+ // A clause holds no `;` or `=`: a match that crossed one found the `from` of some later statement.
+ if (/[;=]/.test(clause)) continue;
+ const quoteAt = from.index + from[0].length - 1;
+ const close = mask.indexOf(from[1], quoteAt + 1);
+ if (close === -1) continue;
+ imports.push([m.index, close + 1]);
+ const moduleName = decodeStringLiteral(src, quoteAt, close + 1);
+ const griffel = moduleName !== null && GRIFFEL_MODULES.has(moduleName);
+ const typeOnly = TYPE_ONLY_CLAUSE.test(trimTrivia(clause));
+ const namespace = NAMESPACE_IMPORT.exec(clause);
+ if (namespace && griffel) {
+ namespaces.add(namespace[1]);
+ if (!typeOnly) helperNamespaces.add(namespace[1]);
+ }
+ const named = /\{([^}]*)\}/.exec(clause);
+ if (!named) continue;
+ for (const part of named[1].split(',')) {
+ // `GriffelStyle`, `type GriffelStyle`, `makeStyles`, `makeStyles as ms`: the imported name, and the name it is bound to.
+ const specifier = trimTrivia(part);
+ const typeSpecifier = TYPE_PREFIX.test(specifier);
+ const words = specifier.replace(TYPE_PREFIX, '').split(AS_SEPARATOR);
+ const imported = trimTrivia(words[0] || '');
+ const bound = trimTrivia(words[1] || words[0] || '');
+ if (!bound) continue;
+ if (STYLE_FUNCTIONS.has(imported) && griffel) local.set(bound, STYLE_FUNCTIONS.get(imported));
+ else if (STYLE_FUNCTIONS.has(bound)) local.delete(bound); // the bare name is bound to something that is not Griffel's
+ if (STYLE_HELPERS.has(imported) && griffel && !typeOnly && !typeSpecifier) helpers.set(bound, STYLE_HELPERS.get(imported));
+ else helpers.delete(bound); // a later import of another module's export, or of a type, under that name takes it back
+ }
+ }
+ for (const name of [...helpers.keys()]) if (!onlyMemberUse(mask, name, imports)) helpers.delete(name);
+ for (const name of [...helperNamespaces]) if (!onlyMemberUse(mask, name, imports)) helperNamespaces.delete(name);
+ return { local, namespaces, helpers, helperNamespaces };
+}
+
+// Whether every use of `name` in the code, outside the import statements in `skip` ([start, end) pairs), is a member access — `name.x` — or a read that cannot declare it:
+// after `=` or `typeof`. Declaring the name again is always a use of another kind where it is declared (`(name)`, `name:`, `name =`, `{ name }`, `function name(`), so a
+// name that passes is bound to its import wherever it is read; `x.name` is a property of something else and is not a use; `...name` and `name?.x` are uses of another
+// kind, and fail it.
+function onlyMemberUse(mask, name, skip) {
+ const re = new RegExp(`(?<![\\p{ID_Continue}$\\u200c\\u200d])${escapeRegExp(name)}(?![\\p{ID_Continue}$\\u200c\\u200d])`, 'gu');
+ for (let m = re.exec(mask); m; m = re.exec(mask)) {
+ if (skip.some(([a, b]) => m.index >= a && m.index < b)) continue;
+ const before = previousSignificant(mask, m.index);
+ if (before >= 0 && mask[before] === '.' && mask[before - 1] !== '.') continue;
+ // Read where it stands, never declared there: after `=` (`const { Button } = Fluent`, a default value, a comparison) — unless `=>` follows, which makes it an
+ // arrow function's parameter (`= shorthands => …`), a declaration — and after `typeof` (a type query, or the operator).
+ const after = skipSpace(mask, m.index + name.length);
+ const arrowParameter = mask[after] === '=' && mask[after + 1] === '>';
+ if (before >= 0 && mask[before] === '=' && !arrowParameter) continue;
+ const word = before >= 0 ? identifierEndingAt(mask, before + 1) : null;
+ if (word && word.name === 'typeof') continue;
+ if (mask[after] !== '.') return false;
+ }
+ return true;
+}
+
+// Whether the name at `at` is the name of a function declaration — `function makeStyles(…) {…}`, `function* makeStyles(…)` — which is not a call.
+function declaresFunction(mask, at) {
+ let end = previousSignificant(mask, at) + 1;
+ if (end > 0 && mask[end - 1] === '*') end = previousSignificant(mask, end - 1) + 1;
+ const word = identifierEndingAt(mask, end);
+ return word !== null && word.name === 'function';
+}
+
+// Every call to a Griffel style function, as { spec, nameAt, callee, open, close, objectOpen, objectClose, argFrom, argTo }: `nameAt` is where the function's name is and `callee`
+// where the call starts (`Fluent.makeStyles(` starts at `Fluent`); `open` and `close` are the call's parentheses and `objectOpen` and `objectClose` the braces of the
+// inline object that is its first argument — -1 where that is not an object literal, and `close` is -1 where the call is never closed; [argFrom, argTo) is the first
+// argument, whatever it is. A name is read whole
+// (`notmakeStyles` is another name) and as a member only of a Griffel namespace import (`this.makeStyles(…)` is not Griffel's). TypeScript type arguments are
+// skipped: `makeStyles<'root'>({ … })`. A call with no argument reads nothing and is left out.
+function styleFunctionCalls(mask, src, match, angles) {
+ const { local, namespaces } = styleFunctionBindings(mask, src);
+ const calls = [];
+ const names = new RegExp(IDENTIFIER_SOURCE, 'gu');
+ for (let m = names.exec(mask); m; m = names.exec(mask)) {
+ const name = m[0];
+ // The name alone decides first: nearly every identifier of a page is something else, and each check below reads the text around it.
+ if (!local.has(name) && !STYLE_FUNCTIONS.has(name)) continue;
+ const prev = previousSignificant(mask, m.index);
+ let spec;
+ let callee = m.index;
+ if (prev >= 0 && mask[prev] === '.' && mask[prev - 1] !== '.') {
+ // `<ns>.makeStyles(` or `<ns>?.makeStyles(`. Three dots are a spread (`...makeStyles(…)`), handled as a bare name below.
+ spec = STYLE_FUNCTIONS.get(name);
+ const dot = mask[prev - 1] === '?' ? prev - 1 : prev;
+ const receiver = identifierEndingAt(mask, previousSignificant(mask, dot) + 1);
+ if (!spec || !receiver || !namespaces.has(receiver.name)) continue;
+ // `a.ns.makeStyles(`: `ns` is a property of `a` there, not the namespace import.
+ const beforeReceiver = previousSignificant(mask, receiver.start);
+ if (beforeReceiver >= 0 && mask[beforeReceiver] === '.' && mask[beforeReceiver - 1] !== '.') continue;
+ callee = receiver.start;
+ } else {
+ spec = local.get(name);
+ if (!spec || declaresFunction(mask, m.index)) continue;
+ }
+ let k = skipSpace(mask, m.index + name.length);
+ if (mask[k] === '<') k = skipSpace(mask, skipTypeArguments(mask, k));
+ if (mask[k] !== '(') continue;
+ const first = skipSpace(mask, k + 1);
+ if (mask[first] === ')') continue;
+ const objectOpen = mask[first] === '{' ? first : -1;
+ const close = match[k];
+ calls.push({ spec, nameAt: m.index, callee, open: k, close, objectOpen, objectClose: objectOpen === -1 ? -1 : match[objectOpen],
+ argFrom: first, argTo: close === -1 ? -1 : expressionEnd(mask, match, angles, first, close) });
+ }
+ return calls;
+}
+
+// The `,` that ends the expression starting at `from` inside a bracket group that closes at `close` — a member of an object, an argument of a call — or `close`. A
+// bracket group is jumped through the match table and a string through its closing quote. The type of an `as` or `satisfies` is jumped whole (typeEnd), so its own
+// commas (`{ … } as Record<string, T>`) do not end the expression; where the text after one does not read as a type, nothing is jumped, and the next comma ends it.
+function expressionEnd(mask, match, angles, from, close) {
+ let k = from;
+ while (k < close) {
+ const ch = mask[k];
+ if (ch === ',') return k;
+ if (ch === '{' || ch === '(' || ch === '[') {
+ const closer = match[k];
+ k = closer === -1 || closer > close ? close : closer + 1;
+ } else if (ch === '"' || ch === "'" || ch === '`') {
+ let end = k + 1;
+ while (end < close && mask[end] !== ch) end += 1;
+ k = end >= close ? close : end + 1;
+ } else if (ID_START.test(ch) && !ID_PART.test(mask[k - 1] || '')) {
+ const id = readIdentifier(mask, k);
+ if (!id) { k += 1; continue; }
+ if ((id.name === 'as' || id.name === 'satisfies') && mask[previousSignificant(mask, k)] !== '.') {
+ const end = typeEnd(mask, angles, id.end, close);
+ k = end === -1 ? id.end : end;
+ continue;
+ }
+ k = id.end;
+ } else {
+ k += 1;
+ }
+ }
+ return close;
+}
+
+// How deep a style value or object may nest before the check stops reading it — far deeper than any page writes one (a few levels) — so that a pathological page gets
+// an answer, not an exhausted stack: past it, a value is unread and an object is reported as one the check does not read.
+const MAX_STYLE_DEPTH = 64;
+// A line terminator, which ends a type before `<` (TypeScript reads `T\n<` as a comparison).
+const LINE_BREAK = /[\n\r\u2028\u2029]/;
+// The types TypeScript reads with no type arguments (parseNonArrayType in https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts): a keyword
+// type unless a `.` follows it, which makes it the first name of a dotted type reference (parseKeywordAndNoDot); and always `void`, the literal types `null`, `true`
+// and `false`, `this`, and the `const` of `as const`. After one of them a `<` is a comparison — `size as number < 5 ? a : b` is `(size as number) < 5 ? a : b` — so
+// it is never jumped as type arguments: a jump there ran on to whatever `>` came later, across the members between.
+const KEYWORD_TYPES = new Set(['any', 'unknown', 'string', 'number', 'bigint', 'symbol', 'boolean', 'undefined', 'never', 'object']);
+const ARGUMENTLESS_TYPES = new Set(['const', 'void', 'null', 'true', 'false', 'this']);
+
+// The `>` that closes each `<` as type arguments would — `<` and `>` counted as brackets from that `<` on, `=>` not a closer — or -1, computed once. A `<` that a
+// comparison leaves open does not keep a later one from closing (each `>` closes the latest open `<`, which is the one a count from that `<` would close at), and a
+// type's arguments are looked up rather than scanned for: a scan from each cast to the end of the object made a page of casts quadratic. The mask holds no `<` or
+// `>` of a string, comment, template or regex.
+function matchAngles(mask) {
+ const match = new Int32Array(mask.length).fill(-1);
+ const open = [];
+ for (let i = 0; i < mask.length; i += 1) {
+ if (mask[i] === '<') open.push(i);
+ else if (mask[i] === '>' && mask[i - 1] !== '=' && open.length) match[open.pop()] = i;
+ }
+ return match;
+}
+
+// Where the type of an `as` or a `satisfies` that starts at `from` ends (exclusive), or -1. Only the forms a page writes are read — `const`, and a name, maybe
+// dotted, maybe with type arguments (`GriffelStyle`, `Fluent.GriffelStyle`, `Record<string, GriffelStyle>`); measured, none of 59 distinct pages that call makeStyles
+// (samples, eval fixtures, pages generated on real environments) wrote a cast inside the call at all. Type arguments are jumped as a run of balanced `<` and `>`
+// (matchAngles; a string or template is blank between its quotes in the mask, so `Record<'>', T>` counts no quoted `>`) that must close inside the range; what they
+// hold is the type's. A type that takes none (KEYWORD_TYPES, ARGUMENTLESS_TYPES) ends at its word. And a type is taken to end only where what follows cannot
+// continue it, as TypeScript reads one (parsePostfixTypeOrHigher in parser.ts): the end of the range, `,` `)` `]` `}` `;` `:`, `&&` `||` `??`, another `as` or
+// `satisfies`, or a `?` before what can start a type — a runtime conditional; TypeScript reads a `?` before anything else as part of the type. Any other type (a
+// union, an object, function or conditional type, an import type, …) or continuation (`[`, `|`, `extends`, `<` after a keyword, …) is -1, so the caller reads the
+// value as one it cannot see: a type is never taken to end where TypeScript would read on.
+function typeEnd(mask, angles, from, end) {
+ const at = (i) => skipSpace(mask, i);
+ const head = readIdentifier(mask, at(from));
+ if (!head) return -1;
+ let k = head.end;
+ const argumentless = ARGUMENTLESS_TYPES.has(head.name) || (KEYWORD_TYPES.has(head.name) && mask[at(k)] !== '.');
+ if (!argumentless) {
+ for (;;) {
+ const dot = at(k);
+ if (mask[dot] !== '.') break;
+ const next = readIdentifier(mask, at(dot + 1));
+ if (!next) return -1;
+ k = next.end;
+ }
+ const open = at(k);
+ if (mask[open] === '<' && !LINE_BREAK.test(mask.slice(k, open))) {
+ const close = angles[open];
+ if (close === -1 || close >= end) return -1;
+ k = close + 1;
+ }
+ }
+ const f = at(k);
+ if (f >= end) return k;
+ const c = mask[f];
+ const d = mask[f + 1];
+ if (c === ',' || c === ')' || c === ']' || c === '}' || c === ';' || c === ':') return k;
+ if ((c === '&' && d === '&') || (c === '|' && d === '|') || (c === '?' && d === '?')) return k;
+ if (c === '?' && d !== '.') {
+ const n = mask[at(f + 1)] || '';
+ return '{(["\'`-'.includes(n) || /[0-9]/.test(n) || ID_START.test(n) ? k : -1;
+ }
+ const word = readIdentifier(mask, f);
+ return word && (word.name === 'as' || word.name === 'satisfies') ? k : -1;
+}
+// ─── Style objects ──────────────────────────────────────────────────────────────────────────────────────────────────────────────
+// The members of the object literal whose `{` is at `open`, as { name, nameAt, spread, valueFrom, valueTo, head, keyText, getter, proto }: `name` is the key where it
+// is a name, a number or a string literal (null for a computed key that is not one), `nameAt` where the key starts in the source, and [valueFrom, valueTo) the value —
+// empty for a shorthand member (`{ borderColor }`), and the expression after the dots for a spread (`spread: true`, no name). A computed key also has `keyText`, as
+// written (`[key]`), and a template key with a substitution has `head`, its text before the first `${` — all that can be known of what it names (scanStyleObject).
+// `proto` marks `__proto__: …` written as a name or a string, which sets the object's prototype rather than a key: `for … in` reads what the prototype holds as
+// the object's own (https://tc39.es/ecma262/#sec-runtime-semantics-propertydefinitionevaluation; a computed `['__proto__']` and a shorthand are ordinary keys). A
+// getter is a member too (`getter: true`, the value its whole text): Griffel reads every slot and key with `for … in` and `obj[key]`, which calls it, so what it
+// returns is that key's value. A setter alone defines no value and a method's value is a function, which Griffel skips, so both are left out. Strings are blank
+// in the mask, so the next quote of the same kind closes one.
+function objectMembers(ctx, open) {
+ const { mask, src, match, angles } = ctx;
+ const close = match[open];
+ // The `,` that ends the member starting at `from`, or `close` (expressionEnd).
+ const memberEnd = (from) => expressionEnd(mask, match, angles, from, close);
+ const members = [];
+ let i = open + 1;
+ while (i < close) {
+ i = skipSpace(mask, i);
+ if (i >= close) break;
+ if (mask.startsWith('...', i)) {
+ const end = memberEnd(i + 3);
+ members.push({ name: null, nameAt: i, spread: true, valueFrom: i + 3, valueTo: end });
+ i = end + 1;
+ continue;
+ }
+ // A function member — `get x() {…}`, `set x(v) {…}`, `async x() {…}`, `async *x() {…}`, `*x() {…}` — is its prefix, then its name, written as any key's
+ // is and with or without space before it (`get['x']()`, `get.5()`), then its parameters. Only a getter defines a value Griffel reads.
+ const functionFrom = i;
+ let functionKind = null;
+ const word = readIdentifier(mask, i);
+ let next = -1;
+ if (word && (word.name === 'get' || word.name === 'set' || word.name === 'async')) {
+ next = skipSpace(mask, word.end);
+ if (word.name === 'async' && mask[next] === '*') next = skipSpace(mask, next + 1);
+ } else if (mask[i] === '*') {
+ next = skipSpace(mask, i + 1);
+ }
+ if (next !== -1 && startsKey(mask, next)) {
+ functionKind = word && word.name === 'get' ? 'getter' : 'function';
+ i = next;
+ }
+ let name = null;
+ let nameAt = i;
+ let afterName = i;
+ let head;
+ let keyText;
+ let numeric = false;
+ let shorthandAllowed = false;
+ const quote = mask[i];
+ if (quote === '"' || quote === "'") {
+ let end = i + 1;
+ while (end < close && mask[end] !== quote) end += 1;
+ if (end >= close) break;
+ name = decodeStringLiteral(src, i, end + 1);
+ afterName = end + 1;
+ } else if (quote === '[') {
+ // A computed key. Only one that is a single string literal — `['borderWidth']`, or a template without a substitution — has a name. A template WITH a
+ // substitution is named by its text as written, which holds its `${` and is never one of the ten names; what it can name is told by its `head`. Any other
+ // expression (`[key]`, `['border' + 'Width']`, `[('borderWidth')]`) has no name.
+ const closer = match[i];
+ if (closer === -1 || closer > close) { i = memberEnd(i) + 1; continue; }
+ keyText = src.slice(i, closer + 1);
+ const inner = skipSpace(mask, i + 1);
+ const q = mask[inner];
+ if (q === '"' || q === "'" || q === '`') {
+ let end = inner + 1;
+ while (end < closer && mask[end] !== q) end += 1;
+ if (end < closer && skipSpace(mask, end + 1) === closer) {
+ const substitution = q === '`' ? substitutionStart(src, inner, end) : -1;
+ if (substitution === -1) {
+ const literal = decodeStringLiteral(src, inner, end + 1);
+ if (literal !== null) { name = literal; nameAt = inner; }
+ } else {
+ // Only the head is text: what the substitutions hold is code (a nested `String.raw\`\u\`` is valid there and is no string escape), so the rest is not
+ // decoded. The head is decoded as the template's own text is (`\u0062order` is `border`); one that cannot be decoded tells nothing, as an empty one.
+ name = src.slice(inner + 1, end);
+ nameAt = inner;
+ head = decodeStringLiteral(`\`${src.slice(inner + 1, substitution)}\``, 0, substitution - inner + 1) ?? '';
+ }
+ }
+ }
+ afterName = closer + 1;
+ } else {
+ // A number is a key as well — `{ 0: { … } }` is a slot called "0" — and it is never one of the ten.
+ NUMERIC_KEY.lastIndex = i;
+ const number = NUMERIC_KEY.exec(mask);
+ if (number) {
+ name = number[0];
+ numeric = true;
+ afterName = i + number[0].length;
+ } else {
+ const id = readIdentifier(mask, i);
+ if (!id) { i = memberEnd(i) + 1; continue; }
+ name = id.name;
+ afterName = id.end;
+ shorthandAllowed = true;
+ }
+ }
+ const after = skipSpace(mask, afterName);
+ // A method's type parameters come between its name and its parameters (`fn<A, B>(…) {…}`): they are jumped whole, commas and all.
+ const params = mask[after] === '<' && angles[after] !== -1 && angles[after] < close ? skipSpace(mask, angles[after] + 1) : after;
+ if (functionKind) {
+ const end = functionEnd(ctx, params, close);
+ if (functionKind === 'getter') members.push({ name, nameAt, spread: false, valueFrom: functionFrom, valueTo: end, head, keyText, numeric, getter: true });
+ i = end + 1;
+ } else if (mask[after] === ':') {
+ const valueFrom = skipSpace(mask, after + 1);
+ const end = memberEnd(valueFrom);
+ members.push({ name, nameAt, spread: false, valueFrom, valueTo: end, head, keyText, numeric, proto: name === '__proto__' && keyText === undefined });
+ i = end + 1;
+ } else if (mask[params] === '(') {
+ i = functionEnd(ctx, params, close) + 1; // a method
+ } else if ((mask[after] === ',' || after >= close) && shorthandAllowed) {
+ // `{ borderColor }`: an unquoted key whose value is the variable of the same name — still a key named borderColor.
+ members.push({ name, nameAt, spread: false, valueFrom: after, valueTo: after });
+ i = after + 1;
+ } else {
+ i = memberEnd(after) + 1;
+ }
+ }
+ return members;
+}
+
+// A numeric literal where a key starts — decimal (`0`, `1.5`, `.5`, `1e3`, `1_000`), hexadecimal, octal or binary, or a BigInt (`1n`): what an object literal
+// takes as a key besides a name, a string and a computed key (https://tc39.es/ecma262/#prod-LiteralPropertyName).
+const NUMERIC_KEY = /(?:0[xX][0-9a-fA-F_]+|0[oO][0-7_]+|0[bB][01_]+|(?:\d[\d_]*(?:\.[\d_]*)?|\.\d[\d_]*)(?:[eE][-+]?\d[\d_]*)?)n?/y;
+
+// Whether a key starts at `i`: a name, a string, a number or a computed key.
+function startsKey(mask, i) {
+ NUMERIC_KEY.lastIndex = i;
+ return Boolean(readIdentifier(mask, i)) || '["\''.includes(mask[i] || ' ') || NUMERIC_KEY.test(mask);
+}
+
+// Where the function member whose parameters open at `paramsOpen` ends: the `,` after its body, or `close`. Its return type comes between the two and may hold
+// commas (`(): Map<A, B> {`), braces (`(): { a: string } {`) and brackets, so the end is not the first comma: it is the first `{ … }`, past bracket groups and a
+// type's arguments (matchAngles), that the next `,` — or the object's end — follows. A function member that does not read that way ends where its expression would.
+function functionEnd({ mask, match, angles }, paramsOpen, close) {
+ if (mask[paramsOpen] !== '(' || match[paramsOpen] === -1 || match[paramsOpen] >= close) return expressionEnd(mask, match, angles, paramsOpen, close);
+ let k = match[paramsOpen] + 1;
+ while (k < close) {
+ const c = mask[k];
+ if (c === '{' || c === '(' || c === '[') {
+ const end = match[k];
+ if (end === -1 || end >= close) return close;
+ if (c === '{') {
+ const next = skipSpace(mask, end + 1);
+ if (next >= close || mask[next] === ',') return Math.min(next, close);
+ }
+ k = end + 1;
+ } else if (c === '<' && angles[k] !== -1 && angles[k] < close) {
+ k = angles[k] + 1;
+ } else {
+ k += 1;
+ }
+ }
+ return close;
+}
+
+// Where the first substitution of the template whose opening back-tick is at `from` and closing one at `to` starts (its `$`), or -1. A `\${` is text, not a substitution.
+function substitutionStart(src, from, to) {
+ for (let k = from + 1; k < to; k += 1) {
+ if (src[k] === '\\') k += 1;
+ else if (src[k] === '$' && src[k + 1] === '{') return k;
+ }
+ return -1;
+}
+
+// The object literals written in [from, to): `{ … }` where an expression may start — after `(`, `,`, `[`, `:`, `?`, `=` or an operator — found through
+// parentheses, brackets, a ternary and a cast, but not inside one another (each is read, in its turn, for the ones it holds). A `{` after `)`, after `=>` or after
+// a word opens a block, not an object, and is skipped whole.
+function objectsIn({ mask, match }, from, to) {
+ const found = [];
+ let k = from;
+ while (k < to) {
+ const c = mask[k];
+ if (c === '"' || c === "'" || c === '`') {
+ let end = k + 1;
+ while (end < to && mask[end] !== c) end += 1;
+ k = end + 1;
+ } else if (c === '{') {
+ const closer = match[k];
+ if (closer === -1 || closer > to) break;
+ const before = previousSignificant(mask, k);
+ const prev = before < from ? '' : mask[before];
+ const block = prev === ')' || (prev === '>' && mask[before - 1] === '=') || ID_PART.test(prev);
+ if (!block) found.push(k);
+ k = closer + 1;
+ } else {
+ k += 1;
+ }
+ }
+ return found;
+}
+
+// A key's value as it is written, so that a key whose value CHANGED can be told from one that did not (griffelProblemsNotIn): whitespace is collapsed, a value that is one quoted string
+// is read as the text it holds (so 'red' and "red" are one value, whichever quotes a page was saved with), and nothing else is evaluated — `tokens.colorBrandStroke1` is that text,
+// whatever the token resolves to, and a variable is its name. A shorthand member (`{ borderColor }`) writes no value; its value is the variable of the same name, so it is that name.
+function valueText({ mask, src }, member) {
+ if (member.valueFrom === member.valueTo) return member.name;
+ const from = member.valueFrom;
+ let to = member.valueTo;
+ while (to > from && isTrivia(mask[to - 1])) to -= 1; // the mask holds a comment as white space
+ const quote = mask[from];
+ // One string literal: it opens at `from`, and the first quote of its kind after it — a quote inside the body is blank in the mask — is the one that closes it at `to`.
+ if ((quote === '"' || quote === "'") && mask.indexOf(quote, from + 1) === to - 1) {
+ const text = decodeStringLiteral(src, from, to);
+ if (text !== null) return JSON.stringify(text);
+ }
+ return src.slice(from, to).replace(/\s+/g, ' ');
+}
+
+// The operators at the top level of [a, b) that decide what an expression's value is — `?` and its `:`, `&&`, `||` and `??` — and each top-level cast, `as` or
+// `satisfies`, as `{ op: 'cast', at, end }` with `end` where its type ends (typeEnd): in source order, as { op, at }. A cast's type is jumped, so `x as A extends B ?
+// C : D` holds no runtime conditional, while what follows the type is code again (`x as T && y`). A bracket group is stepped over whole (the match table) and so is a
+// string; `?.` is a member access, not a conditional. null when a bracket does not close inside the range, or a cast's type cannot be read: what the expression is
+// cannot be told.
+function topLevelOperators(ctx, a, b) {
+ const { mask, match, angles } = ctx;
+ const ops = [];
+ let k = a;
+ while (k < b) {
+ const c = mask[k];
+ if (c === '{' || c === '(' || c === '[') {
+ const closer = match[k];
+ if (closer === -1 || closer >= b) return null;
+ k = closer + 1;
+ } else if (c === '"' || c === "'" || c === '`') {
+ let end = k + 1;
+ while (end < b && mask[end] !== c) end += 1;
+ k = end + 1;
+ } else if (c === '?' && mask[k + 1] === '?') {
+ ops.push({ op: '??', at: k });
+ k += 2;
+ } else if (c === '?' && mask[k + 1] === '.' && !/[0-9]/.test(mask[k + 2] || '')) {
+ k += 2;
+ } else if (c === '?' || c === ':') {
+ ops.push({ op: c, at: k });
+ k += 1;
+ } else if ((c === '&' || c === '|') && mask[k + 1] === c) {
+ ops.push({ op: c + c, at: k });
+ k += 2;
+ } else if (ID_START.test(c) && !ID_PART.test(mask[k - 1] || '')) {
+ const id = readIdentifier(mask, k);
+ if (!id) { k += 1; continue; }
+ // `x.as` is a member, not the operator.
+ if ((id.name === 'as' || id.name === 'satisfies') && mask[previousSignificant(mask, k)] !== '.') {
+ const end = typeEnd(mask, angles, id.end, b);
+ if (end === -1) {
+ // Said, so the problem names the assertion rather than a value written elsewhere (scanStyleObject, griffelStyleProblems).
+ ctx.unreadCast = true;
+ return null;
+ }
+ ops.push({ op: 'cast', at: k, end });
+ k = end;
+ continue;
+ }
+ k = id.end;
+ } else {
+ k += 1;
+ }
+ }
+ return ops;
+}
+
+// The object literals the expression in [from, to) is written as — an object literal, or object literals chosen by a condition — as the offsets of their `{`; or null
+// when some value the expression can have is one the checker cannot read in full. `helpers` lets a trusted Fluent helper stand where an object would (a spread:
+// trustedHelperValue), contributing nothing to read. Reading through a condition sets `ctx.conditional` (heldMembers asks whether a spread is one object for
+// certain). Taken in the order JavaScript binds them (loosest first):
+// c ? X : Y X and Y; the condition is not a style object
+// a || X, a ?? X null: `a` can be the value, and it is not read
+// c && X X; `c` is a condition (a false one spreads nothing)
+// X as T, X satisfies T X, when nothing but casts follows it: the type is jumped (topLevelOperators), and `x as T < 10` is a comparison, not an object
+// ( X ), X! X: parentheses and a non-null assertion change nothing at run time
+// { … } read: the keys are in it
+// Anything else — a variable, a member, a call — holds keys the checker cannot see.
+function styleObjectsOf(ctx, from, to, helpers = false, depth = 0) {
+ const { mask, match } = ctx;
+ // Deeper than any style value is written: what it holds is not read, rather than recursing until the stack runs out.
+ if (depth > MAX_STYLE_DEPTH) return null;
+ const a = skipSpace(mask, from);
+ let b = to;
+ const trim = () => { while (b > a && isTrivia(mask[b - 1])) b -= 1; };
+ trim();
+ while (b > a && mask[b - 1] === '!') { b -= 1; trim(); }
+ if (a >= b) return null;
+ const ops = topLevelOperators(ctx, a, b);
+ if (ops === null) return null;
+ const q = ops.findIndex((o) => o.op === '?');
+ if (q !== -1) {
+ ctx.conditional = true;
+ // The `:` of this `?`: a conditional inside its first branch pairs off its own.
+ let nested = 0;
+ for (let i = q + 1; i < ops.length; i += 1) {
+ if (ops[i].op === '?') nested += 1;
+ else if (ops[i].op === ':' && nested-- === 0) {
+ const yes = styleObjectsOf(ctx, ops[q].at + 1, ops[i].at, helpers, depth + 1);
+ const no = yes && styleObjectsOf(ctx, ops[i].at + 1, b, helpers, depth + 1);
+ return no ? [...yes, ...no] : null;
+ }
+ }
+ return null;
+ }
+ if (ops.some((o) => o.op === '||' || o.op === '??')) return null;
+ const ands = ops.filter((o) => o.op === '&&');
+ if (ands.length) {
+ ctx.conditional = true;
+ return styleObjectsOf(ctx, ands[ands.length - 1].at + 2, b, helpers, depth + 1);
+ }
+ const cast = ops.find((o) => o.op === 'cast');
+ if (cast) {
+ // `X as A as B`: casts one after another; anything else after the first cast's type makes the value something other than X.
+ let end = cast.end;
+ for (const next of ops) if (next.op === 'cast' && next.at === skipSpace(mask, end)) end = next.end;
+ return skipSpace(mask, end) >= b ? styleObjectsOf(ctx, a, cast.at, helpers, depth + 1) : null;
+ }
+ if (mask[a] === '(' && match[a] === b - 1) return styleObjectsOf(ctx, a + 1, b - 1, helpers, depth + 1);
+ if (mask[a] === '{' && match[a] === b - 1) return [a];
+ return helpers && trustedHelperValue(ctx, a, b) ? [] : null;
+}
+
+// Whether the expression in [a, b) is a trusted Griffel-module export (STYLE_HELPERS): `shorthands.<name>(…)` or `typographyStyles.<name>`, by a name the page imported
+// from a Griffel module (`helpers`), or through a namespace import of one (`Fluent.shorthands.<name>(…)`) — see styleFunctionBindings for when either is trusted.
+// Exactly that, and nothing after it.
+function trustedHelperValue(ctx, a, b) {
+ const { mask, match, helpers, helperNamespaces } = ctx;
+ const first = readIdentifier(mask, a);
+ if (!first) return false;
+ let k = skipSpace(mask, first.end);
+ let helper = helpers.get(first.name);
+ if (!helper && helperNamespaces.has(first.name) && mask[k] === '.') {
+ const inner = readIdentifier(mask, skipSpace(mask, k + 1));
+ if (inner && STYLE_HELPERS.has(inner.name)) {
+ helper = STYLE_HELPERS.get(inner.name);
+ k = skipSpace(mask, inner.end);
+ }
+ }
+ if (!helper || mask[k] !== '.') return false;
+ const member = readIdentifier(mask, skipSpace(mask, k + 1));
+ // Only the helper's own exports: a name it inherits (`constructor`, `valueOf`, …) is no helper, and `shorthands.constructor(x)` hands x back unread (STYLE_HELPERS).
+ if (!member || !helper.members.has(member.name)) return false;
+ if (helper.kind === 'member') return member.end === b;
+ k = skipSpace(mask, member.end);
+ if (mask[k] !== '(' || match[k] !== b - 1) return false;
+ return !(helper.guarded && helper.guarded.has(member.name)) || transitionBuildsItsOwnArray(ctx, k, b - 1);
+}
+
+// Whether Griffel's `transition`, called with the arguments between the `(` at `open` and the `)` at `close`, builds its own array — whose `reduce` is the built-in
+// one — rather than handing on the one it was given (STYLE_HELPERS). It hands one on only when it gets exactly one argument and that argument is an array
+// (`transitionInputs.length === 1 && Array.isArray(transitionInputs[0])`), so: any number of arguments but one, none of them a spread (`...list` may be that one); or
+// one array or primitive literal written in place — an array literal is a fresh Array, and a string or a number is no array. Anything else (`transition(list)`,
+// `transition(Object.assign([], { reduce() { … } }))`) may be an array with its own `reduce`.
+function transitionBuildsItsOwnArray(ctx, open, close) {
+ const args = callArguments(ctx, open, close);
+ if (args === null) return false;
+ if (args.some(({ from }) => ctx.mask.startsWith('...', skipSpace(ctx.mask, from)))) return false;
+ if (args.length !== 1) return true;
+ const { from, to } = args[0];
+ const a = skipSpace(ctx.mask, from);
+ let z = to;
+ while (z > a && isTrivia(ctx.mask[z - 1])) z -= 1;
+ return (ctx.mask[a] === '[' && ctx.match[a] === z - 1) || primitiveValue(ctx, from, to);
+}
+
+// The arguments between the `(` at `open` and the `)` at `close`, as [{ from, to }], split at the commas at their top level: a bracket group and a string are stepped
+// over whole, as topLevelOperators steps them, and a trailing comma adds none. null when a bracket does not close inside them, or a `<` stands at their top level —
+// a comparison, or type arguments whose commas would split one argument in two (`x as Map<a, b>`), which cannot be told apart here.
+function callArguments({ mask, match }, open, close) {
+ const args = [];
+ let from = open + 1;
+ let k = from;
+ while (k < close) {
+ const c = mask[k];
+ if (c === '{' || c === '(' || c === '[') {
+ const closer = match[k];
+ if (closer === -1 || closer >= close) return null;
+ k = closer + 1;
+ } else if (c === '"' || c === "'" || c === '`') {
+ let end = k + 1;
+ while (end < close && mask[end] !== c) end += 1;
+ k = end + 1;
+ } else if (c === '<') {
+ return null;
+ } else if (c === ',') {
+ args.push({ from, to: k });
+ from = k + 1;
+ k += 1;
+ } else {
+ k += 1;
+ }
+ }
+ if (skipSpace(mask, from) < close) args.push({ from, to: close });
+ return args;
+}
+
+// A key that names a CSS property holds a value: `color`, `WebkitAppearance`, `-webkit-tap-highlight-color`, or a custom property — `--` and any name
+// (`--brand_color`; https://www.w3.org/TR/css-variables-1/#defining-variables). Any other key of a style object is a selector or an at-rule (`':hover'`,
+// `'& .row'`, `'@media (…)'`), which Griffel reads as a nested style object.
+const PROPERTY_KEY = /^-?[A-Za-z][A-Za-z0-9-]*$/;
+const isPropertyKey = (name) => name.startsWith('--') || PROPERTY_KEY.test(name);
+
+// Whether the value in [from, to) is a string, a template, a number or `true`/`false`/`null`: never a style object, so it hides no key whatever the key it is under
+// looks like (`'borderWidth ': 'x'` is a property Griffel writes as it is). The keywords are reserved words, matched exactly: `Null` or `TRUE` is an ordinary name, and
+// `undefined` is not reserved (a page can bind it). The mask keeps a literal's quotes and blanks its body, so the first quote of its kind closes it.
+const PRIMITIVE = /^(?:[-+]?(?:\d[\d_]*\.?[\d_]*|\.\d[\d_]*)(?:[eE][-+]?\d+)?|true|false|null)$/;
+function primitiveValue({ mask }, from, to) {
+ const a = skipSpace(mask, from);
+ let b = to;
+ while (b > a && isTrivia(mask[b - 1])) b -= 1;
+ if (a >= b) return false;
+ const q = mask[a];
+ if (q === '"' || q === "'" || q === '`') return mask.indexOf(q, a + 1) === b - 1;
+ return PRIMITIVE.test(mask.slice(a, b));
+}
+
+// Every unsupported key under the object whose `{` is at `open`, depth first. `slotObject` is true for the object of slots, whose keys are slot names. `trail` is the names of
+// the keys the object hangs under — the slot, then each selector or at-rule below it — and `findings` collects { name, at, longhands, within, value }, with `within` that trail (a spread, or a
+// computed key that is not a string, is `...` or `[…]` in it): where a key is, apart from the line it is on, so that a page can be told from an earlier version of itself; and `value`, what
+// it is set to (valueText), so that a key given another value is not taken for the same one. A member whose value is a style object the checker cannot see — a slot, a selector or a
+// spread not written as style objects it reads (styleObjectsOf; a spread inside a style object may also be a trusted helper) — is a finding too, `{ unread, at, within, value }`,
+// `unread` saying which it is; the objects written inline in its value are still read. So is a getter that runs, whatever its key (ranGetter). The members are the ones the object holds as Griffel reads it (heldMembers).
+function scanStyleObject(ctx, open, findings, slotObject, trail = []) {
+ if (trail.length > MAX_STYLE_DEPTH) {
+ findings.push({ unread: 'deep', at: open, within: trail, value: '' });
+ return;
+ }
+ for (const { member, within } of heldMembers(ctx, open, findings, slotObject, trail)) {
+ if (!slotObject && member.name !== null && UNSUPPORTED_GRIFFEL_SHORTHANDS.has(member.name)) {
+ findings.push({ name: member.name, at: member.nameAt, longhands: UNSUPPORTED_GRIFFEL_SHORTHANDS.get(member.name), within, value: valueText(ctx, member) });
+ }
+ const here = [...within, member.name === null ? '[…]' : member.name];
+ // Keyframes are not style objects (see the header), so an animation's frames are not read. A SLOT may be called animationName: its object is a style object.
+ // A getter that defines the key still runs when Griffel reads it (ranGetter).
+ if (!slotObject && member.name === 'animationName') {
+ if (member.getter) findings.push(ranGetter(ctx, member, here));
+ continue;
+ }
+ // A computed key that is not one string may name any key, so it is held unless what it is can be told from its start: a template whose text before its first
+ // `${` (`head`) no one of the ten begins with — `--${name}`, `& .${className}`, `@media (min-width: ${width}px)` — names none of them. A slot's key is not a
+ // property, so a computed one is not held.
+ if (!slotObject && (member.name === null || (member.head !== undefined && mayBeginShorthand(member.head)))) {
+ findings.push({ unread: 'key', at: member.nameAt, within: here, value: valueText(ctx, member), key: member.keyText });
+ } else {
+ // What the key holds, read from its name — or, for a template, from its head, by Griffel's own test: it nests an object only under a key that starts with
+ // `:`, `[`, `>`, `&` or an at-rule (`@media`, `@supports` …), so a head that starts with anything else (`--`, `-`, `padding`) names a property whatever is
+ // substituted, while one that starts with one of them may be a selector.
+ const holdsStyleObject = slotObject || (member.head !== undefined ? NESTED_START.test(member.head) : !isPropertyKey(member.name));
+ if (holdsStyleObject) {
+ ctx.unreadCast = false;
+ // A getter's value is what its body returns, which is never read, however it is written: its text, `get <name>(…) {…}`, is no object (`!member.getter`
+ // says so rather than leaving it to what styleObjectsOf makes of a function's text — a getter called `as` would read as a cast).
+ const read = !member.getter
+ && (styleObjectsOf(ctx, member.valueFrom, member.valueTo) !== null || primitiveValue(ctx, member.valueFrom, member.valueTo));
+ if (!read) {
+ const unread = ctx.unreadCast ? 'cast' : slotObject ? 'slot' : 'selector';
+ findings.push({ unread, at: member.nameAt, within: here, value: valueText(ctx, member) });
+ }
+ } else if (member.getter) {
+ // A property's value is no style object, but a getter that defines it is code that runs as Griffel reads the key (ranGetter).
+ findings.push(ranGetter(ctx, member, here));
+ }
+ }
+ // A getter's body is code, not an object: it is not searched for objects written inline. Any other member's objects are style objects one level down.
+ if (!member.getter) for (const nested of objectsIn(ctx, member.valueFrom, member.valueTo)) scanStyleObject(ctx, nested, findings, false, here);
+ }
+}
+
+// The members the object whose `{` is at `open` holds as Griffel reads it, in the order JavaScript defines them, each as { member, within }. Its own members, and
+// what an inline spread copies in — the spread object's OWN members only: a spread copies own enumerable properties, never what its object inherits
+// (CopyDataProperties, https://tc39.es/ecma262/#sec-copydataproperties) — and what a prototype set by `__proto__: { … }` adds, which `for … in` reads. Then as
+// JavaScript resolves them: the last definition of a key is the property, so a member that a later member of the same key certainly replaces never reaches Griffel
+// and is left out; and an own property hides an inherited one of the same name, so an inherited member counts only where no own member certainly defines that key.
+// "Certainly": a spread a condition chooses (`...(c && { … })`) may define nothing, and a key computed at run time (keyOf null) cannot be told, so neither takes
+// anything out — a member is kept whenever the check cannot prove it gone. A spread or a prototype whose value the check cannot read is a finding (it may define
+// any key); the objects written inline in it are still read, at this object's level. A getter a spread copies has RUN — the copy reads every key of its object,
+// which calls it — so taking out the value it returned does not take out what it did: `ran` marks it, and it is a finding where it is taken out (ranGetter), as it
+// is where it is held (scanStyleObject). `ownOnly` reads an object a spread copies; `depth` counts spreads and prototypes nested in one another, past
+// MAX_STYLE_DEPTH unread.
+function heldMembers(ctx, open, findings, slotObject, trail, ownOnly = false, depth = 0) {
+ const own = [];
+ const inherited = [];
+ for (const member of objectMembers(ctx, open)) {
+ if (!member.spread && !member.proto) {
+ own.push({ member, within: trail, certain: true });
+ continue;
+ }
+ if (member.proto && ownOnly) continue;
+ const within = [...trail, member.spread ? '...' : '__proto__'];
+ const into = member.spread ? own : inherited;
+ // What a prototype holds is inherited however it got there; what an object a spread copies inherits is not copied.
+ const copied = member.spread || ownOnly;
+ // A getter its own object still holds when a spread copies that object is called by the copy (CopyDataProperties reads each key with [[Get]]); one that a
+ // prototype holds runs only if Griffel reads it, and is held then. (What an unread value does with an object written in it — a call's argument, say — the
+ // check cannot tell, and that value is a finding already.)
+ const ran = (entry) => entry.ran || (member.spread && entry.member.getter === true);
+ ctx.unreadCast = false;
+ ctx.conditional = false;
+ const objects = depth < MAX_STYLE_DEPTH ? styleObjectsOf(ctx, member.valueFrom, member.valueTo, member.spread && !slotObject) : null;
+ if (objects === null) {
+ if (!primitiveValue(ctx, member.valueFrom, member.valueTo)) {
+ const unread = depth >= MAX_STYLE_DEPTH ? 'deep' : ctx.unreadCast ? 'cast' : member.spread ? 'spread' : 'proto';
+ findings.push({ unread, at: member.nameAt, within, value: valueText(ctx, member) });
+ }
+ if (depth < MAX_STYLE_DEPTH) {
+ for (const nested of objectsIn(ctx, member.valueFrom, member.valueTo)) {
+ for (const entry of heldMembers(ctx, nested, findings, slotObject, within, copied, depth + 1)) into.push({ ...entry, certain: false });
+ }
+ }
+ continue;
+ }
+ const certain = member.spread && !ctx.conditional && objects.length === 1;
+ for (const object of objects) {
+ for (const entry of heldMembers(ctx, object, findings, slotObject, within, copied, depth + 1)) into.push({ ...entry, certain: certain && entry.certain, ran: ran(entry) });
+ }
+ }
+ const last = new Map();
+ own.forEach((entry, i) => {
+ const key = keyOf(entry.member);
+ if (key !== null && entry.certain) last.set(key, i);
+ });
+ // Taken out, a getter that has run is still reported; one that has not never runs (a later definition in its own object replaced it, or an own key hides it).
+ const takenOut = (entry) => { if (entry.ran) findings.push(ranGetter(ctx, entry.member, [...entry.within, entry.member.name])); };
+ const held = own.filter((entry, i) => {
+ const key = keyOf(entry.member);
+ if (key === null || !last.has(key) || last.get(key) <= i) return true;
+ takenOut(entry);
+ return false;
+ });
+ for (const entry of inherited) {
+ const key = keyOf(entry.member);
+ if (key === null || !last.has(key)) held.push(entry);
+ else takenOut(entry);
+ }
+ return held;
+}
+
+// A getter that runs — Griffel calls it as it reads the key, a spread as it copies its object — is code the check does not read: what it returns, and what it does
+// to its object first (`this[':hover'] = …`, `delete this.x`, which Griffel then reads), may put any key in front of Griffel, so it is a finding whatever key it
+// defines, a property's included. One that never runs is not: a later definition in its own object replaces it before anything reads it, and an own key hides an
+// inherited one. What a getter does to anything but its own object is shared state, which the check does not follow (WHAT CODE CAN CHANGE, in the header).
+function ranGetter(ctx, member, within) {
+ return { unread: 'getter', at: member.nameAt, within, value: valueText(ctx, member) };
+}
+
+// The key a member defines, where it can be told for certain: a name or a string as written (decoded — a CR LF or a lone CR in a template is one LF, as JavaScript reads it),
+// and a number in the form JavaScript gives it as a key — `0x10` and `'16'` are one key, `1e3` is `'1000'` (ToString of its value; a module allows no legacy octal
+// such as `010`) — or null: a key computed at run time is never taken to be the same key as another.
+function keyOf(member) {
+ if (member.name === null || member.head !== undefined) return null;
+ if (!member.numeric) return member.name;
+ const text = member.name.replace(/_/g, '');
+ try {
+ return text.endsWith('n') ? String(BigInt(text.slice(0, -1))) : String(Number(text));
+ } catch {
+ return null;
+ }
+}
+
+// What a key Griffel nests an object under starts with (isNestedSelector, and the at-rules, in @griffel/core's resolveStyleRules).
+const NESTED_START = /^[:[>&@]/;
+
+// Whether a key that starts with `head` may be one of the ten: Griffel matches a key exactly, so only one that is a start of one of them can be.
+const mayBeginShorthand = (head) => [...UNSUPPORTED_GRIFFEL_SHORTHANDS.keys()].some((name) => name.startsWith(head));
+
+// ─── What the lexer's reading may have hidden ───────────────────────────────────────────────────────────────────────────────────
+// The offsets of a style function's name followed by `(` or `<` in the raw source at or after `from` that are not in `known` (the calls the mask showed). After the
+// trust frontier a wrong guess may have blanked code up to the next `/`, a call included, so what the mask shows as text there may be a call; a name in a comment or a
+// string that happens to be followed by `(` is reported with it, as the navigation oracle reports a token there whatever accounts for it (pageref-resolver.js).
+function hiddenStyleCalls(src, names, from, known) {
+ const alternatives = [...new Set(names)].map(escapeRegExp).join('|');
+ const re = new RegExp(`(?<![\\p{ID_Continue}$\\u200c\\u200d])(?:${alternatives})(?![\\p{ID_Continue}$\\u200c\\u200d])${WS}*[(<]`, 'gu');
+ re.lastIndex = from;
+ const found = [];
+ for (let m = re.exec(src); m; m = re.exec(src)) if (!known.has(m.index)) found.push(m.index);
+ return found;
+}
+
+// ─── The result ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+function shorthandMessage(name, longhands) {
+ if (!longhands.length) {
+ return `\`${name}\` is not supported by Griffel: it resets every property, and makeStyles drops it at runtime. Set the properties you need one by one instead.`;
+ }
+ return `\`${name}\` is not supported by Griffel: makeStyles drops it at runtime and the page renders without it. Write the longhands instead: ${longhands.join(', ')}.`;
+}
+
+const UNVERIFIABLE_REMEDY = 'Make the code before it unambiguous — put an operand in parentheses, ({ … }) / 2 or (/re/).test(text), or end the statement with a ";" — '
+ + 'or move the makeStyles call above it.';
+
+// What an `unread-style-object` problem says, by what holds the object the checker cannot see. `value` is the expression as written, shortened; for a computed key,
+// `name` is the key as written.
+function unreadMessage(kind, name, value) {
+ const shorten = (text) => (String(text || '').length > 60 ? `${String(text).slice(0, 57)}…` : String(text || ''));
+ const shown = shorten(value);
+ if (kind === 'key') {
+ return `the key ${shorten(name)} is computed, so the check cannot tell what it names: it may be a property Griffel drops, or a selector whose style object `
+ + 'the check does not read. Write the key as a name or a string (`borderTopWidth: …`, `\':hover\': { … }`), or as a template that starts with what it is '
+ + '(`--…`, `& .…`, `@media …`), and check again.';
+ }
+ if (kind === 'cast') {
+ return `the type this value is asserted as (${shown}) is not one the check reads — it reads \`as const\` and a type name, with or without type arguments — so it `
+ + 'cannot tell what the value is, and it may hold a key Griffel drops. Write the object without the assertion, or assert a named type, and check again.';
+ }
+ if (kind === 'deep') {
+ return `this style object is nested deeper than the check reads (${MAX_STYLE_DEPTH} levels), so it cannot read its keys, and they may include one Griffel drops. `
+ + 'Write it with less nesting and check again.';
+ }
+ if (kind === 'call') {
+ return 'this makeStyles call is given a style object written elsewhere, so the check cannot read its keys, and they may include one Griffel drops. '
+ + 'Write the object in the call — makeStyles({ … }) — and check again.';
+ }
+ if (kind === 'spread') {
+ return `this spread (...${shown}) adds keys the check cannot read, and they may include one Griffel drops. Write the keys in this style object instead, `
+ + 'and check again (Fluent\'s shorthands.*(…) and typographyStyles.* may be spread as they are).';
+ }
+ if (kind === 'proto') {
+ return `the prototype set here (__proto__: ${shown}) adds keys the check cannot read, and they may include one Griffel drops. Write the keys in this object `
+ + 'instead, and check again.';
+ }
+ if (kind === 'getter') {
+ return `"${name}" is defined by a getter (${shown}), which runs when its object is read — by Griffel, or by a spread that copies it — and its body is code `
+ + 'the check does not read: what it returns, and what it changes in the object, may include a key Griffel drops. Write the value as a property, and check again.';
+ }
+ const holder = kind === 'slot' ? `slot "${name}"` : `"${name}"`;
+ return `the style object of ${holder} is not written here (${shown}), so the check cannot read its keys, and they may include one Griffel drops. `
+ + 'Write it inline, as an object, and check again.';
+}
+
+/**
+ * The problems with the Griffel style calls of one page's source.
+ * @param {string} source the page's TSX
+ * @returns {{ calls: number, frontier: null | { line: number, column: number, kind: string },
+ * problems: Array<{ code: string, property?: string, line: number, column: number, longhands?: string[], within?: string[], value?: string, message: string }> }}
+ * `calls` is how many makeStyles calls with an inline object were read. A problem is
+ * `unsupported-shorthand` — a key Griffel drops, with the line and column of the key, the longhands to write, `within`: the slot, selectors and at-rules the key sits under
+ * (`["root", ":hover"]`), and `value`: what the key is set to, as written (`"red"` for either quoting of the string red, `tokens.colorBrandStroke1` for an
+ * expression — nothing is evaluated). Together they tell the same key, still there and set to the same, from a new or a changed one when a page is compared
+ * with an earlier version of itself;
+ * `unread-style-object` — a style object the checker cannot see, so it cannot say what keys it holds: the call's own (`makeStyles(styles)`), a slot's or a selector's that is
+ * not written inline (a getter's included), or a spread of anything but an inline object or a trusted Griffel helper; a getter that runs, whatever
+ * key it defines (its code may change what Griffel reads); or a computed key it
+ * cannot read, which may be one of the ten (see the header); with `within` where it is;
+ * `unverifiable-style-call` — the lexer guessed what a `/` or `<` was before the call or inside it, so a key in it cannot be said to be there or not (see the header);
+ * `unbalanced-style-call` — the call's brackets do not balance, as in a page that is cut off.
+ * `frontier` is where the lexer first guessed, or null for a page it read without one.
+ */
+function griffelStyleProblems(source) {
+ // A byte order mark is not a column of line 1 in an editor.
+ const src = String(source == null ? '' : source).replace(/^\uFEFF/, '');
+ // Two views of one lexing pass: the literal mask the checker reads (templates blanked whole, so nothing in one is a key and no call is read inside one), and the
+ // ambiguity listener, which only the other entry point offers. The tokenization is the same with or without a listener (source-literals.js).
+ const mask = blankLiterals(src);
+ let guess = null;
+ blankNonCodePreservingTemplateExpressions(src, { onAmbiguity: (at, kind) => { if (!guess || at < guess.at) guess = { at, kind }; } });
+ const match = matchBrackets(mask);
+ const angles = matchAngles(mask);
+ const { local, helpers, helperNamespaces } = styleFunctionBindings(mask, src);
+ const ctx = { mask, src, match, angles, helpers, helperNamespaces };
+ const starts = lineStarts(src);
+ const problems = [];
+ let read = 0;
+ const calls = styleFunctionCalls(mask, src, match, angles);
+ for (const call of calls) {
+ const at = locate(starts, call.callee);
+ const unbalanced = call.close === -1 || (call.objectOpen !== -1 && call.objectClose === -1);
+ // A call is read for certain only when ALL of it lies before the first guess: a guess inside it can hide a key, and one before it can have shifted where the
+ // call starts and ends. What the lexer was not sure of is not reported as clean. A call that never closes counts as reaching it: a wrong guess blanks code up to
+ // the next `/`, closing bracket included, so with a guess on the page the unbalance is as likely the lexer's as the page's.
+ if (guess && (unbalanced || call.close >= guess.at)) {
+ const where = locate(starts, guess.at);
+ problems.push({
+ code: 'unverifiable-style-call',
+ ...at,
+ message: `the makeStyles call here cannot be checked for certain: the checker cannot tell how the page is read from line ${where.line}, column ${where.column} on (a "/" or "<" there it could read two ways — kind "${guess.kind}"), and this call lies at or after it. ${UNVERIFIABLE_REMEDY}`,
+ });
+ continue;
+ }
+ if (unbalanced) {
+ problems.push({ code: 'unbalanced-style-call', ...at, message: 'the makeStyles call here is never closed: its brackets do not balance, so the page is cut off or malformed. Finish the call and check again.' });
+ continue;
+ }
+ // The argument is read as a slot's value is (styleObjectsOf): an object written in the call, maybe in parentheses, with an assertion or chosen by a condition.
+ ctx.unreadCast = false;
+ const slots = styleObjectsOf(ctx, call.argFrom, call.argTo);
+ if (slots === null) {
+ problems.push({ code: 'unread-style-object', ...at, within: [], message: unreadMessage(ctx.unreadCast ? 'cast' : 'call', '', src.slice(call.argFrom, call.argTo)) });
+ continue;
+ }
+ read += 1;
+ const findings = [];
+ for (const open of slots) scanStyleObject(ctx, open, findings, call.spec.slots);
+ for (const f of findings) {
+ if (f.unread) {
+ problems.push({ code: 'unread-style-object', ...locate(starts, f.at), within: f.within, value: f.value,
+ message: unreadMessage(f.unread, f.key ?? f.within[f.within.length - 1], f.value) });
+ } else {
+ problems.push({ code: 'unsupported-shorthand', property: f.name, ...locate(starts, f.at), longhands: f.longhands, within: f.within, value: f.value, message: shorthandMessage(f.name, f.longhands) });
+ }
+ }
+ }
+ if (guess) {
+ const known = new Set(calls.map((call) => call.nameAt));
+ for (const nameAt of hiddenStyleCalls(src, [...local.keys(), ...STYLE_FUNCTIONS.keys()], guess.at, known)) {
+ const where = locate(starts, guess.at);
+ problems.push({
+ code: 'unverifiable-style-call',
+ ...locate(starts, nameAt),
+ message: `a makeStyles call may be here, but the checker cannot tell for certain that this is code: it cannot tell how the page is read from line ${where.line}, column ${where.column} on (a "/" or "<" there it could read two ways — kind "${guess.kind}"). ${UNVERIFIABLE_REMEDY}`,
+ });
+ }
+ }
+ problems.sort((a, b) => a.line - b.line || a.column - b.column);
+ return { calls: read, frontier: guess ? { ...locate(starts, guess.at), kind: guess.kind } : null, problems };
+}
+
+// The problems of one file as the text a refusal carries — `<file>:<line>:<column>: <message>`, one per problem — so a halt names where each one is and the
+// longhands to write there. One wording for the one defect: the build's halt and genpage-upload.js's refusal both use it, and both end by naming the checker.
+function describeGriffelProblems(problems, file) {
+ return problems.map((p) => `${file}:${p.line}:${p.column}: ${p.message}`).join(' ');
+}
+
+// ─── A page against the version that is already deployed ─────────────────────────────────────────────────────────────────────────
+// The check is held against what a run is about to SHIP. A page that is already deployed with a key Griffel drops — written by an earlier version of the plugin, whose only guard
+// was a grep for `borderWidth`, so `borderColor` under `:hover` passed — shipped it before this check existed, and sending the same bytes again ships nothing new. Refusing it would
+// stop a rebuild, or an edit, over a defect the maker did not touch, and the way out would change how the page looks: those declarations never applied, so writing the longhands makes
+// them start to. Only a key the deployed page did not already have is held back; a page that is created, or whose source changed, is held to the whole check (sdk-build.js and
+// genpage-upload.js decide which a page is), and what is let through is said, with both ways out.
+const isShorthandProblem = (problem) => problem.code === 'unsupported-shorthand';
+
+/**
+ * Which of `problems` the page's deployed version already had. `deployed` is that version's problems (griffelStyleProblems of the source that was deployed). A key counts as already
+ * there when the deployed page has the same key set to the same value in the same place (`within`: the slot, selectors and at-rules it sits under) and, failing that, the same key set to
+ * the same value anywhere that nothing else has claimed — so a slot that was renamed, or a rule that was moved, does not turn a key Griffel was already dropping into a new one. A key given
+ * ANOTHER value is a new one: Griffel drops it just the same, so the page would show none of the change the maker meant, which is what this check exists to stop (a value is compared as
+ * written — `value` of the problem — and nothing is evaluated). Each key of the deployed page is spent once, so a second `borderColor` where there was one is new. A problem that is not a
+ * shorthand — a call the checker cannot read — is never "already there": what it hides cannot be compared with anything.
+ * @returns {{ added: object[], inherited: object[] }} the problems the deployed page did not have, and those it did, each in source order
+ */
+function griffelProblemsNotIn(problems, deployed) {
+ const keyOf = (p) => `${p.property}\u0001${p.value}`;
+ const placeOf = (p) => `${(p.within || []).join('\u0000')}\u0001${keyOf(p)}`;
+ const inPlace = new Map();
+ const anywhere = new Map();
+ const spend = (map, key, by) => map.set(key, (map.get(key) || 0) + by);
+ for (const d of deployed || []) {
+ if (!isShorthandProblem(d)) continue;
+ spend(inPlace, placeOf(d), 1);
+ spend(anywhere, keyOf(d), 1);
+ }
+ const added = [];
+ const inherited = [];
+ const unplaced = [];
+ for (const p of problems) {
+ if (!isShorthandProblem(p)) added.push(p);
+ else if ((inPlace.get(placeOf(p)) || 0) > 0) {
+ spend(inPlace, placeOf(p), -1);
+ spend(anywhere, keyOf(p), -1);
+ inherited.push(p);
+ } else unplaced.push(p);
+ }
+ for (const p of unplaced) {
+ if ((anywhere.get(keyOf(p)) || 0) > 0) { spend(anywhere, keyOf(p), -1); inherited.push(p); } else added.push(p);
+ }
+ const bySource = (a, b) => a.line - b.line || a.column - b.column;
+ return { added: added.sort(bySource), inherited: inherited.sort(bySource) };
+}
+
+// What each way out of a dropped key does to the page. Both are a choice about how it looks, and a message that names only the longhands steers a maker who meant to keep a page as
+// it is into changing it: Griffel never applied the key, so deleting it changes nothing on screen, while the longhands DO apply.
+const SHORTHAND_REMEDIES = 'Deleting a key changes nothing on screen, because Griffel never applied it; writing the longhands (for `all`, the properties you want) '
+ + 'makes the style start to render, which changes how the page looks.';
+
+// The wording that differs between the two places the check is held, so that one defect has one text: the build's pages phase (a page of the App Spec) and genpage-upload.js (a file).
+const SURFACES = {
+ build: { lead: ' — ', where: 'the page\'s source', rerun: 're-run.' },
+ upload: { lead: ' — refusing to upload. ', where: 'the file', rerun: 're-run the upload.' },
+};
+
+/**
+ * The text of a halt or a refusal: `problems` of one file, which the run does not go on with.
+ * @param {object[]} problems what griffelStyleProblems (or griffelProblemsNotIn) found, never empty
+ * @param {string} file the file their positions are in
+ * @param {object} o
+ * @param {'build'|'upload'} o.surface who is speaking (SURFACES)
+ * @param {string} o.subject what the sentence starts with: `page "Detail"`, or the path of the file
+ * @param {string} o.command the checker command that lists every problem, with its path quoted as a shell needs it
+ * @param {string} [o.note] one more sentence before the way on, such as why this page is held to the check
+ * A key Griffel drops is worded as such, with both ways out (SHORTHAND_REMEDIES). A call the checker could not read is NOT said to write CSS Griffel drops — it may not — but to be one
+ * the check could not read, with what to change in the code; where a page has both, the keys come first.
+ */
+function describeGriffelRefusal(problems, file, { surface, subject, command, note = '' }) {
+ const words = SURFACES[surface];
+ const shorthands = problems.filter(isShorthandProblem);
+ const unreadable = problems.filter((p) => !isShorthandProblem(p));
+ const noteText = note ? `${note} ` : '';
+ if (!shorthands.length) {
+ return `${subject} has makeStyles calls the Griffel check could not read, so it cannot tell whether the page writes CSS that Griffel drops at runtime${words.lead}${describeGriffelProblems(unreadable, file)} `
+ + `${noteText}Change ${words.where} as that says (\`${command}\` shows what it cannot read), then ${words.rerun}`;
+ }
+ const alsoUnreadable = unreadable.length
+ ? ` It also has makeStyles calls the check could not read, so it cannot tell whether they hold more: ${describeGriffelProblems(unreadable, file)}`
+ : '';
+ return `${subject} writes CSS that Griffel drops at runtime, so the page would deploy without it${words.lead}${describeGriffelProblems(shorthands, file)} ${SHORTHAND_REMEDIES}${alsoUnreadable} `
+ + `${noteText}Fix ${problems.length === 1 ? 'it' : 'them'} in ${words.where} (\`${command}\` lists every one), then ${words.rerun}`;
+}
+
+// Why a run goes on with a page that has problems (`why`, the sentence that follows its subject), and what the check will do about the page from then on (`next`, the end of the
+// warning). `unchanged` and `unrecorded` are the build's: the page is an update, and either its source is the one the last build recorded for it, or there is no record to say (a
+// workspace that is new, moved or was cleared) — and the page exists in the environment, so an earlier build deployed it as it is, which is the behaviour a run must not take away.
+// `inherited` and `undetermined` are genpage-upload.js's: the deployed page it downloads had these keys, or could not be read to compare with (only under --overwrite-deployed, which
+// goes on without it).
+const STANDING = {
+ unchanged: {
+ why: 'is already deployed, and its source is the one the last build recorded for it, so this build sends it again as it is and goes on.',
+ next: 'once the page\'s source changes, the build holds it to the check and stops on anything the check still reports.',
+ },
+ unrecorded: {
+ why: 'is already deployed, and this workspace holds no record of what the last build sent for it, so the build cannot tell whether this send changes it; it goes on, as builds did before this check.',
+ next: 'once a build has recorded this page, a change to its source is held to the check, and the build stops on anything the check still reports.',
+ },
+ inherited: {
+ why: 'updates a page that is already deployed, and the deployed page already had these, set the same, so the upload goes on.',
+ next: 'an upload that adds anything the check reports, or sets one of these to another value, is refused.',
+ },
+ undetermined: {
+ why: 'updates a page that is already deployed, and the deployed page could not be read to tell which of these it already had, so the upload goes on.',
+ next: 'when the deployed page can be read, an upload that adds anything the check reports is refused.',
+ },
+};
+
+/**
+ * The text of a warning: `problems` of one page that the run goes on with, because it ships nothing new (see above). Same arguments as describeGriffelRefusal, with `standing` — one
+ * of STANDING's keys — in place of `note`. It says that the page renders without the key today, both ways out, and that the check still stops a change that adds one.
+ */
+function describeGriffelWarning(problems, file, { surface, subject, standing, command }) {
+ const words = SURFACES[surface];
+ const shorthands = problems.filter(isShorthandProblem);
+ const unreadable = problems.filter((p) => !isShorthandProblem(p));
+ const parts = [`${subject} ${STANDING[standing].why}`];
+ if (shorthands.length) {
+ parts.push(`It writes CSS that Griffel drops at runtime, so the page renders without it as it does today: ${describeGriffelProblems(shorthands, file)} ${SHORTHAND_REMEDIES}`);
+ }
+ if (unreadable.length) {
+ parts.push(`${shorthands.length ? 'It also has' : 'It has'} makeStyles calls the Griffel check could not read, so it cannot tell ${shorthands.length ? 'whether they hold more' : 'whether the page writes CSS that Griffel drops at runtime'}: ${describeGriffelProblems(unreadable, file)}`);
+ }
+ parts.push(`Edit ${words.where} to ${shorthands.length ? 'do either' : 'make the code readable'} (\`${command}\` ${shorthands.length ? 'lists every one' : 'shows what it cannot read'}); ${STANDING[standing].next}`);
+ return parts.join(' ');
+}
+
+// typeEnd over a whole source — where the type that starts at `from` ends, or -1 — for the differential test that holds it against TypeScript's own parser: never an end
+// TypeScript does not agree with (tests/griffel-styles.test.js, with TYPESCRIPT_ORACLE_PATH set).
+function assertedTypeEnd(source, from) {
+ const mask = blankLiterals(String(source));
+ return typeEnd(mask, matchAngles(mask), from, mask.length);
+}
+
+module.exports = { griffelStyleProblems, describeGriffelProblems, griffelProblemsNotIn, describeGriffelRefusal, describeGriffelWarning, SHORTHAND_REMEDIES, UNSUPPORTED_GRIFFEL_SHORTHANDS, GRIFFEL_MODULES, STYLE_FUNCTIONS,
+ assertedTypeEnd };
diff --git a/plugins/model-apps/scripts/lib/lcid-cultures.js b/plugins/model-apps/scripts/lib/lcid-cultures.js
new file mode 100644
index 000000000..1c5c77cc4
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/lcid-cultures.js
@@ -0,0 +1,189 @@
+'use strict';
+// Which culture an environment language is, and which way it is written — the host's half of the SDK's
+// `getEnvironmentLanguages()`.
+//
+// The SDK answers LCIDs only ("culture names, display names and text direction are NOT SDK output"): `pac`
+// printed them from .NET's `CultureInfo`, and no Intl API maps an LCID to a locale. So the mapping lives here, as
+// data, and an LCID it does not name STAYS NUMERIC — `cultureForLcid` answers null, never a neighbouring language's
+// code or a guessed direction. A page that keys its translations by culture code, and sets `dir` from the
+// direction, must not be handed a wrong answer in place of an unknown one.
+//
+// The data is Windows' own, because that is where PAC's `Code` and `RTL` columns came from: every specific
+// (language + region) culture it names, by LCID, with the name `CultureInfo.Name` gives it and the direction
+// `TextInfo.IsRightToLeft` gives it. Left out on purpose: neutral cultures (an environment provisions a language
+// under a specific LCID), the invariant culture, the pseudo-locales (`qps-*`) and custom LCIDs (4096). Sort-order
+// variants whose id carries a sort id above 0xFFFF (the German phone book, 0x10407) are no 16-bit LCID an
+// environment reports; 1034 (Spanish, traditional sort) is in, and Windows names it `es-ES`, like 3082.
+// See: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-lcid/70feba9f-294e-491e-b6eb-56532684c37f
+// https://learn.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo.name
+// https://learn.microsoft.com/en-us/dotnet/api/system.globalization.textinfo.isrighttoleft
+//
+// Regenerate in Windows PowerShell 5.1 (.NET Framework, so the data is Windows' and not ICU's), then diff:
+// foreach ($l in 1..65535) {
+// try { $c = [Globalization.CultureInfo]::GetCultureInfo($l) } catch { continue }
+// if ($c.LCID -eq $l -and -not $c.IsNeutralCulture -and $c.Name -and $c.Name -notlike 'qps-*') {
+// "[$l, '$($c.Name)'], rtl=$($c.TextInfo.IsRightToLeft)"
+// }
+// }
+// Windows still names 2074 and 3098 `sr-Latn-CS` and `sr-Cyrl-CS` (Serbia and Montenegro, a region that no longer
+// exists): that is what `CultureInfo.Name` gave PAC for them, so it is what the table holds.
+//
+// Direction is a table and not `Intl.Locale#maximize().script`, on purpose: a Node built without full ICU data
+// answers no script for Arabic, so a computed direction would read an Arabic environment as left-to-right with no
+// error. The tests check the two against each other where the host has the data.
+
+const CODES = [
+ [1025, 'ar-SA'], [1026, 'bg-BG'], [1027, 'ca-ES'], [1028, 'zh-TW'], [1029, 'cs-CZ'],
+ [1030, 'da-DK'], [1031, 'de-DE'], [1032, 'el-GR'], [1033, 'en-US'], [1034, 'es-ES'],
+ [1035, 'fi-FI'], [1036, 'fr-FR'], [1037, 'he-IL'], [1038, 'hu-HU'], [1039, 'is-IS'],
+ [1040, 'it-IT'], [1041, 'ja-JP'], [1042, 'ko-KR'], [1043, 'nl-NL'], [1044, 'nb-NO'],
+ [1045, 'pl-PL'], [1046, 'pt-BR'], [1047, 'rm-CH'], [1048, 'ro-RO'], [1049, 'ru-RU'],
+ [1050, 'hr-HR'], [1051, 'sk-SK'], [1052, 'sq-AL'], [1053, 'sv-SE'], [1054, 'th-TH'],
+ [1055, 'tr-TR'], [1056, 'ur-PK'], [1057, 'id-ID'], [1058, 'uk-UA'], [1059, 'be-BY'],
+ [1060, 'sl-SI'], [1061, 'et-EE'], [1062, 'lv-LV'], [1063, 'lt-LT'], [1064, 'tg-Cyrl-TJ'],
+ [1065, 'fa-IR'], [1066, 'vi-VN'], [1067, 'hy-AM'], [1068, 'az-Latn-AZ'], [1069, 'eu-ES'],
+ [1070, 'hsb-DE'], [1071, 'mk-MK'], [1072, 'st-ZA'], [1073, 'ts-ZA'], [1074, 'tn-ZA'],
+ [1075, 've-ZA'], [1076, 'xh-ZA'], [1077, 'zu-ZA'], [1078, 'af-ZA'], [1079, 'ka-GE'],
+ [1080, 'fo-FO'], [1081, 'hi-IN'], [1082, 'mt-MT'], [1083, 'se-NO'], [1085, 'yi-001'],
+ [1086, 'ms-MY'], [1087, 'kk-KZ'], [1088, 'ky-KG'], [1089, 'sw-KE'], [1090, 'tk-TM'],
+ [1091, 'uz-Latn-UZ'], [1092, 'tt-RU'], [1093, 'bn-IN'], [1094, 'pa-IN'], [1095, 'gu-IN'],
+ [1096, 'or-IN'], [1097, 'ta-IN'], [1098, 'te-IN'], [1099, 'kn-IN'], [1100, 'ml-IN'],
+ [1101, 'as-IN'], [1102, 'mr-IN'], [1103, 'sa-IN'], [1104, 'mn-MN'], [1105, 'bo-CN'],
+ [1106, 'cy-GB'], [1107, 'km-KH'], [1108, 'lo-LA'], [1109, 'my-MM'], [1110, 'gl-ES'],
+ [1111, 'kok-IN'], [1112, 'mni-IN'], [1113, 'sd-Deva-IN'], [1114, 'syr-SY'], [1115, 'si-LK'],
+ [1116, 'chr-Cher-US'], [1117, 'iu-Cans-CA'], [1118, 'am-ET'], [1119, 'tzm-Arab-MA'], [1121, 'ne-NP'],
+ [1122, 'fy-NL'], [1123, 'ps-AF'], [1124, 'fil-PH'], [1125, 'dv-MV'], [1126, 'bin-NG'],
+ [1127, 'ff-Latn-NG'], [1128, 'ha-Latn-NG'], [1129, 'ibb-NG'], [1130, 'yo-NG'], [1131, 'quz-BO'],
+ [1132, 'nso-ZA'], [1133, 'ba-RU'], [1134, 'lb-LU'], [1135, 'kl-GL'], [1136, 'ig-NG'],
+ [1137, 'kr-Latn-NG'], [1138, 'om-ET'], [1139, 'ti-ET'], [1140, 'gn-PY'], [1141, 'haw-US'],
+ [1142, 'la-VA'], [1143, 'so-SO'], [1144, 'ii-CN'], [1145, 'pap-029'], [1146, 'arn-CL'],
+ [1148, 'moh-CA'], [1150, 'br-FR'], [1152, 'ug-CN'], [1153, 'mi-NZ'], [1154, 'oc-FR'],
+ [1155, 'co-FR'], [1156, 'gsw-FR'], [1157, 'sah-RU'], [1158, 'quc-Latn-GT'], [1159, 'rw-RW'],
+ [1160, 'wo-SN'], [1164, 'fa-AF'], [1169, 'gd-GB'], [1170, 'ku-Arab-IQ'], [2049, 'ar-IQ'],
+ [2051, 'ca-ES-valencia'], [2052, 'zh-CN'], [2055, 'de-CH'], [2057, 'en-GB'], [2058, 'es-MX'],
+ [2060, 'fr-BE'], [2064, 'it-CH'], [2067, 'nl-BE'], [2068, 'nn-NO'], [2070, 'pt-PT'],
+ [2072, 'ro-MD'], [2073, 'ru-MD'], [2074, 'sr-Latn-CS'], [2077, 'sv-FI'], [2080, 'ur-IN'],
+ [2092, 'az-Cyrl-AZ'], [2094, 'dsb-DE'], [2098, 'tn-BW'], [2107, 'se-SE'], [2108, 'ga-IE'],
+ [2110, 'ms-BN'], [2115, 'uz-Cyrl-UZ'], [2117, 'bn-BD'], [2118, 'pa-Arab-PK'], [2121, 'ta-LK'],
+ [2128, 'mn-Mong-CN'], [2137, 'sd-Arab-PK'], [2141, 'iu-Latn-CA'], [2143, 'tzm-Latn-DZ'], [2144, 'ks-Deva-IN'],
+ [2145, 'ne-IN'], [2151, 'ff-Latn-SN'], [2155, 'quz-EC'], [2163, 'ti-ER'], [3073, 'ar-EG'],
+ [3076, 'zh-HK'], [3079, 'de-AT'], [3081, 'en-AU'], [3082, 'es-ES'], [3084, 'fr-CA'],
+ [3098, 'sr-Cyrl-CS'], [3131, 'se-FI'], [3152, 'mn-Mong-MN'], [3153, 'dz-BT'], [3179, 'quz-PE'],
+ [4097, 'ar-LY'], [4100, 'zh-SG'], [4103, 'de-LU'], [4105, 'en-CA'], [4106, 'es-GT'],
+ [4108, 'fr-CH'], [4122, 'hr-BA'], [4155, 'smj-NO'], [4191, 'tzm-Tfng-MA'], [5121, 'ar-DZ'],
+ [5124, 'zh-MO'], [5127, 'de-LI'], [5129, 'en-NZ'], [5130, 'es-CR'], [5132, 'fr-LU'],
+ [5146, 'bs-Latn-BA'], [5179, 'smj-SE'], [6145, 'ar-MA'], [6153, 'en-IE'], [6154, 'es-PA'],
+ [6156, 'fr-MC'], [6170, 'sr-Latn-BA'], [6203, 'sma-NO'], [7169, 'ar-TN'], [7177, 'en-ZA'],
+ [7178, 'es-DO'], [7180, 'fr-029'], [7194, 'sr-Cyrl-BA'], [7227, 'sma-SE'], [8193, 'ar-OM'],
+ [8201, 'en-JM'], [8202, 'es-VE'], [8204, 'fr-RE'], [8218, 'bs-Cyrl-BA'], [8251, 'sms-FI'],
+ [9217, 'ar-YE'], [9225, 'en-029'], [9226, 'es-CO'], [9228, 'fr-CD'], [9242, 'sr-Latn-RS'],
+ [9275, 'smn-FI'], [10241, 'ar-SY'], [10249, 'en-BZ'], [10250, 'es-PE'], [10252, 'fr-SN'],
+ [10266, 'sr-Cyrl-RS'], [11265, 'ar-JO'], [11273, 'en-TT'], [11274, 'es-AR'], [11276, 'fr-CM'],
+ [11290, 'sr-Latn-ME'], [12289, 'ar-LB'], [12297, 'en-ZW'], [12298, 'es-EC'], [12300, 'fr-CI'],
+ [12314, 'sr-Cyrl-ME'], [13313, 'ar-KW'], [13321, 'en-PH'], [13322, 'es-CL'], [13324, 'fr-ML'],
+ [14337, 'ar-AE'], [14345, 'en-ID'], [14346, 'es-UY'], [14348, 'fr-MA'], [15361, 'ar-BH'],
+ [15369, 'en-HK'], [15370, 'es-PY'], [15372, 'fr-HT'], [16385, 'ar-QA'], [16393, 'en-IN'],
+ [16394, 'es-BO'], [17417, 'en-MY'], [17418, 'es-SV'], [18441, 'en-SG'], [18442, 'es-HN'],
+ [19465, 'en-AE'], [19466, 'es-NI'], [20490, 'es-PR'], [21514, 'es-US'], [22538, 'es-419'],
+ [23562, 'es-CU'],
+];
+
+// The LCIDs of the cultures above that `TextInfo.IsRightToLeft` marks right-to-left: every Arabic region, Hebrew,
+// Persian and Dari, Urdu, Yiddish, Syriac, Pashto, Divehi, Uyghur, Central Kurdish and the Arabic-script
+// Tamazight, Punjabi and Sindhi.
+const RTL_LCIDS = new Set([
+ 1025, 1037, 1056, 1065, 1085, 1114, 1119, 1123, 1125, 1152,
+ 1164, 1170, 2049, 2080, 2118, 2137, 3073, 4097, 5121, 6145,
+ 7169, 8193, 9217, 10241, 11265, 12289, 13313, 14337, 15361, 16385,
+]);
+
+const CODE_BY_LCID = new Map(CODES);
+
+/**
+ * The culture an LCID names, or null when this table does not name it.
+ * @param {number} lcid - a positive integer, as the SDK reports it (e.g. 1025)
+ * @returns {{ lcid: number, code: string, rtl: boolean } | null} e.g. { lcid: 1025, code: 'ar-SA', rtl: true }
+ */
+function cultureForLcid(lcid) {
+ // Only a number the SDK could have read: a numeric string, a fraction, a negative or a custom id is no LCID here,
+ // and an unknown one must not coerce into a neighbour's.
+ if (!Number.isInteger(lcid) || lcid <= 0) return null;
+ const code = CODE_BY_LCID.get(lcid);
+ return code === undefined ? null : { lcid, code, rtl: RTL_LCIDS.has(lcid) };
+}
+
+// Built once, and not at all where Intl has no DisplayNames (a Node without ICU) — the name is a courtesy and the
+// code and direction above never depend on it. `languageDisplay: 'standard'` gives "English (United States)", the form
+// PAC's Language column had, where the default 'dialect' gives "American English".
+// See: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/DisplayNames
+let displayNames;
+function englishNames() {
+ if (displayNames === undefined) {
+ try {
+ displayNames = new Intl.DisplayNames(['en'], { type: 'language', fallback: 'none', languageDisplay: 'standard' });
+ } catch {
+ displayNames = null;
+ }
+ }
+ return displayNames;
+}
+
+/**
+ * The English name of a culture code ("Arabic (Saudi Arabia)"), or null when this host's Intl has none for it.
+ * `fallback: 'none'` is what makes "has none" visible: the default would answer the code itself, which is no name.
+ */
+function languageName(code, names = englishNames()) {
+ if (!names || typeof code !== 'string') return null;
+ try {
+ const name = names.of(code);
+ return typeof name === 'string' && name ? name : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * One language as the planner reads it. An LCID this table does not name keeps its number and has no code, name or
+ * direction (`null`, never a default).
+ * @returns {{ lcid: number, code: string|null, name: string|null, rtl: boolean|null }}
+ */
+function describeLanguage(lcid, names) {
+ const culture = cultureForLcid(lcid);
+ return {
+ lcid,
+ code: culture ? culture.code : null,
+ name: culture ? languageName(culture.code, names) : null,
+ rtl: culture ? culture.rtl : null,
+ };
+}
+
+/**
+ * The line the plan's Localization section carries for a language: `<LCID> <Code> — RTL: Yes|No`, the columns PAC
+ * printed. An LCID without a culture reads `<LCID> unknown — RTL: unknown`.
+ */
+function languageLine(language) {
+ const direction = language.rtl === null ? 'unknown' : language.rtl ? 'Yes' : 'No';
+ return `${language.lcid} ${language.code === null ? 'unknown' : language.code} — RTL: ${direction}`;
+}
+
+/**
+ * What the SDK's `getEnvironmentLanguages()` answered, in the planner's terms: the base language, every PROVISIONED
+ * language in the server's order, the LCIDs no culture is known for, and a line per provisioned language. The base
+ * language is described on its own, not looked for among the provisioned ones: the SDK checks no relation between its
+ * reads, so the base can be absent from them.
+ * @param {{ baseLanguage: number, provisioned: number[] }} reads
+ */
+function describeEnvironmentLanguages(reads, names) {
+ if (!reads || !Number.isInteger(reads.baseLanguage) || !Array.isArray(reads.provisioned)) {
+ throw new TypeError('describeEnvironmentLanguages expects { baseLanguage: number, provisioned: number[] }');
+ }
+ const baseLanguage = describeLanguage(reads.baseLanguage, names);
+ // A local, not a call straight on the read's provisioned list: the SDK-surface scan takes any receiver whose name
+ // holds "provision" for an SDK handle, and would list `map` as an SDK method.
+ const lcids = reads.provisioned;
+ const languages = lcids.map((lcid) => describeLanguage(lcid, names));
+ const unmapped = [...new Set([baseLanguage, ...languages].filter((language) => language.code === null).map((language) => language.lcid))];
+ return { baseLanguage, languages, unmapped, summary: languages.map(languageLine) };
+}
+
+module.exports = { cultureForLcid, languageName, describeLanguage, languageLine, describeEnvironmentLanguages, CODES, RTL_LCIDS };
diff --git a/plugins/model-apps/scripts/lib/lookup-cell-labels.js b/plugins/model-apps/scripts/lib/lookup-cell-labels.js
new file mode 100644
index 000000000..789ae8328
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/lookup-cell-labels.js
@@ -0,0 +1,74 @@
+'use strict';
+// Repair, on a deployed form, the label an older build gave a lookup cell (ADO 6691205).
+//
+// Kept apart from lookup-labels.js on purpose: this half needs the form-topology helpers in
+// artifact-intent.js, which itself requires entity-provision.js — and entity-provision.js requires
+// lookup-labels.js. Folding the two together would close that loop.
+
+const { lookupColumnsFor, isOldLookupFieldLabel } = require('./app-spec.js');
+const { findFieldCellLocations } = require('./artifact-intent.js');
+const { lookupKey } = require('./lookup-labels.js');
+
+// The value at a JSON pointer such as `/tabs/0/columns/0/sections/0/rows/0/cells/0` — the form of
+// pointer findFieldCellLocations returns, which only ever holds array indices and plain keys.
+function atPointer(root, pointer) {
+ let cur = root;
+ for (const token of String(pointer).split('/').slice(1)) {
+ if (cur == null) return undefined;
+ cur = cur[token];
+ }
+ return cur;
+}
+
+// A bound cell's label is stored in the form. The SDK derives it from the column's DisplayName only
+// when the cell has none, so a form built while the lookup column still carried the SDK's old default
+// (the parent's logical name) keeps that name on the cell after the COLUMN is relabelled. A cell the SDK
+// could not resolve a column for at push carries the field's own lower-case logical name instead — its
+// control normalization defaults `label` to `fieldName`.
+//
+// Same rule as the column repair, and for the same reason — only the old default is touched. A cell is
+// rewritten only when the spec sets no lookup.displayName AND its label is exactly an old default
+// (isOldLookupFieldLabel: the parent's or the lookup's own lower-case logical name — a column's old default is
+// only the first of these, which is why the two are separate predicates). It becomes what the column carries
+// NOW (`lookupLabels`, from the data-model phase): the repaired label, or a maker's if the maker relabelled the
+// column. With no record of the column's label — the phase did not run, or could not read it — the cell is left
+// as it is rather than given a label nothing proves.
+//
+// EVERY cell of the lookup is held to the rule, each on its own label: a deployed form can hold a field more than
+// once (a maker can place it in a second section), and a first cell that is already right, or a maker's, says
+// nothing about the label of a second one an older build left.
+//
+// Returns the logical names of the lookups it relabelled a cell of.
+async function repairLookupCellLabels({ provision, formId, entityLogical, spec, lookupLabels }) {
+ const repaired = [];
+ const child = String(entityLogical || '').toLowerCase();
+ for (const lookup of lookupColumnsFor(spec, child)) {
+ if (lookup.source === 'explicit') continue;
+ const column = lookupLabels && lookupLabels[lookupKey(lookup.rel)];
+ if (!column || !column.label) continue;
+ // `await` is load-bearing — the SDK's artifact reads are async, and a bare call hands the pure
+ // helpers below a Promise that silently matches nothing.
+ let form = (await provision.getArtifact('form', formId)) || {};
+ const cells = findFieldCellLocations(form, lookup.logical).length;
+ let relabelled = false;
+ for (let i = 0; i < cells; i++) {
+ const location = findFieldCellLocations(form, lookup.logical)[i];
+ if (!location) break;
+ const cell = atPointer(form, location.cellPointer);
+ const deployed = cell && cell.control && cell.control.label;
+ if (typeof deployed !== 'string' || deployed === column.label || !isOldLookupFieldLabel(lookup.rel, deployed)) continue;
+ // updateElement MERGES an object patch, so classId, isRequired and the rest of the control survive.
+ await provision.updateElement('form', formId, `${location.cellPointer}/control`, { label: column.label });
+ relabelled = true;
+ // Read again after each write, so each label is judged on the form as the SDK holds it now. A label patch moves no
+ // cell — updateElement merges it into that one control — so the later cells keep their indexes; and every write is
+ // decided on the label of the cell at hand, so even an SDK that re-normalised a form as it wrote could not have a
+ // maker's label overwritten here.
+ form = (await provision.getArtifact('form', formId)) || {};
+ }
+ if (relabelled) repaired.push(lookup.logical);
+ }
+ return repaired;
+}
+
+module.exports = { repairLookupCellLabels };
diff --git a/plugins/model-apps/scripts/lib/lookup-labels.js b/plugins/model-apps/scripts/lib/lookup-labels.js
new file mode 100644
index 000000000..cb8cd5d41
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/lookup-labels.js
@@ -0,0 +1,154 @@
+'use strict';
+// The environment-facing half of the lookup label default (ADO 6691205).
+//
+// The RULE lives in app-spec.js (`lookupLabelFor`) so every offline surface shares it. What is here
+// is only what needs Dataverse: reading the display name of a parent table the spec cannot name, and the
+// current labels of a table's lookup columns (so a rebuild can tell the build's old default from a maker's
+// label).
+//
+// These are deliberately NARROW reads on the SDK's own client (`sdk.dataverse`) — one keyed read of a
+// table's DisplayName, one `Attributes` read of a table's lookup columns — not
+// `fetchEntityMetadata`/`findTables`: those are the broad reads documented on `relationshipExists`
+// (entity-provision.js) as the ones that make Dataverse keep only the base-language label of the create
+// that follows, they write the fetched table into the build's workspace, and `fetchEntityMetadata` costs
+// ~11 requests for the one property needed here. Remove this once the SDK offers a label-only read.
+
+const { odataLit } = require('./odata.js');
+const { labelText } = require('./app-spec.js');
+
+// Dataverse sends a Label as:
+// { "LocalizedLabels": [ { "Label": "Account", "LanguageCode": 1033, "IsManaged": true, ... },
+// { "Label": "Compte", "LanguageCode": 1036, ... } ],
+// "UserLocalizedLabel": { "Label": "Compte", "LanguageCode": 1036, ... } }
+// `UserLocalizedLabel` is the label in the CALLING USER's language, which is not necessarily the
+// language the build stamps on the label it writes — so the labels are read by language code instead.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/label
+function labelsByLcid(label) {
+ const out = {};
+ const rows = label && Array.isArray(label.LocalizedLabels) ? label.LocalizedLabels : [];
+ for (const row of rows) {
+ const lcid = Number(row && row.LanguageCode);
+ if (Number.isInteger(lcid) && lcid > 0 && typeof row.Label === 'string' && row.Label.trim()) out[String(lcid)] = row.Label;
+ }
+ return out;
+}
+
+// One label to write as a plain string: the entry for the authoring language, then 1033, then the
+// lowest-numbered language (labelText's own order, so an offline surface and a live read agree on a
+// fallback), and only then the calling user's.
+function pickLabel(label, languageCode) {
+ const map = labelsByLcid(label);
+ const picked = labelText(map, languageCode);
+ if (picked) return picked;
+ const user = label && label.UserLocalizedLabel && label.UserLocalizedLabel.Label;
+ return typeof user === 'string' && user.trim() ? user : null;
+}
+
+function describe(res, thrown) {
+ if (thrown) return (thrown && thrown.message) || String(thrown);
+ const envelope = res && res.body && typeof res.body === 'object' && (res.body.error || res.body.Error);
+ return envelope && envelope.message ? `HTTP ${res.status}: ${envelope.message}` : `HTTP ${res && res.status}`;
+}
+
+// `dataverse.get` RESOLVES with `{ status }` on a non-2xx instead of throwing, and rejects only on a
+// transport failure; both are folded into one discriminated answer so no caller can mistake "could not
+// read" for "absent".
+async function read(client, url) {
+ let res;
+ try {
+ res = await client.get(url);
+ } catch (err) {
+ return { state: 'error', why: describe(null, err) };
+ }
+ if (res && res.status === 404) return { state: 'absent' };
+ if (!res || res.status < 200 || res.status >= 300 || !res.body || typeof res.body !== 'object') {
+ return { state: 'error', why: describe(res) };
+ }
+ return { state: 'ok', body: res.body };
+}
+
+// The display name of a table, as one string in the authoring language.
+// GET /EntityDefinitions(LogicalName='account')?$select=LogicalName,DisplayName
+// -> 200 { "LogicalName": "account", "DisplayName": <Label> } (see labelsByLcid)
+// Returns { state: 'ok', label } | { state: 'absent' } | { state: 'error', why }.
+// `label` is null when the table carries none (a table every label of which is blank).
+async function readTableLabel(client, logical, languageCode) {
+ const got = await read(client, `/EntityDefinitions(LogicalName='${odataLit(logical)}')?$select=LogicalName,DisplayName`);
+ if (got.state !== 'ok') return got;
+ return { state: 'ok', label: pickLabel(got.body.DisplayName, languageCode) };
+}
+
+// The labels of some columns of ONE table, each in EVERY language it carries:
+// GET /EntityDefinitions(LogicalName='contoso_task')/Attributes?$select=LogicalName,DisplayName
+// &$filter=LogicalName eq 'contoso_projectid' or LogicalName eq 'contoso_ownerid'
+// -> 200 { "value": [ { "LogicalName": "contoso_projectid", "DisplayName": <Label> }, … ] } (see labelsByLcid)
+// This is the read the vendored SDK itself makes for column hints (`readColumnHints`: one `Attributes`
+// request filtered by logical name, in batches of 40), so one request covers every lookup of a table where
+// a keyed read per lookup cost one each on every rebuild. `DisplayName` is declared on the base
+// AttributeMetadata type, so no cast is needed, and a column the table lacks is simply absent from `value`.
+// All languages, not one: the rebuild repair applies only to a label written in a single language — the old
+// default was — and must be able to see that a second one is there.
+// Returns { state: 'ok', byColumn: Map(logical -> { "1033": "…" }) } | { state: 'absent' } (the TABLE is not
+// there) | { state: 'error', why }.
+const COLUMN_READ_BATCH = 40;
+async function readColumnLabels(client, entityLogical, columnLogicals) {
+ const names = [...new Set((columnLogicals || []).map((c) => String(c).toLowerCase()).filter(Boolean))];
+ const byColumn = new Map();
+ for (let i = 0; i < names.length; i += COLUMN_READ_BATCH) {
+ const filter = names.slice(i, i + COLUMN_READ_BATCH).map((n) => `LogicalName eq '${odataLit(n)}'`).join(' or ');
+ const got = await read(client, `/EntityDefinitions(LogicalName='${odataLit(entityLogical)}')/Attributes?$select=LogicalName,DisplayName&$filter=${filter}`);
+ if (got.state !== 'ok') return got;
+ if (!Array.isArray(got.body.value)) return { state: 'error', why: 'the response carried no value array' };
+ for (const row of got.body.value) {
+ if (row && typeof row.LogicalName === 'string') byColumn.set(row.LogicalName.toLowerCase(), labelsByLcid(row.DisplayName));
+ }
+ }
+ return { state: 'ok', byColumn };
+}
+
+// A memoizing reader for the display names of parent tables the spec cannot name (see
+// lookupParentNeedsEnvironment, app-spec.js). One read per table per build however many lookups point at
+// it. Returns null when there is no raw client to read with (a test double), so callers fall back to the
+// humanized name without pretending to have asked.
+//
+// A failed read is reported ONCE per table through `warn` and cached as "no label", so a lookup to a
+// table the environment would not answer for falls back to a humanized name rather than failing a
+// build over a label.
+function makeTableLabelReader({ provision, languageCode, warn }) {
+ const client = provision && provision.dataverse;
+ if (!client || typeof client.get !== 'function') return null;
+ const cache = new Map();
+ return (logical) => {
+ const key = String(logical).toLowerCase();
+ if (!cache.has(key)) {
+ cache.set(key, readTableLabel(client, key, languageCode).then((got) => {
+ if (got.state === 'ok') return got.label;
+ if (got.state === 'error' && typeof warn === 'function') {
+ warn(`could not read the display name of table '${key}' (${got.why}), so a lookup to it that sets no lookup.displayName is labelled with the table's name instead. Set lookup.displayName, or rename the column in Maker.`);
+ }
+ return null;
+ }));
+ }
+ return cache.get(key);
+ };
+}
+
+// `<referencing>|<lookup logical>`, the identity a lookup column has across the data-model result, the
+// rebuild repair and the forms phase.
+function lookupKey(rel) {
+ return `${String(rel.referencing).toLowerCase()}|${String((rel.lookup && rel.lookup.schemaName) || '').toLowerCase()}`;
+}
+
+// Are two spec labels the same label? A string equals a string; an LCID map equals a map with the same
+// languages and text. A string and a map never are: a rebuild writes them differently (one language vs
+// several), which is the difference the download must not erase.
+function sameLabel(a, b) {
+ if (typeof a === 'string' && typeof b === 'string') return a === b;
+ if (a && b && typeof a === 'object' && typeof b === 'object' && !Array.isArray(a) && !Array.isArray(b)) {
+ const keys = Object.keys(a);
+ return keys.length === Object.keys(b).length && keys.every((k) => a[k] === b[k]);
+ }
+ return false;
+}
+
+module.exports = { labelsByLcid, pickLabel, readMetadata: read, readTableLabel, readColumnLabels, makeTableLabelReader, lookupKey, sameLabel };
diff --git a/plugins/model-apps/scripts/lib/pageref-resolver.js b/plugins/model-apps/scripts/lib/pageref-resolver.js
index 7c7ea1bf4..98f39a476 100644
--- a/plugins/model-apps/scripts/lib/pageref-resolver.js
+++ b/plugins/model-apps/scripts/lib/pageref-resolver.js
@@ -1,5 +1,5 @@
'use strict';
-const { blankNonCodePreservingTemplateExpressions, isTrivia } = require('./source-literals.js');
+const { blankNonCodePreservingTemplateExpressions, isTrivia, isLineTerminator } = require('./source-literals.js');
// Pure STRUCTURAL resolver for generative-page cross-page navigation. Authors emit a link as a stable
// symbolic token — pageId: "PAGEREF_<key>" — because the real GenPageId is minted by the server at
@@ -191,7 +191,8 @@ function matchBrackets(mask) {
// tag`x`(navigateTo)({ … }) a back-tick ends an operand: a tagged template
// function () { return f; }(navigateTo)({ … }) `}` ends an operand: a function expression — which the `}` of a block cannot be told from
// So the last token before the `(` must be the start of the source; `;` `{` `(` `[` `,` or `:`; a `?` that is a ternary (`?.` ends in
-// a `.`); an operator that ends in `=` (`=` `==` `===` `!=` `!==` `+=` `<=` `>=` …); `=>`; or `&&`, `||` or `??`. Anything else is
+// a `.`); an operator that ends in `=` (`=` `==` `===` `!=` `!==` `+=` `<=` `>=` …); `=>`; `&&`, `||` or `??`; or the keyword `return` on the
+// line of the `(` (followsReturnKeyword). Anything else is
// refused — a name or keyword, `)`, `]`, `.`, `?.`, `}`, `!`, any other `>`, a quote or a back-tick, `++`, `--`, the other operators —
// and the token in the call is reported as stray: the plain `navigateTo({ … })` is the one to write. Comments are blank in the
// mask, so they are not tokens.
@@ -204,10 +205,37 @@ function parenBeginsExpression(mask, at) {
return true;
case '>': return mask[i - 1] === '=';
case '&': case '|': return mask[i - 1] === mask[i];
- default: return false;
+ default: return followsReturnKeyword(mask, i, at);
}
}
+// Whether the token that ends at `last`, before the `(` at `open`, is the keyword `return` that starts a return statement, so that the expression after it begins at the `(`:
+// return (navigateTo)({ … });
+// TypeScript's `parseReturnStatement` reads an expression after `return` when one starts on the same line (https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts), and a
+// `(` starts one, so `(navigateTo)` is the callee of a call and the object is its argument. That holds in every program that parses, because `return` is a reserved word: a name only after a `.`
+// (`a.return(navigateTo)({ … })` hands the object to what `a.return(navigateTo)` returns) or as a member's own name, where a `(` that follows is the parameter list of a method that has no body here.
+// Three things are checked, each of which would read another program:
+// - a line terminator between `return` and the `(` — a block comment that holds one included, which the mask keeps — is automatic semicolon insertion at a restricted production
+// (https://tc39.es/ecma262/#sec-automatic-semicolon-insertion): the statement is `return;` and the `(navigateTo)({ … })` after it is a statement of its own that never runs. Both are calls of
+// navigateTo, but the page does not navigate, so the call is no proof of an edge: refused;
+// - the word is the whole of `return`: what stands right before it is white space or one of `;` `{` `)` `:` (or the start of the source), so it is no tail of a longer name (`xreturn`, `$return`,
+// `1return`, `a.#return`) and no escape's end (`\u0061return` ends in a hex digit, and `}` is not allowed before it because `\u{61}return` ends in one);
+// - the token before it, past white space and comments, is no `.` (a `?.` ends in one): a member named `return`.
+// `await` and `yield` are not listed, for the reason the lexer has a guess for `<await` (opensTypeParameters): they are keywords only inside an async function or a generator (`await` also at the top
+// level of a module) and identifiers anywhere else. TypeScript parses `function f() { await (navigateTo)({ … }) }` with no diagnostic, as a call of `await(navigateTo)` whose result is called with the
+// object, which does not navigate; and the lexer does not track the function around a token, so both stay refused.
+const RETURN_PREDECESSORS = ';{):';
+function followsReturnKeyword(mask, last, open) {
+ const start = last - 5;
+ if (start < 0 || mask.slice(start, last + 1) !== 'return') return false;
+ for (let k = last + 1; k < open; k += 1) if (isLineTerminator(mask[k])) return false;
+ const before = mask[start - 1];
+ if (before !== undefined && !isTrivia(before) && !RETURN_PREDECESSORS.includes(before)) return false;
+ let k = start - 1;
+ while (k >= 0 && isTrivia(mask[k])) k -= 1;
+ return mask[k] !== '.';
+}
+
// Whether the mask between `from` and `to` is a member chain and nothing more — `navigateTo`, `Xrm.Navigation.navigateTo`,
// `xrm?.Navigation?.["navigateTo"]`: identifiers joined by `.` and `?.`, or a computed member holding one string literal.
function isMemberChain({ mask, match }, from, to) {
diff --git a/plugins/model-apps/scripts/lib/process-runner.js b/plugins/model-apps/scripts/lib/process-runner.js
index 80364e1bb..c3d1e4e30 100644
--- a/plugins/model-apps/scripts/lib/process-runner.js
+++ b/plugins/model-apps/scripts/lib/process-runner.js
@@ -215,17 +215,128 @@ function spawnProcess(name, args, options = {}, deps = {}) {
return childProcess.spawn(inv.file, inv.args, withOptions(inv, options));
}
+// One `ps` listing line: `<pid> <ppid>`, optionally followed by the process's start time (`lstart`, which killProcessTree asks for), in any
+// spacing, with no header (the `=` after each name blanks it):
+// 100 1 Mon Oct 12 09:00:01 2026
+// 4242 100 Mon Oct 12 09:12:30 2026
+// 5000 4242 Mon Oct 5 09:12:31 2026
+// The start time is kept as the text ps printed, with its runs of spaces made one: it is only ever compared with what ps prints for the same pid
+// moments later, in the same environment, so its format and locale do not matter.
+const PS_LINE = /^\s*(\d+)\s+(\d+)(?:\s+(\S.*?))?\s*$/;
+
+// The pids under `rootPid` in such a listing. Parents come before their children (breadth first). Lines that are not a pid and a parent pid are
+// skipped, and a process listed twice, or two that name each other as parent, are read once, so a damaged listing cannot loop.
+function descendantPids(rootPid, listing) {
+ const children = new Map();
+ for (const line of String(listing == null ? '' : listing).split(/\r?\n/)) {
+ const pair = PS_LINE.exec(line);
+ if (!pair) continue;
+ const parent = Number(pair[2]);
+ if (!children.has(parent)) children.set(parent, []);
+ children.get(parent).push(Number(pair[1]));
+ }
+ const found = [];
+ const seen = new Set([rootPid]);
+ const queue = [rootPid];
+ for (let i = 0; i < queue.length; i += 1) {
+ for (const pid of children.get(queue[i]) || []) {
+ if (seen.has(pid)) continue;
+ seen.add(pid);
+ found.push(pid);
+ queue.push(pid);
+ }
+ }
+ return found;
+}
+
+// Each pid's start time in such a listing, as `PS_LINE` reads it; a line with none gives none.
+function startTimes(listing) {
+ const started = new Map();
+ for (const line of String(listing == null ? '' : listing).split(/\r?\n/)) {
+ const row = PS_LINE.exec(line);
+ if (row && row[3]) started.set(Number(row[1]), row[3].replace(/\s+/g, ' '));
+ }
+ return started;
+}
+
+// Whether `pid` still names the process a listing saw, read again just before it is signalled: `ps -o lstart= -p <pid>` must print the same start
+// time. A descendant can exit after the listing, and its pid can then be given to an unrelated process — signalling the number would end that one.
+// A pid the listing gave no start time for, one that is gone (ps exits 1 and prints nothing) and one that now started at another time are all left
+// alone. This is best effort, not an identity the kernel keeps: two processes can share a start time (it is to the second), so a pid given out again
+// within the second its first holder started passes; and a pid given out again after this read and before the signal is not seen, whatever its start.
+function stillTheSame(pid, startedAt, run) {
+ if (!startedAt) return false;
+ try {
+ const now = run('ps', ['-o', 'lstart=', '-p', String(pid)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 15000 });
+ return !!now && now.status === 0 && String(now.stdout == null ? '' : now.stdout).replace(/\s+/g, ' ').trim() === startedAt;
+ } catch {
+ return false;
+ }
+}
+
+// Ends `child` AND everything it started, for a call that ran out of time. Killing only the process that was started is not enough: on Windows
+// `pac.cmd` is a shim — cmd.exe, which runs pac.exe — so ending cmd.exe leaves the stalled pac running and holding its connections. A tree is
+// ended by `taskkill /T /F` on Windows (https://learn.microsoft.com/windows-server/administration/windows-commands/taskkill) and, elsewhere, by
+// SIGKILL to each process `ps` lists under it (SIGKILL, not SIGTERM: a stalled process may ignore that) — the child first, so it can start nothing
+// more, then its descendants deepest first, each only once `ps` shows that its pid still has the start time the listing saw (stillTheSame — best
+// effort, as it says). Both tools
+// are started through spawnResultSync, the audited call above, so each is resolved to an absolute executable on PATH and never taken from the current
+// directory. This never throws, whatever has gone wrong: the caller is already handling a failure, and a process that is already gone, a tool that is
+// absent or one that times out still end with the child itself asked to die.
+// `env` is the environment the tools are looked up in (a seam for the tests).
+//
+// A child that has ALREADY EXITED is not ended by its pid. Node's 'exit' can come before 'close' when a process the child started still holds its pipes — the very case a call that
+// runs out of time is stopped in — and by then the number can belong to another process: Windows reuses ids at once, and a tree kill by it would end that process and everything it started.
+// There is no tree to walk from a process that is gone, either: what it started was re-parented, and taskkill /T and the `ps` walk both start from a live pid. So such a child is only asked to
+// die (a no-op), and whatever it left running is what the caller's own deadline already gave up on.
+function killProcessTree(child, { platform = process.platform, env = process.env, run = spawnResultSync, kill = (pid, signal) => process.kill(pid, signal) } = {}) {
+ const pid = child && child.pid;
+ const endChild = () => {
+ try { if (child && typeof child.kill === 'function') child.kill('SIGKILL'); } catch { /* already gone */ }
+ };
+ if (!Number.isInteger(pid) || pid <= 0) { endChild(); return; }
+ // `exitCode` and `signalCode` are null while a ChildProcess runs; an object that is not one (a test's stand-in) has neither, which reads as running.
+ if (child.exitCode != null || child.signalCode != null) { endChild(); return; }
+ try {
+ if (platform === 'win32') {
+ // taskkill.exe lives in System32, next to cmd.exe. The lookup reads PATH like every executable here, and a PATH without that folder — a service, a CI
+ // runner, a stripped-down shell — would make the kill find nothing and leave the stalled tree running, so System32 goes FIRST on the PATH this one lookup
+ // reads. First also means no earlier, user-writable folder on PATH can stand in for taskkill. The caller's own environment is not changed.
+ // Exits 128 when the process is already gone, which is the outcome wanted. windowsHide: no console window opens for the kill — spawnResultSync's own lookup
+ // (invocation) already hides every child's window, and it is stated here too so that the kill stays hidden whichever `run` is in use.
+ run('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore', timeout: 15000, windowsHide: true },
+ { env: withPathFirst(env, path.win32.dirname(windowsCmd(env)), 'win32') });
+ endChild();
+ } else {
+ const listing = run('ps', ['-A', '-o', 'pid=,ppid=,lstart='], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 15000 });
+ const listed = listing && listing.status === 0;
+ const under = listed ? descendantPids(pid, listing.stdout) : [];
+ const started = listed ? startTimes(listing.stdout) : new Map();
+ endChild();
+ for (const descendant of under.reverse()) {
+ if (!stillTheSame(descendant, started.get(descendant), run)) continue;
+ try { kill(descendant, 'SIGKILL'); } catch { /* already gone */ }
+ }
+ }
+ } catch {
+ endChild();
+ }
+}
+
module.exports = {
CMD_INERT_ARG,
cmdArgument,
+ descendantPids,
envValue,
withOptions,
execFileAsync,
invocation,
+ killProcessTree,
resolveExecutable,
runSync,
spawnProcess,
spawnResultSync,
+ startTimes,
windowsCmd,
withPathFirst,
};
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/lib/provision-input.js b/plugins/model-apps/scripts/lib/provision-input.js
index cbf02386c..370f6482f 100644
--- a/plugins/model-apps/scripts/lib/provision-input.js
+++ b/plugins/model-apps/scripts/lib/provision-input.js
@@ -5,7 +5,7 @@
// App-Spec subset: { solution, entities, relationships, globalChoices?, sampleData? }.
// Entities carry FULL schema names (e.g. cr_candidate), not bare suffixes.
-const { TYPE_MAP, normalizeLanguageCode, validateLabel, validateChoiceOptionLabels, isLocalizedLabelMap, labelIsMissing, rejectLocalizedGlobalChoice, validateSampleDataRows, ENTITY_KEYS, ENTITY_KEY_HINTS, invalidLanguageCodeMessage, relationshipNameCollisions, relationshipCollisionMessage } = require('./app-spec.js');
+const { TYPE_MAP, normalizeLanguageCode, validateLabel, validateChoiceOptionLabels, isLocalizedLabelMap, labelIsMissing, rejectLocalizedGlobalChoice, validateSampleDataRows, ENTITY_KEYS, ENTITY_KEY_HINTS, invalidLanguageCodeMessage, relationshipNameCollisions, relationshipCollisionMessage, primaryNameLengthProblem } = require('./app-spec.js');
// Validates provision-entities input. Returns { ok, errors }.
function validateProvisionInput(input) {
@@ -132,6 +132,13 @@ function validateProvisionInput(input) {
} else if (!e.primaryAttribute.schemaName || typeof e.primaryAttribute.schemaName !== 'string') {
errors.push(`entity '${e.schemaName}': primaryAttribute.schemaName is required and must be a string`);
}
+ // The length of the name column goes into BOTH table creates as the request's MaxLength, so a value the platform would
+ // refuse — or a string, which it would be sent as — has to stop here, before the solution is written. It is the rule
+ // validateAppSpec applies (one function), because this gate is the only one /genpage and /app-builder pass through.
+ if (e.primaryAttribute && typeof e.primaryAttribute === 'object') {
+ const lengthProblem = primaryNameLengthProblem(e.primaryAttribute.maxLength);
+ if (lengthProblem) errors.push(`entity '${e.schemaName}': ${lengthProblem}`);
+ }
// Validate columns
if (Array.isArray(e.columns)) {
diff --git a/plugins/model-apps/scripts/lib/schema-facts.js b/plugins/model-apps/scripts/lib/schema-facts.js
index c4f80c6e7..dddf838e3 100644
--- a/plugins/model-apps/scripts/lib/schema-facts.js
+++ b/plugins/model-apps/scripts/lib/schema-facts.js
@@ -6,7 +6,7 @@
// offline eval harness diffs per build. Pure (no I/O, no SDK): it derives everything deterministically
// from the App Spec, reusing the SAME naming/value rules the engine uses, so a fact equals what WOULD
// be provisioned — not a naive spec echo. See docs/app-builder-design.md §13.2, §14.
-const { columnTypeMap, choiceValueMap, relationshipSchemaName, manyToManySchemaName, quickCreateEnabledFor, labelText } = require('./app-spec.js');
+const { columnTypeMap, choiceValueMap, relationshipSchemaName, manyToManySchemaName, quickCreateEnabledFor, labelText, lookupLabelFor } = require('./app-spec.js');
const lc = (s) => String(s || '').toLowerCase();
const byKey = (k) => (a, b) => (a[k] < b[k] ? -1 : a[k] > b[k] ? 1 : 0);
@@ -70,7 +70,9 @@ function relationshipFacts(spec) {
for (const r of spec.relationships || []) {
if (r.type === 'OneToMany') {
rels.push({ kind: '1:n', schemaName: lc(relationshipSchemaName(r, prefix)), referenced: lc(r.referenced), referencing: lc(r.referencing),
- lookup: { logicalName: lc(r.lookup && r.lookup.schemaName), displayName: labelText(r.lookup && r.lookup.displayName, spec && spec.languageCode) || '' } });
+ // The label the build WRITES, not the one the author typed: an omitted lookup.displayName defaults
+ // to the parent table's name (lookupLabelFor), so a fact that echoed the spec would be empty.
+ lookup: { logicalName: lc(r.lookup && r.lookup.schemaName), displayName: labelText(lookupLabelFor(spec, r).label, spec && spec.languageCode) || '' } });
} else if (r.type === 'ManyToMany') {
const fact = { kind: 'n:n', schemaName: lc(manyToManySchemaName(r, prefix)), entity1: lc(r.entity1), entity2: lc(r.entity2) };
if (r.intersectEntityName) fact.intersect = lc(r.intersectEntityName);
diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.js
index f2cc5d451..d9fbc0577 100644
--- a/plugins/model-apps/scripts/lib/sdk-build.js
+++ b/plugins/model-apps/scripts/lib/sdk-build.js
@@ -32,6 +32,7 @@ const {
manyToManySchemaName,
normalizePageSource,
quickCreateEnabledFor,
+ askedPrimaryNameLength,
isPlatformIconRef,
FORM_TYPE_CODE,
formIdentityKey,
@@ -43,6 +44,10 @@ const {
choiceValueMap,
BPF_ROLE_ACCESS,
dashboardNameKey,
+ formLayoutNames,
+ subgridRelationshipName,
+ lookupLabelFor,
+ lookupParentNeedsEnvironment,
} = require('./app-spec.js');
const { PHASES } = require('./stages.js');
const { topoOrderEntities, entityByLogical } = require('./_graph.js');
@@ -73,7 +78,11 @@ const {
findExistingColumns,
relationshipExists,
localizedLabelLcidsInSpec,
+ lookupsWithDefaultLabel,
+ relationshipsInCreateOrder,
} = require('./entity-provision.js');
+const { repairLookupCellLabels } = require('./lookup-cell-labels.js');
+const { hasLabelUses, makeChoiceReader, makeGlobalChoiceReader, resolveViewFilterLabels, checkViewFilterLabelsBeforeBuild, describeProblem, describeProblems } = require('./view-filter-labels.js');
// Pure App Spec -> canonical SDK intent compiler (new form topology + generic-surface intents).
const {
compileFormIntent,
@@ -82,9 +91,11 @@ const {
findFieldCellPointer,
findFieldCellLocation,
findSectionLocation,
+ findSectionById,
declaredSectionByField,
subgridCellIntent,
subgridSectionIntent,
+ notesSectionIntent,
quickViewCellIntent,
formEventsRegionIntent,
viewColumnsIntent,
@@ -95,6 +106,8 @@ const {
const { makeGenpageCli, suppliedButBlank, unescapePacName } = require('./genpage-cli.js');
const { matchContainer, isEngineOwnedSection, isEngineHostSection, holdsControlOf, claimedByAuthoredName, planOrderMoves } = require('./form-container-match.js');
const { rowOccupancy, fitsGrid, strandedRows } = require('./form-occupancy.js');
+const { TIMELINE_CONTROL_ID, FULL_BUILD, timelineInSection, controlIdTaken, timelineRepairPlan, timelineRefusal } = require('./form-timeline.js');
+const { placementOf, resolvePlacement, columnSequence, neighbourOf, findGridSection: findSubgridSection } = require('./form-subgrid-placement.js');
const { manifestResourceName, buildManifest, serializeManifest, parseManifestBase64, reconcilePageIds } = require('./page-manifest.js');
// MEMBERSHIP authority (the app's live sitemap) + the cross-app shared-page scan. fetchSitemap is
// fail-closed & discriminated (C4); fetchAppsForPages is the only way to prove a generative page is not
@@ -103,13 +116,17 @@ const { fetchSitemap, navigationProof, fetchAppsForPages } = require('./sitemap-
// Structural nav oracle — used in the §9 PAGEREF_ scan/parity/resolve pipeline. `extractNavTargets`
// classifies every generative navigateTo pageId at a REAL call site (never a decoy string / comment GUID).
const { extractNavTargets, navReferencedKeys, navMalformedRefs, resolvePageRefs, navTargetParity, strayPageRefs, describePageRefLocations, pageRefAdvice, frontierNote, PAGEREF_RULE } = require('./pageref-resolver.js');
+const { griffelStyleProblems, describeGriffelRefusal, describeGriffelWarning } = require('./griffel-styles.js');
+const { recordedContentSha } = require('./content-hash.js');
const { selectSummaryTables } = require('./ai-candidates.js');
-const { AI_APP_SETTING, resolveAiFlags, encodeAiFlags, rebucketNonEnablingSkips, specOptsIntoAi, featureWantValue, sameSettingValue, resolveAppModuleId, proveAppOverride } = require('./ai-app-settings.js');
+const { AI_APP_SETTING, resolveAiFlags, encodeAiFlags, rebucketNonEnablingSkips, rebucketPendingPublish, specOptsIntoAi, featureWantValue, sameSettingValue, resolveAppModuleId, proveAppOverride, proofBudget } = require('./ai-app-settings.js');
const { DASHBOARD_LAUNCHER_URL, adoptLiveSitemap, chromeByTargetKey, describeSitemapNotes } = require('./sitemap-merge.js');
const { buildPromptSpec } = require('./ai-prompt.js');
const { odataLit } = require('./odata.js');
const { isRestrictedSolution } = require('./system-solutions.js');
const { tableRefs, pinAppTables, publishAppComponents, resolveMainForms, appComponentsFor, applyAppMainForms, explainAppPushWarnings } = require('./app-components.js');
+const { hasUnsyncedEdits } = require('./unsynced-edits.js');
+const { createSolutionMembership, ensureSolutionComponent } = require('./solution-membership.js');
// Re-export from entity-provision so the export surface stays unchanged
const BuildHalt = _BuildHalt;
@@ -403,14 +420,22 @@ function resolvePhases({ only, skip, from, to } = {}) {
// Resolve a view-filter value: a Choice/MultiChoice label becomes its option int; everything
// else (raw ints, strings, ISO dates) passes through. No-value operators omit the value entirely.
//
-// Resolution goes through `choiceValueMap`, the SHARED rule, rather than `options.indexOf(val)`.
+// `resolution` (ADO 6691114, lib/view-filter-labels.js) is what the build resolved against the
+// ENVIRONMENT's option metadata before it wrote any view. It answers first, because the spec can only prove
+// a value for an option set this build created: 100000000 + index is wrong for a global choice that already
+// existed with other values, and the spec says nothing of a column it does not declare. Without one — a
+// caller with no environment to read, `viewDef(spec, v)` in a test — this is the spec-only rule it always was.
+//
+// The spec-only rule goes through `choiceValueMap`, the SHARED rule, rather than `options.indexOf(val)`.
// Two reasons, and the first is a real defect the naive version had: a LOCALIZED option is an
// object (`{ "1033": "Open", "3082": "Abierto" }`), so `indexOf("Abierto")` returns -1 and the
// LABEL was sent as the value of a numeric picklist condition — an invalid or silently ineffective
// view filter. The second is that `choiceValueMap` also resolves a column bound to a `globalChoice`,
// which the inline-only lookup never did.
-function resolveFilterValue(spec, entityLogical, attr, val) {
+function resolveFilterValue(spec, entityLogical, attr, val, resolution) {
if (typeof val !== 'string') return val;
+ const resolved = resolution ? resolution.value(entityLogical, attr, val) : undefined;
+ if (resolved !== undefined) return resolved;
const e = entityByLogical(spec, entityLogical);
const c = e && (e.columns || []).find((x) => x.schemaName.toLowerCase() === String(attr).toLowerCase());
if (!c || (c.type !== 'Choice' && c.type !== 'MultiChoice')) return val;
@@ -483,17 +508,43 @@ function planFor(spec, opts) {
for (const sr of e.statusReasons || []) items.push({ phase: 'data-model', label: `status reason ${e.schemaName}: ${sr.label}` });
for (const k of e.alternateKeys || []) items.push({ phase: 'data-model', label: `alt key ${e.schemaName}.${k.schemaName}` });
}
- for (const r of spec.relationships || []) {
+ // The relationships in the order the data-model phase creates them (relationshipsInCreateOrder): localized
+ // lookups first. The plan lists what the build does, in the order it does it.
+ for (const r of relationshipsInCreateOrder(spec)) {
if (r.type === 'OneToMany') items.push({ phase: 'data-model', label: `relationship 1:N ${r.referenced}->${r.referencing}`, key: { kind: 'relationship', entity: r.referenced, name: relationshipSchemaName(r, relPrefix), relType: 'OneToMany', declared: r } });
else if (r.type === 'ManyToMany') items.push({ phase: 'data-model', label: `relationship N:N ${r.entity1}<->${r.entity2}`, key: { kind: 'relationship', entity: r.entity1, name: manyToManySchemaName(r, relPrefix), relType: 'ManyToMany', declared: r } });
}
+ // ADO 6691205: one step per lookup whose label the build owns (the spec sets none). On a rebuild it
+ // repairs a column an older build labelled with its old default; on a fresh build it is a skip. The
+ // predicate is the one the data-model phase emits by, so [n/total] holds.
+ for (const r of lookupsWithDefaultLabel(spec)) {
+ const { label, source } = lookupLabelFor(spec, r);
+ const parent = String(r.referenced).toLowerCase();
+ const humanized = `"${labelText(label, spec && spec.languageCode)}"`;
+ let shown = humanized;
+ if (source === 'derived') {
+ // A parent whose name the spec cannot give (a table it does not declare, or an `existing: true` one it
+ // declares without a displayName) is named by the environment at build time; the spec cannot say how.
+ if (lookupParentNeedsEnvironment(spec, r)) shown = `the display name of ${parent}`;
+ // A declared table with no displayName that is not flagged: the build creates it, or finds it already
+ // there and takes its label from the environment — which the plan cannot know, so it says both.
+ else if (entityByLogical(spec, r.referenced)) shown = `${humanized}, or the label from the environment if ${parent} is already there`;
+ }
+ items.push({ phase: 'data-model', label: `lookup label ${String(r.referencing).toLowerCase()}.${r.lookup.schemaName} (default ${shown})` });
+ }
+ // Present exactly when the spec gives a name column a length: provisionDataModel narrates one step for it either way (run, or
+ // skipped with the reason), so the count holds. Listed after the relationships and the lookup labels because that is where the build sets the
+ // length of a table it creates: once every labelled create and repair of the phase is done.
+ for (const e of spec.entities) {
+ if (askedPrimaryNameLength(e) !== undefined) items.push({ phase: 'data-model', label: `primary column length ${e.schemaName}.${e.primaryAttribute.schemaName}` });
+ }
}
if (has('sample-data') && opts.sampleData) {
for (const e of spec.entities) { const n = sampleRecordsFor(spec, e).length; if (n) items.push({ phase: 'sample-data', label: `${n} sample record(s) -> ${e.schemaName}` }); }
}
if (has('web-resources')) for (const wr of spec.webResources || []) items.push({ phase: 'web-resources', label: `web resource ${wr.name} (${wr.type || 'js'})` });
if (has('web-resources')) for (const e of spec.entities || []) if (e.icon || e.vectorIcon) items.push({ phase: 'web-resources', label: `table icon for ${e.schemaName.toLowerCase()}` });
- if (has('views')) for (const v of spec.views || []) items.push({ phase: 'views', label: `view "${v.name}" for ${v.entity}`, key: { kind: 'view', entity: v.entity, name: v.name } });
+ if (has('views')) for (const v of spec.views || []) items.push({ phase: 'views', label: `view "${v.name}" for ${v.entity}`, key: { kind: 'view', entity: v.entity, name: v.name, declared: v } });
if (has('views')) for (const e of spec.entities || []) if (enrichesDefaultViews(spec, e)) items.push({ phase: 'views', label: `enrich default views for ${e.schemaName.toLowerCase()}` });
if (has('charts')) for (const c of spec.charts || []) items.push({ phase: 'charts', label: `chart "${c.name}" (${c.chartType}) for ${c.entity}`, key: { kind: 'chart', entity: c.entity, name: c.name } });
if (has('forms')) for (const f of spec.forms || []) {
@@ -603,7 +654,7 @@ async function subgridViewId(provision, createdViews, spec, sg, childLogical) {
return def && def.savedqueryid;
}
-function viewDef(spec, v) {
+function viewDef(spec, v, resolution) {
const entityLogical = v.entity.toLowerCase();
const cols = (v.columns && v.columns.length ? v.columns : [primaryNameOf(spec, entityLogical)]).map((name, i) => ({ name: String(name).toLowerCase(), width: 100, order: i }));
const conditions = [];
@@ -614,11 +665,11 @@ function viewDef(spec, v) {
const op = f.op || 'eq';
if (op === 'in' || op === 'not-in') {
const subOp = op === 'in' ? 'eq' : 'ne';
- const vals = (f.values || []).map((x) => resolveFilterValue(spec, entityLogical, attr, x));
+ const vals = (f.values || []).map((x) => resolveFilterValue(spec, entityLogical, attr, x, resolution));
groups.push({ type: op === 'in' ? 'or' : 'and', conditions: vals.map((x) => ({ attribute: attr, operator: subOp, value: String(x) })), groups: [] });
} else {
const cond = { attribute: attr, operator: op };
- if (f.value !== undefined) cond.value = String(resolveFilterValue(spec, entityLogical, attr, f.value));
+ if (f.value !== undefined) cond.value = String(resolveFilterValue(spec, entityLogical, attr, f.value, resolution));
conditions.push(cond);
}
}
@@ -627,6 +678,121 @@ function viewDef(spec, v) {
sort: (v.sort || []).map((s) => ({ attribute: String(s.attr).toLowerCase(), descending: s.dir === 'desc' })) };
}
+// The raw-client readers every view-label check shares. `read` is null with no client to ask (a test double), and
+// every check then does what it did before there was one.
+function viewLabelReaders(spec, provision) {
+ const client = provision && provision.dataverse;
+ const languageCode = spec && spec.languageCode;
+ return { read: makeChoiceReader({ client, languageCode }), readGlobalChoice: makeGlobalChoiceReader({ client, languageCode }) };
+}
+
+// What the build says of a view that already exists whose spec filters on a label that names no option: `reconcileView`
+// never reapplies an existing view's filters, so nothing stops — but verify reads the spec's label, and will report it.
+// The dry run says the same, so the user hears it before the apply rather than from `--verify`.
+const existingViewLabelNote = (p) => {
+ // `ambiguous` is a label that names several options; anything else is one that names none. The first sentence says which, so the
+ // reason that follows (the numbers the label sits on, or the refusal of the spec's own number) is not left to contradict it.
+ const what = p.reason === 'ambiguous'
+ ? `"${p.label}" names more than one option of ${p.entity}.${p.attr} (${(p.values || []).join(', ')})`
+ : `"${p.label}" is not an option of ${p.entity}.${p.attr}`;
+ return `view "${p.view}" (${p.entity}) already exists, so its filters are left as they are — but ${what}, and verify will report that.${p.refusal ? ` ${p.refusal}` : ''}`;
+};
+
+// Of the view-label `problems`, the ones that may stop the build: those on a view it would CREATE. `reconcileView`
+// never reapplies an existing view's filters, so the label in the spec of a view that is already there changes
+// nothing the build writes (verify still reports it) — that is said once, not raised. The existence lookup is
+// made only once a problem is found, so a build with nothing wrong pays no extra read; when the lookup cannot
+// tell (a table the build has not created yet has no views to find), the view counts as one to create — the
+// fail-closed answer.
+async function blockingViewLabelProblems(problems, { provision, say }) {
+ const existing = new Map();
+ const viewExists = (name, entity) => {
+ const key = `${entity}|${name}`;
+ if (!existing.has(key)) existing.set(key, Promise.resolve().then(() => provision.findArtifact('view', { name, entity })).then((id) => !!id, () => false));
+ return existing.get(key);
+ };
+ const blocking = [];
+ for (const p of problems) {
+ if (await viewExists(p.view, p.entity)) say(existingViewLabelNote(p));
+ else blocking.push(p);
+ }
+ return blocking;
+}
+
+// `beforeAnyWrite`: the pre-flight stops the build before this run has written anything; the views phase, only
+// before it writes a view. The pre-flight is tagged with the phase name the CLI's own pre-flight halts already
+// carry (`preflight`): it is not part of the views phase, which has not started.
+function viewLabelHalt(blocking, { beforeAnyWrite }) {
+ const halt = new BuildHalt(
+ `${blocking.length} view filter value${blocking.length === 1 ? '' : 's'} cannot be resolved to an option of the table. ${beforeAnyWrite ? 'The build stopped before writing anything' : 'No view was written'}:\n${describeProblems(blocking)}`,
+ { phase: beforeAnyWrite ? 'preflight' : 'views', code: 'view-filter-label-unresolved', recoverable: false });
+ // A label the environment shows to be wrong (`unknown`, `ambiguous`) is wrong on a re-run too, so such a halt is never
+ // run again. One that only unanswered option reads left undecided (`unreadable`, each `why` reading e.g. "HTTP 503: …")
+ // may be answered next time, but only when every one of those reads was throttled or unavailable (429, 503): it then
+ // carries that status, which the CLI's retry check (isTransientHalt) reads. Every other halt is marked never-retry,
+ // because the message quotes the user's own filter labels, and a label such as "SQL Timeout" must not read as transient.
+ const statusOf = (p) => { const m = /\bHTTP (\d{3})\b/.exec(String(p.why || '')); return m ? Number(m[1]) : null; };
+ const throttled = blocking.length > 0 && blocking.every((p) => p.reason === 'unreadable' && [429, 503].includes(statusOf(p)));
+ if (throttled) halt.statusCode = statusOf(blocking[0]);
+ else halt.transient = false;
+ return halt;
+}
+
+// The build's pre-flight (ADO 6691114): before the first write of an apply that writes the data model, stop on a
+// view-filter label the environment already shows to be wrong (lib/view-filter-labels.js
+// `checkViewFilterLabelsBeforeBuild`). Without it the first sign was Dataverse rejecting the saved view — after
+// the tables and columns had been written, which left a half-built app for a typo in a filter.
+//
+// Only a DEFINITE answer halts here: a label that depends on something the build is about to create is left
+// to the views phase, which asks again once the data model exists. So is a label the spec's own number stands in
+// for (a maker renamed the option — view-filter-labels.js `specNumberStands`): no problem, and not handed on as
+// final, because the views phase resolves it and WARNS about it, once. Returns what the environment already held
+// and resolved — final, so the views phase takes it as it is (see checkViewFilterLabelsBeforeBuild) — or
+// undefined when nothing was checked.
+//
+// NOT run at all when the spec carries a localized label (AB#6686428). The pre-flight's reads carry labels
+// (every option's, in every language), and the measured hazard — documented on relationshipExists — is that
+// a label-bearing metadata read ahead of a create makes Dataverse keep only the base-language label of a
+// multi-language one, silently. Those reads were never measured to be safe, and a typo in a filter does not
+// justify risking the labels the whole localization feature exists to keep, so a build that may create any
+// localized label (any map on a table, column, option, lookup… — which of them the environment lacks is
+// not knowable without reads) leaves the check to the views phase. That phase runs after every create, so
+// it is still before any view is written; what is lost is only the guarantee that NOTHING was written yet.
+// The dry run is unaffected: it creates nothing, so no create follows its reads.
+async function preflightViewLabels(spec, provision, say) {
+ const labelViews = (spec.views || []).filter((v) => hasLabelUses(spec, v));
+ if (!labelViews.length) return undefined;
+ if (localizedLabelLcidsInSpec(spec).length) return undefined;
+ const { problems, resolved } = await checkViewFilterLabelsBeforeBuild(spec, labelViews, viewLabelReaders(spec, provision));
+ if (problems.length) {
+ const blocking = await blockingViewLabelProblems(problems, { provision, say });
+ if (blocking.length) throw viewLabelHalt(blocking, { beforeAnyWrite: true });
+ }
+ return resolved;
+}
+
+// The views phase's gate (ADO 6691114): the FINAL resolution of every option label a view filters on, against the
+// ENVIRONMENT as the build left it (lib/view-filter-labels.js), halting — before any view is written — on one
+// that names nothing. The alternative is a filter whose value is the label's own text: Dataverse rejects it, or
+// stores it and matches nothing, so a build that "succeeds" would ship it. A fresh reader, not the pre-flight's:
+// the data model has been written since, and what the build created is what this reads. `prior` is what the
+// pre-flight resolved from what already existed — a column, or the global choice a column the build creates is
+// bound to — which the build leaves as it was. A localized spec has no `prior` (its pre-flight is skipped), so a
+// column bound to a global choice whose own options cannot be read is resolved from the set itself.
+//
+// Returns what `viewDef` resolves values with, or null when no view names a label (nothing was read).
+async function resolveViewLabelsOrHalt(spec, provision, say, prior) {
+ const labelViews = (spec.views || []).filter((v) => hasLabelUses(spec, v));
+ if (!labelViews.length) return null;
+ const { read, readGlobalChoice } = viewLabelReaders(spec, provision);
+ const resolution = await resolveViewFilterLabels(spec, labelViews, { read, prior, readGlobalChoice });
+ for (const w of resolution.warnings) say(w);
+ if (!resolution.problems.length) return resolution;
+ const blocking = await blockingViewLabelProblems(resolution.problems, { provision, say });
+ if (!blocking.length) return resolution;
+ throw viewLabelHalt(blocking, { beforeAnyWrite: false });
+}
+
// Pick a "good" default-view column set: the primary name column plus up to DEFAULT_VIEW_MAX_EXTRA
// meaningful declared columns (in declared order), skipping wide/opaque types that read poorly in a
// grid. Used to enrich the auto-generated "Active/Inactive <Entity>" views (which ship with only
@@ -895,8 +1061,11 @@ async function readPageManifest(provision, appUnique) {
// dedup means a single-page first build issues one create + zero updates, an N-new-page first build one
// create + (N-1) updates, and a no-op final persist. Stored as type 'js' (webresourcetype 3): there is no
// 'json' web-resource kind and 'js' round-trips arbitrary text unchanged. Returns { id, content } for the
-// next call. Stable 7-arg signature (Tasks 5 + 8).
-async function persistPageManifest(provision, spec, keyToId, sol, appUnique, existingId, lastContent) {
+// next call. The first seven parameters are the long-standing positional signature; `solutionMembers` is an
+// optional eighth that only spares the add when the solution is proven to hold the manifest already (see
+// solution-membership.js). Every call goes through it, including the one that creates the manifest, which is
+// why a first build that deploys pages makes the membership read.
+async function persistPageManifest(provision, spec, keyToId, sol, appUnique, existingId, lastContent, solutionMembers) {
const name = manifestResourceName(appUnique);
const content = serializeManifest(buildManifest(spec, keyToId));
let id = existingId;
@@ -904,7 +1073,7 @@ async function persistPageManifest(provision, spec, keyToId, sol, appUnique, exi
if (id) await provision.updateWebResource(id, { content });
else { const r = await provision.createWebResource({ name, displayName: `${spec.app.name} Page Manifest`, type: 'js', content }); id = r.id; }
}
- if (id) await provision.addSolutionComponent({ componentId: id, componentType: COMPONENT_TYPE.webResource, solutionUniqueName: sol.uniqueName });
+ if (id) await ensureSolutionComponent(provision, solutionMembers, { componentId: id, componentType: COMPONENT_TYPE.webResource, solutionUniqueName: sol.uniqueName });
return { id, content };
}
@@ -912,12 +1081,12 @@ async function persistPageManifest(provision, spec, keyToId, sol, appUnique, exi
// sitemap only in the Default solution, so the app's own solution is incomplete on export. Resolve
// the sitemap by its unique name (== the app's unique name) and add it. Best-effort + idempotent:
// a re-add of an already-present component is tolerated so this never fails an otherwise-good build.
-async function ensureSitemapInSolution(provision, sol, appUnique) {
+async function ensureSitemapInSolution(provision, sol, appUnique, solutionMembers) {
try {
const rows = await provision.queryRecords('sitemap', { select: ['sitemapid'], filter: `sitemapnameunique eq '${odataLit(appUnique)}'`, top: 1 });
const sitemapId = rows && rows[0] && rows[0].sitemapid;
if (!sitemapId) return;
- await provision.addSolutionComponent({ componentId: sitemapId, componentType: COMPONENT_TYPE.sitemap, solutionUniqueName: sol.uniqueName });
+ await ensureSolutionComponent(provision, solutionMembers, { componentId: sitemapId, componentType: COMPONENT_TYPE.sitemap, solutionUniqueName: sol.uniqueName });
} catch { /* best-effort — the app + its sitemap already exist; a component-pin hiccup must not fail the build */ }
}
@@ -937,14 +1106,23 @@ function appHasCrossPageNav(spec) {
return ((spec && spec.pages) || []).some((p) => (p.navigatesTo || []).length > 0);
}
-// Write a RESOLVED deployment copy of a page's .tsx into the run-scoped staging dir — NEVER over the
-// canonical source (a GUID baked into canonical breaks cross-env recreate; design §9 / SDK T5). pac
-// genpage upload takes a file PATH, so resolved bytes must exist on disk. The dir is created per RUN
-// under <workspace>/.pageref-deploy/<runId>/ and removed in a finally (never leave env GUIDs on disk,
-// no sanitized-name cross-run collision). The key is sanitized to a safe filename.
+// Write the copy of a page's .tsx that pac uploads into the run-scoped staging dir — NEVER over the canonical
+// source. Every page is sent from one. A navigation page's copy has its PAGEREF_ tokens resolved (a GUID baked
+// into canonical breaks cross-env recreate; design §9 / SDK T5); every other page's copy is the bytes the pages
+// scan read and checked, so a save to the canonical file while the build runs cannot ship unchecked, and the
+// source hash the build records is the one of what it sent. pac genpage upload takes a file PATH, so the bytes
+// must exist on disk. The dir is created per RUN under <workspace>/.pageref-deploy/<runId>/ and removed in a
+// finally (never leave env GUIDs on disk, no sanitized-name cross-run collision). The key is sanitized to a safe
+// filename, behind a fixed `page-` prefix: Windows reserves the device names CON, PRN, AUX, NUL, COM1-9 and LPT1-9
+// (the digit may also be a superscript ¹ ² ³) as a file name with or without an extension — `NUL.txt` is NUL
+// (https://learn.microsoft.com/windows/win32/fileio/naming-a-file) — and a page key is a slug that can be one
+// (`con`, `com1`). Where a release treats such a name as the device, `con.tsx` is not a file at all, and pac would be
+// handed the console, or nothing. Windows 11 (build 26200, measured) writes `con.tsx` as an ordinary file, but the
+// name is ours to choose, so no key comes near the rule. `code` is a string, or the Buffer the scan read (written
+// byte for byte).
function writeStagingFile(stagingDir, key, code) {
fs.mkdirSync(stagingDir, { recursive: true });
- const file = path.join(stagingDir, `${String(key).replace(/[^A-Za-z0-9_-]/g, '_')}.tsx`);
+ const file = path.join(stagingDir, `page-${String(key).replace(/[^A-Za-z0-9_-]/g, '_')}.tsx`);
fs.writeFileSync(file, code, 'utf8');
return file;
}
@@ -1417,20 +1595,26 @@ async function ensureAppNotAvailableToRole(sdk, appId, roleId) {
// sdk-teardown.js, verify verify-spec.js, and the roleGrant apply path) — a name-only match could
// touch a same-named role in a DIFFERENT business unit, which for a grant is privilege escalation.
// `q` is a queryRecords fn (the teardown `sdk` or the verify `read`); `cache` memoizes the root-BU
-// lookup for the run.
+// lookup for the run — as the lookup IN FLIGHT, not its answer: verify resolves several personas' and
+// grants' roles at once, and a cache that only held the answer (or a placeholder set before the read
+// settled) handed every concurrent caller but the first an unresolved BU, which they all reported as
+// "role not found".
async function resolveRoleBusinessUnit(q, businessUnitId, cache = {}) {
if (businessUnitId && FORM_GUID_RE.test(businessUnitId)) return businessUnitId;
- if (Object.prototype.hasOwnProperty.call(cache, 'rootBu')) return cache.rootBu;
- cache.rootBu = null;
- try {
- if (typeof q === 'function') {
- // Root BU has no parent. Mirrors the vendored SDK's own resolveRootBusinessUnit query.
- const rows = await q('businessunit', { select: ['businessunitid'], filter: '_parentbusinessunitid_value eq null', top: 1 });
- const id = rows && rows[0] && rows[0].businessunitid;
- if (id && FORM_GUID_RE.test(String(id))) cache.rootBu = String(id);
- }
- } catch { /* best-effort: fall back to a name-only match */ }
- return cache.rootBu;
+ if (!cache.rootBuLookup) {
+ cache.rootBuLookup = (async () => {
+ try {
+ if (typeof q === 'function') {
+ // Root BU has no parent. Mirrors the vendored SDK's own resolveRootBusinessUnit query.
+ const rows = await q('businessunit', { select: ['businessunitid'], filter: '_parentbusinessunitid_value eq null', top: 1 });
+ const id = rows && rows[0] && rows[0].businessunitid;
+ if (id && FORM_GUID_RE.test(String(id))) return String(id);
+ }
+ } catch { /* best-effort: fall back to a name-only match */ }
+ return null;
+ })();
+ }
+ return cache.rootBuLookup;
}
// The `_businessunitid_value eq <guid>` OData clause (Edm.Guid is UNQUOTED) that scopes a role query to a
@@ -1561,6 +1745,43 @@ async function annotateLivePlan(plan, { spec, provision, warn } = {}) {
// `unknown` below.
const relReader = { dataverse: provision && provision.dataverse };
+ // ADO 6691114: a view the build would CREATE writes its filter labels as option values, so say now when
+ // one cannot be resolved — the apply would halt on it. A dry run writes nothing, so it is asked exactly what the
+ // build's pre-flight is asked (lib/view-filter-labels.js `checkViewFilterLabelsBeforeBuild`): only a DEFINITE
+ // answer is reported, and a label that depends on something the build is about to create (a status reason it
+ // inserts, a table it makes) is not. It only HALTS for a view that is `create`: an existing view's filters are
+ // never reapplied, so for one the apply only says (see below). One reader, one read per table. The reader writes
+ // nothing, which is why it is not `fetchEntityMetadata`.
+ const labelReaders = viewLabelReaders(spec, provision);
+ // `wouldHalt` marks the answer as DEFINITE — the environment was asked and the label matches no option — so the
+ // dry run's summary does not count it among the items it "could not read". The mark stays `? unknown`: the
+ // view's state is still not `create`, since the apply would stop before writing it.
+ //
+ // A label the build would bind to the spec's own number instead (a maker renamed the option) leaves the view
+ // `create`, and the build WARNS about it in the views phase. A dry run has no such phase, so it says the same
+ // here, once however many views name the label.
+ //
+ // An EXISTING view is judged too, for what the apply will SAY about it: the views phase resolves every label the
+ // spec filters on, so it gives the same warning whether or not the view is already there, and for a label that
+ // names no option it says the view's filters are left as they are and verify will report it. The view stays
+ // `reuse` — the apply does not stop on it — so only the words differ from a view it would create.
+ const saidViewLabels = new Set();
+ const sayOnce = (message) => {
+ if (saidViewLabels.has(message)) return;
+ saidViewLabels.add(message);
+ if (typeof warn === 'function') warn(message);
+ };
+ const judgeViewLabels = async (item, key) => {
+ if (key.kind !== 'view' || (item.state !== 'create' && item.state !== 'reuse') || !key.declared || !hasLabelUses(spec, key.declared)) return;
+ const { problems, notes } = await checkViewFilterLabelsBeforeBuild(spec, [key.declared], labelReaders);
+ if (item.state === 'create') {
+ if (problems.length) { item.state = 'unknown'; item.stateWhy = problems.map(describeProblem).join(' '); item.wouldHalt = true; }
+ } else {
+ for (const p of problems) sayOnce(existingViewLabelNote(p));
+ }
+ for (const note of notes) sayOnce(note);
+ };
+
const tableState = async (logical) => {
if (!tableCache.has(logical)) {
try {
@@ -1677,7 +1898,7 @@ async function annotateLivePlan(plan, { spec, provision, warn } = {}) {
// A form/view/chart on a table that does not exist yet cannot exist either, and the filter
// would 400 on the metadata cache — so answer from the table, as the build's own lookup does.
const t = await tableState(String(k.entity).toLowerCase());
- if (t.found === false) { item.state = 'create'; continue; }
+ if (t.found === false) { item.state = 'create'; await judgeViewLabels(item, k); continue; }
// …and if the TABLE probe was inconclusive, nothing about its artifacts is knowable either.
// Without this the plan contradicts itself in adjacent lines — `? unknown` for the table and
// a confident `+ create` for every view and form on it — and the apply never gets that far:
@@ -1688,6 +1909,7 @@ async function annotateLivePlan(plan, { spec, provision, warn } = {}) {
if (t.found === null) { item.state = 'unknown'; item.stateWhy = t.why; continue; }
const present = await artifactPresent(k.kind, { name: k.name, entityLogicalName: String(k.entity).toLowerCase(), formType: k.formType, formId: k.formId, uniqueName: k.uniqueName });
item.state = present === null ? 'unknown' : (present ? 'reuse' : 'create');
+ await judgeViewLabels(item, k);
}
} catch (err) {
item.state = 'unknown';
@@ -1777,8 +1999,24 @@ function partialEnrichment(error) {
// `keepGoing` is for the halt path (settleOwedPublishes): there a target whose own publish THROWS is
// reported and the others are still published, because nothing else will publish them. The publish
// phase keeps the old behaviour — a thrown publish halts it — so a build reports that as it always did.
+//
+// A target is `[type, id]` plus an optional third element that names what the publish is FOR: the app's own
+// label, or — for a table — the names of what its one publish ships. The publish phase fills it with the saved
+// views and forms whose publishes were deferred onto the table (`publishReconciled`), its enriched default views,
+// and the views, forms and charts this run created there and a chart whose description it wrote (`noteSaved`); the
+// owed record a halted build hands to settleOwedPublishes carries only what was deferred. One artifact stands for
+// its whole table in the envelope, so a
+// bare `form <guid>` would name the table's untouched Main form in a "publish … FAILED" or "could not be
+// CONFIRMED" line, and say nothing about the view that is actually not live.
+//
+// Returns `{ appPublished, failed }`. `appPublished`: whether the app's own publish went through (a failed one, or no
+// app target, is false). The ai-features re-confirmation reads it — an override saved in the app's unpublished layer is
+// in force once the app is published, and the publish phase is what does that. `failed`: `{ target, error }` for each
+// TABLE target whose last publish the SDK refused by value (`publish.kind === 'failed'`, after the retry below), so its
+// saved changes are not live. This function only reports one (a warning); publishReconciledTables, which must not let
+// the app be published ahead of such a table, halts on it.
async function publishTargets(provision, runner, concurrency, entityTargets, appTarget, warn, { keepGoing = false } = {}) {
- const labelOf = ([type, id]) => (type === 'app' && appTarget ? appTarget[2] : `${type} ${id}`);
+ const labelOf = targetLabel;
const publishOne = async ([type, id], label) => {
if (!keepGoing) return reportPartialPush(await provision.publishArtifact(type, id), label, warn);
try {
@@ -1788,7 +2026,13 @@ async function publishTargets(provision, runner, concurrency, entityTargets, app
return undefined;
}
};
+ // A publish that was not refused. `unverifiable` still means PublishXml answered 2xx; only the read-back that
+ // would confirm it was not possible. An outcome that says nothing about publishing proves nothing.
+ const published = (result) => !!(result && result.publish && result.publish.kind && result.publish.kind !== 'failed' && result.publish.kind !== 'notRequested');
+ const refused = (result) => !!(result && result.publish && result.publish.kind === 'failed');
+ const failed = [];
const all = appTarget ? [...entityTargets, appTarget] : entityTargets;
+ const isApp = (target) => !!appTarget && target[0] === 'app' && target[1] === appTarget[1];
if (all.length > 1 && typeof provision.publishArtifacts === 'function') {
let results = null;
try {
@@ -1797,34 +2041,61 @@ async function publishTargets(provision, runner, concurrency, entityTargets, app
results = null;
}
if (Array.isArray(results) && results.length === all.length) {
- const failed = [];
+ const retry = [];
+ let appResult;
results.forEach((outcome, i) => {
- if (outcome && outcome.publish && outcome.publish.kind === 'failed') failed.push(all[i]);
- else reportPartialPush(outcome, labelOf(all[i]), warn);
+ if (refused(outcome)) retry.push(all[i]);
+ else {
+ reportPartialPush(outcome, labelOf(all[i]), warn);
+ if (isApp(all[i])) appResult = outcome;
+ }
});
- for (const target of failed) await publishOne(target, labelOf(target));
- return;
+ for (const target of retry) {
+ const retried = await publishOne(target, labelOf(target));
+ if (isApp(target)) appResult = retried;
+ else if (refused(retried)) failed.push({ target, error: retried.publish.error });
+ }
+ return { appPublished: published(appResult), failed };
}
}
- await runner.mapLimit(entityTargets, concurrency, (async (target) => publishOne(target, `${target[0]} ${target[1]}`)));
- if (appTarget) await publishOne(['app', appTarget[1]], appTarget[2]);
+ const outcomes = await runner.mapLimit(entityTargets, concurrency, (async (target) => publishOne(target, labelOf(target))));
+ entityTargets.forEach((target, i) => {
+ const outcome = (outcomes || [])[i];
+ if (refused(outcome)) failed.push({ target, error: outcome.publish.error });
+ });
+ const appResult = appTarget ? await publishOne(['app', appTarget[1]], appTarget[2]) : undefined;
+ return { appPublished: published(appResult), failed };
+}
+
+// What a publish target is FOR, in the words a warning or a halt prints: the names the target carries (a table's
+// deferred and saved artifacts, the app's own label), else `type id`.
+function targetLabel([type, id, label]) {
+ return (Array.isArray(label) ? label.join(', ') : label) || `${type} ${id}`;
}
-// The publishes a build still OWED when it stopped: the tables whose default views its deferred
-// enrichment (4b) saved and that no completed publish phase (8) covered. `runSdkBuild` attaches them
+// The publishes a build still OWED when it stopped: the tables whose saved views and forms — the default
+// views its deferred enrichment (4b) saved, and the existing views and forms its reconcile paths pushed —
+// no completed publish phase (8) covered. `runSdkBuild` attaches them
// to the halt (`owedPublishes`) instead of publishing them there, because only its caller knows
// whether the halt is final: the CLI retries a transient one (a 429, a customization lock) at once,
// the retry saves those views again and owes their publish again, and a publish sent into that
// throttling would only fail the same way. The CLI keeps what each failed attempt owed, because a later
-// attempt can halt before the enrichment an earlier one did, until a publish phase pays it (`owedPaid`).
+// attempt can halt before the step an earlier one owed from, until a publish phase pays it (`owedPaid`).
//
-// On a FINAL halt the caller publishes them with this (`owed`: `[type, id]` pairs). Before the publish
-// was batched, the enrichment published each table as it went, so a build that stopped in a later phase
-// left those tables live (live-verified, before and after the batching). Without this they would wait,
-// saved but unpublished, for the full re-run that recovers from the halt — which saves them again and
-// owes their publish again — and nothing makes an operator start one.
+// On a FINAL halt the caller publishes them with this (`owed`: `[type, id, names?]` targets, see
+// publishTargets). Before the publish was batched, the enrichment and every reconcile published each table
+// as it went, so a build that stopped in a later phase left those tables live (live-verified, before and
+// after the batching). Without this they would wait, saved but unpublished, for the full re-run that
+// recovers from the halt — which saves them again and owes their publish again — and nothing makes an
+// operator start one.
// Best-effort and per target: the halt is what the operator must see, so a failure is a warning, never a
// throw, and a target that cannot be published does not keep the others back.
+//
+// This runs only for a halt the build THROWS. A process killed outright (Ctrl-C, a crash, a closed
+// terminal) settles nothing: what a reconcile had saved and deferred stays saved but unpublished until the
+// next build, which publishes it (a clean workspace copy is still published, see publishReconciled). No marker
+// outlives the process to say it is owed, and the CLI installs no signal handler that could write one. The
+// default-view enrichment (4b), whose publish was deferred the same way first, has the same exposure.
async function settleOwedPublishes(provision, owed, warn) {
const targets = Array.isArray(owed) ? owed.filter((target) => Array.isArray(target) && target[0] && target[1]) : [];
if (!targets.length || !provision) return;
@@ -1832,16 +2103,33 @@ async function settleOwedPublishes(provision, owed, warn) {
try {
await publishTargets(provision, makeRunner({ emit: () => undefined, total: 0 }), 1, targets, null, say, { keepGoing: true });
} catch (e) {
- say(`publishing the default views it had already enriched FAILED: ${(e && e.message) || e} — the change is SAVED but the runtime still serves the previously published copy; the build is idempotent, so re-run it once the cause is cleared`);
+ say(`publishing the views and forms it had already saved FAILED: ${(e && e.message) || e} — the change is SAVED but the runtime still serves the previously published copy; the build is idempotent, so re-run it once the cause is cleared`);
}
}
+// Fold the targets one halted attempt still owes (`err.owedPublishes`) into `byTarget`, keyed by `type:id`, for the
+// CLI to settle once no retry follows. A later attempt can stop before a step an earlier one owed from, so the
+// names an attempt recorded for a target are UNIONED with what the earlier ones recorded — "last attempt wins"
+// would drop the names of whatever only the earlier attempt reached, and a failed settle would name too little.
+function collectOwedPublishes(byTarget, owed) {
+ for (const target of Array.isArray(owed) ? owed : []) {
+ if (!Array.isArray(target)) continue;
+ const key = `${target[0]}:${target[1]}`;
+ const namesOf = (t) => (Array.isArray(t && t[2]) ? t[2] : []);
+ const names = [...new Set([...namesOf(byTarget.get(key)), ...namesOf(target)])];
+ byTarget.set(key, names.length ? [target[0], target[1], names] : target);
+ }
+ return byTarget;
+}
+
// Every caller enters here; the phases run in runSdkBuildPhases. This wrapper only carries what the
-// deferred default-view enrichment still owes out of a halt: `owedPublishes`, and `owedPaid` when this
-// run's publish phase completed — which pays what an earlier attempt of the same build owed too, since
-// every attempt enriches the same tables (see settleOwedPublishes).
+// deferred publishes (default-view enrichment, reconciled views and forms) still owe out of a halt:
+// `owedPublishes`, and `owedPaid` when this run's publish phase completed — which pays what an earlier
+// attempt of the same build owed too, since every attempt saves the same tables (see settleOwedPublishes).
async function runSdkBuild(spec, opts = {}) {
- // tables: entity logical -> [type, id] of a saved default view that owes its publish.
+ // tables: entity logical -> [type, id, names] of a saved view or form that owes its publish, and the names of
+ // what is deferred onto that table: its reconciled views and forms, and its enriched default views
+ // (oweTablePublish).
const owed = { tables: new Map(), paid: false };
try {
return await runSdkBuildPhases(spec, opts, owed);
@@ -1890,12 +2178,12 @@ async function runSdkBuildPhases(spec, opts, owed) {
dryRun: true,
livePlan: canProbe,
plan: plan.map((p) => (p.state ? `${p.label} [${p.state}]` : p.label)),
- planItems: plan.map((p) => ({ phase: p.phase, label: p.label, ...(p.state ? { state: p.state } : {}), ...(p.stateWhy ? { stateWhy: p.stateWhy } : {}) })),
+ planItems: plan.map((p) => ({ phase: p.phase, label: p.label, ...(p.state ? { state: p.state } : {}), ...(p.stateWhy ? { stateWhy: p.stateWhy } : {}), ...(p.wouldHalt ? { wouldHalt: true } : {}) })),
};
}
const createdFormsThisRun = new Set();
- const result = { ok: true, created: { entities: {}, relationships: {}, records: {}, webResources: {}, views: {}, charts: {}, forms: {}, formIds: {}, businessRules: {}, businessProcessFlows: {}, bpfBackingTables: {}, commands: {}, dashboards: {}, pages: {}, pageDeployedShas: {}, ai: { appFeatures: null, summaries: {} }, roles: {}, roleGrants: {}, bpfRoleGrants: {}, app: null }, skipped: { businessRules: [], aiSummaries: [], layout: [], unauthorizedRemovals: [] } };
+ const result = { ok: true, created: { entities: {}, relationships: {}, records: {}, webResources: {}, views: {}, charts: {}, forms: {}, formIds: {}, businessRules: {}, businessProcessFlows: {}, bpfBackingTables: {}, commands: {}, dashboards: {}, pages: {}, pageDeployedShas: {}, pageSourceShas: {}, ai: { appFeatures: null, summaries: {} }, roles: {}, roleGrants: {}, bpfRoleGrants: {}, app: null }, skipped: { businessRules: [], aiSummaries: [], layout: [], unauthorizedRemovals: [] } };
// #changed-only (pages-only fast apply): seed the LIVE app id (discovered by unique name upstream) so the
// pages phase's `pages-requires-app` guard passes WITHOUT running the app-shell phase in this invocation.
// The full-build path never sets opts.changedOnly, so result.created.app stays null and app-shell
@@ -1904,15 +2192,139 @@ async function runSdkBuildPhases(spec, opts, owed) {
const runner = makeRunner({ emit, total: plan.length });
const sol = spec.solution;
+ // ADO 6691114: a view-filter label the environment already shows to be wrong stops the build here, before it
+ // writes anything — in any apply that writes the solution or the data model, whether or not it also builds the
+ // views, so the staged flow's data run fails first too — unless the spec carries a localized label, whose
+ // creation no label-bearing read may precede (preflightViewLabels). The views phase checks again once the data
+ // model exists (the final answer, with the values). A note both of them would make is made once.
+ const warnedViewLabels = new Set();
+ const sayViewLabel = (message) => {
+ if (warnedViewLabels.has(message)) return;
+ warnedViewLabels.add(message);
+ if (typeof opts.warn === 'function') opts.warn(message);
+ };
+ let preflightResolved;
+ if (has('solution') || has('data-model')) preflightResolved = await preflightViewLabels(spec, provision, sayViewLabel);
+
+ // Solution membership of the components this run REUSES (solution-membership.js): read once, at first use,
+ // and a component the solution is PROVEN to hold is not added again. A component this run creates is added
+ // directly — a component made a moment ago cannot already be a member — with one exception: the page
+ // manifest is persisted after every page create and once more at the end (persistPageManifest), so it always
+ // goes through `ensureSolutionComponent`, and a build that deploys pages makes the read even when it is the
+ // first. That costs a read and never an add: a manifest the solution lacks is still added.
+ //
+ // A reused view, chart or form is also proven by its TABLE: one the build created is held by the solution with
+ // all its subcomponents, which the platform does not list one by one, so these three have no row of their own to
+ // find. The membership asks for the table's MetadataId — the `objectid` of the table's row — only when it needs
+ // it, once per table, through the raw client the build already uses for table metadata (`tableRefs`). A client
+ // without `get`, a table that does not resolve, any failure at all: no proof, and the component is added.
+ const resolveTableId = async (logical) => (await tableRefs(provision.dataverse, [logical])).get(String(logical).toLowerCase()).metadataId;
+ const solutionMembers = createSolutionMembership({ read: provision, solutionUniqueName: sol && sol.uniqueName, componentTypes: Object.values(COMPONENT_TYPE), resolveTableId });
+ const ensureInSolution = (componentId, componentType, table) => ensureSolutionComponent(provision, solutionMembers, { componentId, componentType, solutionUniqueName: sol.uniqueName }, { table });
+
+ // With --publish, phase 8 publishes the table of every view and form the reconcile paths touch (an entity
+ // PublishXml ships every pending customization on that table), so a reconcile's own publish would only
+ // repeat it, one ~2.5 s PublishXml per artifact. It is deferred to phase 8 and recorded as owed — the same
+ // record the default-view enrichment (4b) keeps — so a build that halts first still gets it published by its
+ // caller (settleOwedPublishes); and the owed table is itself a phase 8 target, so deferring cannot leave an
+ // entity out of it.
+ //
+ // One artifact publishes its whole table, so the record keeps the first artifact deferred onto the table as the
+ // target and collects the NAMES of every one (`view Open Tickets`, `form Ticket events`, `default views of
+ // new_ticket`, …): when that publish fails — or cannot be confirmed — the line says which saved changes are not
+ // live, as the per-artifact publish it replaces did, instead of naming whichever form happened to stand for the
+ // table (publishTargets). The reconcile paths and the default-view enrichment (4b) both owe through this, so the
+ // record is the same whichever of them reaches the table first.
+ //
+ // Without --publish nothing runs phase 8, so the reconcile publishes its own artifact so the change takes
+ // effect, as it always did. That includes a reconcile whose push was skipped as unchanged: a clean workspace
+ // copy is the UNPUBLISHED layer, so it cannot show that an earlier run which pushed and then stopped ever
+ // published (hasUnsyncedEdits).
+ const publishInPhase8 = has('publish') && publish;
+ const oweTablePublish = (logical, type, id, name) => {
+ const target = owed.tables.get(logical);
+ if (!target) owed.tables.set(logical, [type, id, [name]]);
+ else if (!(target[2] || []).includes(name)) target[2] = [...(target[2] || []), name];
+ };
+ // The tables a reconcile deferred onto phase 8: publishReconciledTables pays them before the app is published.
+ const reconciledTables = new Set();
+ const publishReconciled = async (type, id, entityLogical, label) => {
+ const logical = String(entityLogical || '').toLowerCase();
+ if (publishInPhase8 && logical) {
+ oweTablePublish(logical, type, id, label);
+ reconciledTables.add(logical);
+ return;
+ }
+ reportPartialPush(await provision.publishArtifact(type, id), label, opts.warn);
+ };
+
+ // ...but not past the app's own publish. Live-measured: when a table's EXISTING form is saved, a PublishXml that
+ // names only the app (`<appmodules>`), sent before the table's own publish, leaves the form's LABEL changes
+ // unpublished for good. The cell and section labels keep their published text through every later publish of
+ // the table, alone or in one envelope with the app; the structure saved with them (a cell's showlabel) does go
+ // live. The unpublished layer still holds the new text, so a re-run finds nothing to push and cannot repair it.
+ // Publishing the table first, or in the same envelope as the app, leaves the labels live. So does a web resource's
+ // or another table's publish in between.
+ //
+ // 2.13.0 published each reconciled view and form right after its push, so its app publishes always came after.
+ // Deferring that publish to phase 8 put the app's own publishes in between: the sitemap finalize on every rebuild of
+ // an existing app, the create of a new app (its push publishes it) and the hidden-table pin after that create. A
+ // form relabel the reconcile makes (a lookup cell that showed its column's logical name, a section the spec
+ // renames) was then saved, reported, and never shown. So the app step publishes these tables, in one envelope,
+ // before it writes the app; a view description the reconcile writes is a label too and goes out with them. Every
+ // reconcile has run by then, and nothing before that step publishes the app: the command and dashboard steps publish
+ // nothing, and the app icon publishes only its web resource. Phase 8 still publishes these tables with everything
+ // else. The default views the enrichment (4b) saved stay owed to phase 8 alone: it re-saves their columns on every
+ // build, never a label, so paying for them here would only add a publish to every first build.
+ const publishReconciledTables = async () => {
+ const targets = [...reconciledTables].map((logical) => owed.tables.get(logical)).filter(Boolean);
+ reconciledTables.clear();
+ if (!targets.length) return;
+ const { failed } = await publishTargets(provision, runner, concurrency, targets, null, opts.warn);
+ if (!failed.length) return;
+ // A table whose publish the SDK refused (by value: it never throws for one) still holds its saved labels
+ // unpublished, and the app's publish below would strand them for good — so the build stops before it writes the
+ // app. Nothing is lost: the halt carries every table this run owes (runSdkBuild), the CLI re-runs a transient
+ // refusal at once, and once no retry follows it publishes them without the app (settleOwedPublishes).
+ const names = failed.map(({ target }) => targetLabel(target)).join('; ');
+ const detail = failed.map(({ error }) => (error && error.message) || 'refused').join('; ');
+ const first = failed[0].error;
+ const halt = new BuildHalt(`publish ${names} FAILED before the app was written: ${detail} — the build stopped there, because the app's publish would leave the labels saved on these tables unpublished for good. The changes are saved; re-run the build once the cause is cleared.`, { phase: 'app-shell', code: 'reconciled-publish-failed', recoverable: true, cause: first });
+ // The runner wraps this halt once more (makeRunner), and the CLI's retry check (isTransientHalt, build-model-app.js)
+ // reads a status only on the halt it is given and on that halt's cause. So the refusal's HTTP status is carried here,
+ // where it can see it — a 429 or a 503 is re-run as it was before this publish moved ahead of the app — and so is an
+ // explicit "never retry".
+ const status = first && (first.statusCode || first.status);
+ if (status) halt.statusCode = status;
+ if (first && first.transient === false) halt.transient = false;
+ throw halt;
+ };
+
+ // The names of what this run CREATED on each table (`view Open Tickets`, `form Ticket`, `chart By Area`), and of a
+ // chart whose description it wrote — labels only. A created artifact is as unpublished as a reconciled one, but a
+ // create defers no publish into `owed.tables` (only the reconcile, event-wiring and quick-view paths and the
+ // default-view enrichment do), so on a first build a table's record held no more than what those left (its default
+ // views, a quick view's placement, a form's event wiring) and a failed publish read as if only those were not live.
+ // These names deliberately stay OUT of `owed.tables`: that record is what a halted build publishes, and a created
+ // artifact in it would make a halt publish tables it has never published. Phase 8 reads them (forTable) to
+ // complete the label of the table's one publish; no request, read or write depends on them.
+ const savedOnTable = new Map();
+ const noteSaved = (entityLogical, name) => {
+ const logical = String(entityLogical || '').toLowerCase();
+ if (!logical) return;
+ if (!savedOnTable.has(logical)) savedOnTable.set(logical, new Set());
+ savedOnTable.get(logical).add(name);
+ };
+
// 1. Solution (idempotent; header-less provisioning client).
if (has('solution')) await provisionSolution({ sdk, provision, runner, solution: sol });
// 2. Data model — idempotent. Discover existing tables/columns/relationships via the SDK
// (find*/fetch*), then create only what's missing. Captures entitySetName for every
// entity (fresh -> createTable result, existing -> findTables hit).
- let dataModel = { entities: {}, globalChoiceIds: {}, statusReasonValues: {}, columns: {}, relationships: [] };
+ let dataModel = { entities: {}, globalChoiceIds: {}, statusReasonValues: {}, columns: {}, relationships: [], lookupLabels: {} };
if (has('data-model')) {
- dataModel = await provisionDataModel({ sdk, provision, runner, spec, apply, languageCode: opts.languageCode, warn: opts.warn, provisionedLanguages: opts.provisionedLanguages, preResolvedLanguageCode: opts.preResolvedLanguageCode });
+ dataModel = await provisionDataModel({ sdk, provision, runner, spec, apply, languageCode: opts.languageCode, warn: opts.warn, provisionedLanguages: opts.provisionedLanguages, preResolvedLanguageCode: opts.preResolvedLanguageCode, reconcileLookupLabels: true });
Object.assign(result.created.entities, dataModel.entities);
}
@@ -2016,13 +2428,234 @@ async function runSdkBuildPhases(spec, opts, owed) {
// A sub-grid used to be spliced as a single cell into the first field section's rows, which rendered
// it half-width inside a 2-column section; giving it a dedicated section makes the related list span
// the form. `sg.label` is already resolved to the child's display name by the forms phase.
- const addSubgrids = async (formId, subs) => {
- for (const sg of subs || []) {
+ //
+ // A grid that declares no placement (`tab` / `column` / `after` / `before`) goes where it always has: the end
+ // of the first tab's first form-column, and is never moved. One that does is put where it says, and a rebuild
+ // CONVERGES it there — see placeGridSection below. `ctx` carries what the topology pass
+ // resolved on an existing explicit layout ({ topology, sectionTargets }); a form this run created, or an auto
+ // layout, has none and resolves the layout's names on the form itself.
+ //
+ // The order the grids are placed in matters. Those that name no anchor (no key, or a tab only) are appended to
+ // the end of their column first, in declared order, as they always were. The anchored ones follow, each put
+ // DIRECTLY beside the nearest token toward its anchor that is on the form already: `after` grids in declared
+ // order, so a grid sharing an anchor with an earlier one lands after it; `before` grids in REVERSE declared
+ // order, so the one declared last sits against the anchor and the earlier ones in front of it.
+ const addSubgrids = async (formId, def, ctx) => {
+ const subs = def.__subgrids || [];
+ // The anchored grids of each layout form-column, in declared order: what a column's sequence is built from.
+ const groups = new Map();
+ for (const sg of subs) {
+ const resolved = sg.placement && sg.placement.resolved;
+ if (!resolved || !resolved.anchor) continue;
+ const key = `${resolved.tabIndex}:${resolved.columnIndex}`;
+ if (!groups.has(key)) groups.set(key, []);
+ groups.get(key).push({ key: String(sg.relationshipName).toLowerCase(), [resolved.anchor.side]: resolved.anchor.name });
+ }
+ const sideOf = (sg) => (sg.placement && sg.placement.resolved.anchor ? sg.placement.resolved.anchor.side : null);
+ for (const sg of subs) {
+ if (sideOf(sg)) continue;
+ if (sg.placement) {
+ await placeGridSection(formId, def, sg, groups, ctx);
+ continue;
+ }
if (hasSubgrid(await provision.getArtifact('form', formId) || {}, sg.relationshipName)) continue;
const sectionsPtr = firstColumnSectionsPointer(await provision.getArtifact('form', formId) || {});
if (!sectionsPtr) continue;
await provision.addElement('form', formId, sectionsPtr, subgridSectionIntent({ subgridClassId: SUBGRID_CLASS_ID, targetEntity: sg.targetEntity, relationshipName: sg.relationshipName, viewId: sg.viewId, label: sg.label }));
}
+ for (const sg of subs.filter((s) => sideOf(s) === 'after')) await placeGridSection(formId, def, sg, groups, ctx);
+ for (const sg of subs.filter((s) => sideOf(s) === 'before').reverse()) await placeGridSection(formId, def, sg, groups, ctx);
+ };
+
+ // --- sub-grid placement (lib/form-subgrid-placement.js) ------------------------------------------------
+
+ const columnAtPointer = (form, pointer) => {
+ const t = String(pointer || '').split('/').filter(Boolean);
+ if (t.length !== 4) return null;
+ const tab = (form.tabs || [])[Number(t[1])];
+ return (tab && (tab.columns || [])[Number(t[3])]) || null;
+ };
+ const columnPointerOfSection = (pointer) => String(pointer).replace(/\/sections\/\d+$/, '');
+ // `/tabs/<ti>/columns/<ci>` → the two indices, for naming the tab and form-column in a report.
+ const columnIndicesOf = (columnPointer) => {
+ const t = String(columnPointer).split('/').filter(Boolean);
+ return { ti: Number(t[1]), ci: Number(t[3]) };
+ };
+ const tabNameAt = (form, ti) => ((form.tabs || [])[ti] || {}).name || `#${ti + 1}`;
+
+ // The section a form holds a relationship's sub-grid control in, with its pointers (lib/form-subgrid-placement.js
+ // finds it; `engine` says the build owns it). A grid a maker put in a section of their own is found too, but it
+ // is not the build's to move.
+ const findGridSection = (form, relationshipName) => {
+ const hit = findSubgridSection(form.tabs, relationshipName);
+ if (!hit) return null;
+ const columnPointer = `/tabs/${hit.ti}/columns/${hit.ci}`;
+ return Object.assign(hit, { columnPointer, listPointer: `${columnPointer}/sections`, pointer: `${columnPointer}/sections/${hit.si}` });
+ };
+
+ // The recorded section targets address sections by index, so adding a section to a column pushes the ones after
+ // it up and taking one out pulls them down. Corrected here, so the prune and the vacated-section sweep that
+ // run after the sub-grids still resolve every section the topology pass gave them.
+ const shiftSectionTargets = (targets, listPointer, index, delta) => {
+ for (const t of Object.values(targets || {})) {
+ const m = t && /^(.*\/sections)\/(\d+)$/.exec(String(t.pointer || ''));
+ if (!m || m[1] !== listPointer) continue;
+ const at = Number(m[2]);
+ if (delta > 0 ? at >= index : at > index) t.pointer = `${listPointer}/${at + delta}`;
+ }
+ };
+
+ // Where the layout's tab `wantTabIndex` is on the live form: the index the topology pass matched it to on an
+ // explicit layout, else the tab of that name (a form this run created has its tabs where the compiler put them;
+ // an auto layout's only tab is `tab_general`). -1 when it cannot be found.
+ const deployedTabIndex = (form, def, wantTabIndex, ctx) => {
+ if (ctx && ctx.topology) {
+ const matched = ctx.topology.tabIndexOf[wantTabIndex];
+ return Number.isInteger(matched) && (form.tabs || [])[matched] ? matched : -1;
+ }
+ const name = ((def.__subgridLayout || [])[wantTabIndex] || {}).name;
+ return (form.tabs || []).findIndex((t) => String((t && t.name) || '').toLowerCase() === name);
+ };
+
+ // The live section a layout section name stands for: the section the topology pass matched it to — which can
+ // carry another name, matched by label or position — else the section of that name, never an engine host that
+ // shares it. `{ pointer, section }`, or null.
+ const deployedSectionByName = (form, name, ctx) => {
+ const targets = ctx && ctx.sectionTargets;
+ const key = targets ? Object.keys(targets).find((k) => k.toLowerCase() === name) : undefined;
+ if (key !== undefined) {
+ const pointer = resolveSectionPointer(form, targets[key]);
+ const section = pointer && sectionAt(form, pointer);
+ if (section) return { pointer, section };
+ }
+ const loc = findSectionLocation(form, name, (s) => !isEngineHostSection(s));
+ return loc ? { pointer: loc.pointer, section: loc.section } : null;
+ };
+
+ // The form-column a placed grid belongs in on the live form — where its anchor is, or the tab (and column) it
+ // names — or null when the layout name it is placed by cannot be found there.
+ const gridDestination = (form, def, sg, ctx) => {
+ const resolved = sg.placement.resolved;
+ if (resolved.anchor) {
+ const at = deployedSectionByName(form, resolved.anchor.name, ctx);
+ return at ? { columnPointer: columnPointerOfSection(at.pointer), anchored: true } : null;
+ }
+ const ti = deployedTabIndex(form, def, resolved.tabIndex, ctx);
+ if (ti < 0) return null;
+ const ci = resolved.createColumn;
+ if (!((form.tabs[ti].columns || [])[ci])) return null;
+ return { columnPointer: `/tabs/${ti}/columns/${ci}`, tabIndex: ti, anyColumn: resolved.columnIndex === undefined, anchored: false };
+ };
+
+ // The live index, in the column at `columnPointer`, of one token of a column's sequence — a section of the
+ // layout or an engine grid section — or undefined when it is not in that column.
+ const tokenIndexIn = (form, columnPointer, token, ctx) => {
+ if (token.grid !== undefined) {
+ const hit = findGridSection(form, token.grid);
+ return hit && hit.engine && hit.columnPointer === columnPointer ? hit.si : undefined;
+ }
+ const at = deployedSectionByName(form, token.section, ctx);
+ if (!at || columnPointerOfSection(at.pointer) !== columnPointer) return undefined;
+ return Number(at.pointer.slice(at.pointer.lastIndexOf('/') + 1));
+ };
+
+ // The column's sequence of layout sections and anchored grids (columnSequence) for the layout column a placed
+ // grid is anchored in.
+ const gridSequence = (def, resolved, groups) => {
+ const column = ((def.__subgridLayout || [])[resolved.tabIndex] || { columns: [] }).columns[resolved.columnIndex] || { sections: [] };
+ return columnSequence(column.sections, groups.get(`${resolved.tabIndex}:${resolved.columnIndex}`) || []);
+ };
+
+ // Where an ANCHORED grid goes in its column right now: DIRECTLY beside the nearest token of its sequence toward
+ // its anchor that is already in the column (neighbourOf) — right after it for an `after` grid, right before it
+ // for a `before` grid. `gap` is the insertion point in the column as it stands, i.e. the index the grid would
+ // be inserted before. That is where a fresh build puts the grid, so a rebuilt form and a new one agree.
+ const anchoredPosition = (form, columnPointer, seq, gridKey, ctx) => {
+ const near = neighbourOf(seq, gridKey, (token) => tokenIndexIn(form, columnPointer, token, ctx) !== undefined);
+ if (!near) return null;
+ const refIndex = tokenIndexIn(form, columnPointer, near.token, ctx);
+ return { side: near.side, token: near.token, refIndex, gap: near.side === 'after' ? refIndex + 1 : refIndex };
+ };
+
+ // Put ONE placed grid where the spec says: add its section when it has none, and when the build's own section
+ // for it is somewhere else — the end of the first tab, where an earlier build appended it, behind the Notes
+ // section, in another form-column — MOVE that same section: its id, its control, anything a maker set on it
+ // travel with it. An anchored grid ends DIRECTLY beside its anchor (anchoredPosition); a grid that names only a
+ // tab (and column) is put at the end of that column and, once in it, left where it is.
+ //
+ // Only the grid moves. The fewest-moves planner the topology pass orders sections with (planOrderMoves) is NOT
+ // used here because it moves whichever section is cheapest — and where the Notes section sits between the
+ // anchor and a grid an older build appended after it, that is the authored section or the timeline, leaving the
+ // Notes section in the middle of the form. What a placement never does: touch a grid in a section the build did
+ // not create, or move one the spec does not place.
+ const placeGridSection = async (formId, def, sg, groups, ctx) => {
+ const form = await provision.getArtifact('form', formId) || {};
+ const existing = findGridSection(form, sg.relationshipName);
+ const dest = gridDestination(form, def, sg, ctx);
+ const warn = (message) => { if (typeof opts.warn === 'function') opts.warn(message); };
+ const shown = `the sub-grid for '${sg.targetEntity}'`;
+ if (!dest) {
+ // The tab or section the layout names is not on this form — the spec gate cannot see a deployed form. The
+ // grid is still added where it always goes, so it is never lost to an unresolvable placement.
+ const r = sg.placement.resolved;
+ reportLayoutSkip(`form ${def.name}: ${shown} was not placed ${r.anchor ? `${r.anchor.side} section '${r.anchor.name}'` : `in tab '${(def.__subgridLayout[r.tabIndex] || {}).name}'`}`
+ + ' — the deployed form has no such section or tab to place it by'
+ + `${existing ? '; it stays where it is' : ', so it was added at the end of the first tab'}. Adjust the layout in the maker.`);
+ if (existing) return;
+ const sectionsPtr = firstColumnSectionsPointer(form);
+ if (sectionsPtr) await provision.addElement('form', formId, sectionsPtr, subgridSectionIntent({ subgridClassId: SUBGRID_CLASS_ID, targetEntity: sg.targetEntity, relationshipName: sg.relationshipName, viewId: sg.viewId, label: sg.label }));
+ return;
+ }
+ const listPointer = `${dest.columnPointer}/sections`;
+ const sectionCount = ((columnAtPointer(form, dest.columnPointer) || {}).sections || []).length;
+ const resolved = sg.placement.resolved;
+ const seq = dest.anchored ? gridSequence(def, resolved, groups) : null;
+ const gridKey = String(sg.relationshipName).toLowerCase();
+ const position = dest.anchored ? anchoredPosition(form, dest.columnPointer, seq, gridKey, ctx) : null;
+ // The insertion point as the column stands now: beside the neighbour for an anchored grid, the end otherwise.
+ const gap = position ? position.gap : sectionCount;
+ const to = columnIndicesOf(dest.columnPointer);
+ const where = `tab '${tabNameAt(form, to.ti)}' (form-column ${to.ci + 1})`;
+ if (existing) {
+ const name = existing.section.name || `#${existing.si + 1}`;
+ const sameColumn = existing.listPointer === listPointer;
+ // Already where the spec puts it — directly beside its neighbour, or in the tab (and form-column) it names:
+ // nothing to write, and nothing to report either. The report below is advice for a grid that is NOT in place
+ // ("move that section"); one that already is has nothing to move, and a notice that repeats on every rebuild
+ // is one a maker learns to ignore.
+ const inPlace = dest.anchored
+ ? !!position && sameColumn && existing.si === (position.side === 'after' ? position.refIndex + 1 : position.refIndex - 1)
+ : (dest.anyColumn ? existing.ti === dest.tabIndex : existing.columnPointer === dest.columnPointer);
+ if (inPlace) return;
+ if (!existing.engine) {
+ reportLayoutSkip(`form ${def.name}: ${shown} sits in section '${name}', which this build did not create, `
+ + 'so it was left there. Move that section in the maker, or delete it to let the build place a grid of its own.');
+ return;
+ }
+ // moveElement removes the section before it inserts, so within one column an insertion point below the
+ // section's own index is one lower once it has gone.
+ const index = sameColumn && existing.si < gap ? gap - 1 : gap;
+ await provision.moveElement('form', formId, existing.pointer, listPointer, { index });
+ shiftSectionTargets(ctx && ctx.sectionTargets, existing.listPointer, existing.si, -1);
+ shiftSectionTargets(ctx && ctx.sectionTargets, listPointer, index, 1);
+ const from = `from tab '${tabNameAt(form, existing.ti)}' (form-column ${existing.ci + 1}) `;
+ if (position) {
+ const next = position.token.section !== undefined ? `section '${position.token.section}'`
+ : `the sub-grid for '${((def.__subgrids || []).find((s) => String(s.relationshipName).toLowerCase() === position.token.grid) || {}).targetEntity || position.token.grid}'`;
+ warn(`form ${def.name}: moved ${shown} (section '${name}') ${sameColumn ? '' : from}to sit directly ${position.side} ${next}, in ${where}, where subgrids[] places it.`);
+ } else {
+ warn(`form ${def.name}: moved ${shown} (section '${name}') ${from}to ${where}, where subgrids[] places it.`);
+ }
+ return;
+ }
+ const intent = subgridSectionIntent({ subgridClassId: SUBGRID_CLASS_ID, targetEntity: sg.targetEntity, relationshipName: sg.relationshipName, viewId: sg.viewId, label: sg.label });
+ if (!dest.anchored) {
+ // The end of the column: appended, so no recorded section moves.
+ await provision.addElement('form', formId, listPointer, intent);
+ return;
+ }
+ await provision.addElement('form', formId, listPointer, intent, { position: { index: gap } });
+ shiftSectionTargets(ctx && ctx.sectionTargets, listPointer, gap, 1);
};
// A quick-view's semantic identity is the lookup field it renders through (one quick-view per lookup).
@@ -2147,6 +2780,12 @@ async function runSdkBuildPhases(spec, opts, owed) {
}
};
+ // ADO 6691205 — repair, on a deployed form, the label an older build gave a lookup cell: only the
+ // old default, and only when the spec sets no lookup.displayName (lib/lookup-cell-labels.js applies the rule).
+ const repairLookupCellLabelsOn = (formId, def) => repairLookupCellLabels({
+ provision, formId, entityLogical: def.entityLogicalName, spec, lookupLabels: dataModel.lookupLabels,
+ });
+
// Remove the rows a cell's departure left holding nothing: its own row, and the rows its row-span
// covered. An empty `<row/>` renders as a blank line, and one would accumulate per pruned or
// relocated field. `strandedRows` keeps a row that a row-spanning cell above still reserves (it is
@@ -2172,10 +2811,23 @@ async function runSdkBuildPhases(spec, opts, owed) {
const departed = new Set();
const narrowed = [];
const newFields = new Set();
- for (const { logical, sectionPointer, cell } of newCells) {
- appendCellPacked(planned, sectionPointer, cell);
+ for (const queued of newCells) {
+ // The section the cell was queued for, found again as it is now (see queuedSectionPointer). Were it gone the field
+ // goes where a field with no section goes, rather than being lost — or halting the build on a pointer that
+ // addresses nothing.
+ let sectionPointer = queuedSectionPointer(planned, queued);
+ if (!sectionPointer) {
+ const rowsPointer = firstFieldSectionRowsPointer(planned);
+ if (!rowsPointer) {
+ reportLayoutSkip(`form ${def.name}: '${queued.logical}' was not added — the form has no section to put it in.`);
+ continue;
+ }
+ sectionPointer = rowsPointer.slice(0, -'/rows'.length);
+ reportLayoutSkip(`form ${def.name}: '${queued.logical}' was added to the first section of the form — the section the layout names for it was no longer there.`);
+ }
+ appendCellPacked(planned, sectionPointer, queued.cell);
affected.add(sectionPointer);
- newFields.add(logical);
+ newFields.add(queued.logical);
}
const place = (logical, anchor, before = false) => {
const move = planFieldAdjacent(planned, logical, anchor, def.name, before);
@@ -2236,7 +2888,8 @@ async function runSdkBuildPhases(spec, opts, owed) {
// cannot be interrupted separately. Existing cell/control IDs and opaque state are copied.
if (affected.size === 1) {
const [pointer] = affected;
- await provision.updateElement('form', formId, pointer + '/rows', sectionAt(planned, pointer).rows);
+ const section = sectionAt(planned, pointer);
+ if (section) await provision.updateElement('form', formId, pointer + '/rows', section.rows);
} else {
await provision.updateElement('form', formId, '/tabs', planned.tabs);
}
@@ -2264,6 +2917,13 @@ async function runSdkBuildPhases(spec, opts, owed) {
if (alreadyPlaced && rowOccupancy(destination.rows)[from.rowIndex].used <= landing.gridWidth) return {};
const skip = (reason) => ({ warning: `form ${formName}: placement of '${logical}' ${before ? 'before' : 'after'} '${anchor}' `
+ `was skipped - ${reason}. Adjust the layout in the maker.` });
+ // A field is never placed into a section the engine owns — the Notes timeline's rows are spacers its cell
+ // spans, and a sub-grid host holds nothing else. The anchor can only be here because a maker put a field
+ // into the host; positioning another control beside it would put the engine's own section's layout in
+ // the spec's hands.
+ if (!alreadyPlaced && isEngineHostSection(destination)) {
+ return skip('the anchor sits in a section the build owns (the Notes timeline or a sub-grid), which no field is placed into');
+ }
const fits = (candidate) => [from.sectionPointer, to.sectionPointer].every((pointer) => {
const section = sectionAt(candidate, pointer);
return fitsGrid(section.rows || [], Number(section.columns) || 1);
@@ -2583,6 +3243,9 @@ async function runSdkBuildPhases(spec, opts, owed) {
const local = (global || !authoredWant) ? null : matchContainer((liveSections || {}).sections, wantSection, si,
{ claimed: claimedHere, skip: (s) => isEngineOwnedSection(s) || isEngineHostSection(s) || claimedByAuthoredName(authoredSectionNames)(s), nameSkip: (s) => !candidate(s) });
if (!global && !local) {
+ // The Notes host carries the control id Dynamics renders a timeline under, so it is not added to a
+ // form that already has a control by that id — a second `notescontrol` would be a duplicate.
+ if (!authoredWant && timelineInSection(wantSection) && timelineCreationBlocked(form, def.name)) continue;
// An authored section is created where the layout places it: right after the furthest section this
// column has already matched, the index the move above uses. Appended, it landed after every
// section still to come — a new one declared mid-column, or a generated one recreated after a
@@ -2611,6 +3274,12 @@ async function runSdkBuildPhases(spec, opts, owed) {
// `columns` is the key that matters most: it is what makes a section render as two
// columns rather than one, and it was previously unreachable on an existing form.
const patch = diffPatch(live, wantSection, ['columns', 'label', 'showLabel', 'visible']);
+ // The engine's own timeline host keeps the width a maker gave the timeline. The spec says nothing about it —
+ // the compiler writes one column — so a maker who widened the timeline (a cell of `colspan` 2 in a
+ // 2-column section, as the platform's Contact form has it) must not have the section narrowed under it: a
+ // cell wider than its section is not a layout, and the re-flow that would clamp it never runs on a host
+ // (repackSectionRows). A host whose cell still fits the one column is narrowed as before.
+ if (!authoredWant && patch.columns !== undefined && !fitsGrid(live.rows || [], Number(patch.columns))) delete patch.columns;
// NARROWING the grid overflows rows that no cell changed. Three unit-width cells sit
// legally in a 4-column row and illegally in a 1-column one, so a width change alone can
// invalidate the layout — and the span-change repack never fires, because no span changed.
@@ -2657,7 +3326,10 @@ async function runSdkBuildPhases(spec, opts, owed) {
}
}
}
- return sectionTargets;
+ // The deployed index each layout tab was matched to (a hole where one could not be placed), beside the section
+ // targets: a sub-grid placed by `tab` is put in the tab the layout's tab resolved to, which is not its index in
+ // the spec once a maker's own tab sits among them.
+ return { sectionTargets, tabIndexOf };
};
// Resolve a section target recorded during the topology pass back to a live pointer.
@@ -2689,6 +3361,21 @@ async function runSdkBuildPhases(spec, opts, owed) {
return (col && (col.sections || [])[Number(t[5])]) || null;
};
+ // Where the section a field being ADDED was queued for is on the form NOW, or null when it is gone.
+ //
+ // A new field is not written when it is queued: it is held until every positioning step is done (see
+ // appendCellPacked), and the sub-grids are placed in between. A grid section added to a column, taken out of it
+ // or moved within it changes the index of every section behind it, so the pointer recorded when the field was
+ // queued can address the grid's section by then — the field lands in the grid — or none at all. The section is
+ // therefore found again by what it is: its id, the one identity a move leaves alone, else (a form whose sections
+ // carry none) its recorded name and place, as every other recorded section is (resolveSectionPointer).
+ const queuedSectionPointer = (form, queued) => {
+ const byId = queued.sectionId ? findSectionById(form, queued.sectionId) : null;
+ if (byId) return byId.pointer;
+ const pointer = resolveSectionPointer(form, { pointer: queued.sectionPointer, name: queued.sectionName });
+ return pointer && sectionAt(form, pointer) ? pointer : null;
+ };
+
// Reflow an ENTIRE section against a new grid width, using the create path's own packer so both
// routes produce the same shape. Called when a section NARROWS: no cell changed, but rows that
// fitted the old width can overrun the new one.
@@ -2701,6 +3388,10 @@ async function runSdkBuildPhases(spec, opts, owed) {
const form = await provision.getArtifact('form', formId) || {};
const section = sectionAt(form, sectionPointer);
if (!section) return;
+ // An engine host is never re-flowed. The timeline's rows are the empty rows its cell spans — which a
+ // re-flow would delete as "beyond the new count" — and a host holds a single control, so there is
+ // nothing for a narrower grid to re-pack.
+ if (isEngineHostSection(section)) return;
const liveRows = section.rows || [];
// A ROWSPAN makes a row's cells positionally meaningful: the cell beneath a vertically spanning
// one is a SPACER reserving the covered slot, and reading-order flattening moves it beside the
@@ -2959,13 +3650,32 @@ async function runSdkBuildPhases(spec, opts, owed) {
section.rows = rows;
};
+ // The rows a field with no resolved section falls back to: the form's first section that is not one the
+ // engine owns. A field must never land in the Notes host or a sub-grid host — in the timeline's section it
+ // would sit under its spacer rows, or beside the timeline once a maker widened the grid — so a host that
+ // happens to come first is passed over. Where every section is a host there is nowhere better to put the
+ // field than the old fallback, which is kept so a field is never lost.
+ const firstFieldSectionRowsPointer = (form) => {
+ const tabs = form.tabs || [];
+ for (let ti = 0; ti < tabs.length; ti += 1) {
+ const columns = (tabs[ti] && tabs[ti].columns) || [];
+ for (let ci = 0; ci < columns.length; ci += 1) {
+ const sections = (columns[ci] && columns[ci].sections) || [];
+ for (let si = 0; si < sections.length; si += 1) {
+ if (!isEngineHostSection(sections[si])) return `/tabs/${ti}/columns/${ci}/sections/${si}/rows`;
+ }
+ }
+ }
+ return firstSectionRowsPointer(form);
+ };
+
const placeFieldInSection = async (formId, logical, wantCell, target, vacated, rawSpan, formName) => {
let form = await provision.getArtifact('form', formId) || {};
const targetPointer = resolveSectionPointer(form, target);
const existing = findFieldCellLocation(form, logical);
if (!existing) {
- const rowsPtr = targetPointer ? targetPointer + '/rows' : firstSectionRowsPointer(form);
+ const rowsPtr = targetPointer ? targetPointer + '/rows' : firstFieldSectionRowsPointer(form);
if (!rowsPtr) return;
const sectionPointer = rowsPtr.slice(0, -'/rows'.length);
// Span the NEW cell for the section it is landing in, by the same rule as an existing one.
@@ -2978,7 +3688,10 @@ async function runSdkBuildPhases(spec, opts, owed) {
const span = spanForLiveSection(key, wantCell, rawSpan, liveSection);
if (span === undefined) delete cell[key]; else cell[key] = span;
}
- return { logical, sectionPointer, cell };
+ // The section is queued by what it IS (its id, its name) as well as where it is: the cell is written only
+ // once every positioning step is done, and addSubgrids runs in between and moves sections about (see
+ // queuedSectionPointer).
+ return { logical, sectionPointer, sectionId: liveSection.id, sectionName: liveSection.name, cell };
}
// Converge the cell SHAPE even when the cell is already where it belongs. `colspan`/`rowspan`
// used to be create-only on an existing form: an author who widened a field to `colspan: 2` on a
@@ -3092,6 +3805,104 @@ async function runSdkBuildPhases(spec, opts, owed) {
+ `section '${destination}' the layout moves it to, so it now spans ${landing.colspan}. Declare its colspan to choose the width.`);
}
};
+ // A new Notes host carries the control id `notescontrol`, the one Dynamics renders a timeline under (see
+ // lib/form-timeline.js). A form that already has a control by that id — a maker's own timeline, or a host an
+ // older build wrote that was renamed since — must not get a second one: ids are names the platform's
+ // designer and scripts address, so a duplicate is not a harmless extra. Reported on the build result, not
+ // dropped: the spec asked for Notes.
+ const timelineCreationBlocked = (form, formName) => {
+ if (!controlIdTaken(form.tabs, TIMELINE_CONTROL_ID)) return false;
+ reportLayoutSkip(`form ${formName}: no Notes section was added — a control on this form already uses the id '${TIMELINE_CONTROL_ID}', `
+ + 'the only id Dynamics renders a timeline under, so a second one would duplicate it. Keep that control as the form\'s timeline, '
+ + `or remove it in the maker, then run ${FULL_BUILD} to let the build add one.`);
+ return true;
+ };
+
+ // An AUTO layout has no topology pass to add the Notes host, so one the form lacks is added here — unless the form
+ // already has a control by `notescontrol` (timelineCreationBlocked). An explicit layout's pass already created the
+ // host, or declined to. It runs BEFORE the sub-grids, so a host an auto form gains here sits where it does on a
+ // new form: ahead of the grids appended after it.
+ const addTimelineHost = async (formId, def) => {
+ if (!def.__notes || def.__explicitLayout) return;
+ const form = await provision.getArtifact('form', formId) || {};
+ if (findSectionLocation(form, 'section_notes', (s) => !!timelineInSection(s))) return;
+ const sectionsPointer = firstColumnSectionsPointer(form);
+ if (!sectionsPointer || timelineCreationBlocked(form, def.name)) return;
+ await provision.addElement('form', formId, sectionsPointer, notesSectionIntent(NOTES_CLASS_ID));
+ if (typeof opts.warn === 'function') opts.warn(`form ${def.name}: added the Notes section (timeline) the spec asks for.`);
+ };
+
+ // Make the Notes section's timeline the shape Dynamics renders (lib/form-timeline.js): the control id
+ // `notescontrol`, a tall cell with `auto="false"`, and the empty rows that cell spans. An older build wrote
+ // the timeline as a generated-id control in a one-row cell, which is published and never shown (#680) — and
+ // because that host is the engine's own section, a rebuild repairs it in place: same section, same position,
+ // same cell and control identity, in ONE write so an interruption leaves either the old rows or the new.
+ //
+ // Only the engine's own host is touched: the section named `section_notes` that holds the timeline control. A
+ // timeline a maker added elsewhere is never edited. Two shapes are left alone and reported (timelineRefusal):
+ // · a host that holds more than the timeline — a maker put a field in it, and the spacer rows the span needs
+ // would have to be inserted between the timeline and that field;
+ // · a host whose control id cannot be renamed because another control already uses `notescontrol`.
+ // Both would leave a form that renders neither better nor worse than before, so the write is refused whole
+ // rather than half-applied.
+ //
+ // It runs LAST of the passes that place fields — after the prune of a field the layout dropped and the moves that
+ // put a field beside its `fieldOptions` anchor — because it rewrites only this section's rows, and because the
+ // first of the two refusals is about what else the section holds. Run before those, it would refuse an old host
+ // whose stray field the SAME build is about to take out: the maker would be told to delete the section while the
+ // build prunes the field, and the form would stay in the old shape until a second build.
+ //
+ // `--verify` reads the form BEFORE these passes, so it predicts what they take out of the host (notesHostInspector in
+ // verify-spec.js). A change to which fields a pass takes out has to be made there too; the cases in
+ // form-timeline-real-bundle.test.js ("verify before the build and the build itself agree") are what keep the two from drifting.
+ // Each of those passes acts on the FIRST cell it finds of a field, in the order the form is in by then — which the topology
+ // pass has already changed — so verify predicts a field only while the form has one cell of it, and says it cannot tell otherwise.
+ //
+ // A host the maker already sized (a cell spanning more than one row) keeps its span: only a one-row cell is
+ // not a working timeline, and the spec says nothing about how tall the timeline is. Platform forms differ in
+ // height too — a cell of N rows with the N-1 rows under it, N being 5, 20, 23 on different forms — and in
+ // whether the cell carries `auto="false"`, so a cell of ANY height with its rows is in shape and nothing is
+ // written for it; `auto` goes in only with the conversion of an old cell (see timelineRepairPlan).
+ const repairTimelineHost = async (formId, def) => {
+ if (!def.__notes) return;
+ const warn = (message) => { if (typeof opts.warn === 'function') opts.warn(message); };
+ const form = await provision.getArtifact('form', formId) || {};
+ const host = findSectionLocation(form, 'section_notes', (s) => !!timelineInSection(s));
+ if (!host) return;
+ const found = timelineInSection(host.section);
+ const plan = timelineRepairPlan(found);
+ if (!Object.keys(plan).length) return;
+ const refusal = timelineRefusal(form.tabs, found);
+ if (refusal === 'other-controls') {
+ reportLayoutSkip(`form ${def.name}: the Notes section's timeline was left as it is — the section also holds other controls, so the rows `
+ + 'its cell needs cannot be inserted without moving them. Move them out of it, or delete the section, in the maker, '
+ + `then run ${FULL_BUILD} to get a timeline that renders.`);
+ return;
+ }
+ if (refusal === 'id-taken') {
+ reportLayoutSkip(`form ${def.name}: the Notes section's timeline was left as it is — its control id cannot become '${TIMELINE_CONTROL_ID}', `
+ + 'the only id Dynamics renders a timeline under, because another control on the form already uses it. '
+ + `Remove or rename one of the two in the maker, then run ${FULL_BUILD}.`);
+ return;
+ }
+ // getArtifact can hand back the stored tree itself, so the repair is made on a copy.
+ const rows = JSON.parse(JSON.stringify(host.section.rows || []));
+ const cell = rows[found.rowIndex].cells[found.cellIndex];
+ if (plan.id) cell.control.id = plan.id;
+ if (plan.rowspan) cell.rowspan = plan.rowspan;
+ if (plan.auto) {
+ // `auto` is a cell attribute the typed cell does not model: it lives in the bag of own attributes.
+ const pairs = ((cell.bag && cell.bag.a) || []).map((pair) => pair.slice());
+ const at = pairs.findIndex((pair) => pair[0] === 'auto');
+ if (at >= 0) pairs[at][1] = plan.auto; else pairs.push(['auto', plan.auto]);
+ cell.bag = Object.assign({ c: [] }, cell.bag, { a: pairs });
+ }
+ for (let i = 0; i < (plan.addRows || 0); i += 1) rows.push({ cells: [] });
+ await provision.updateElement('form', formId, host.rowsPointer, rows);
+ warn(`form ${def.name}: repaired the Notes section's timeline in place to the shape Dynamics renders — control id '${TIMELINE_CONTROL_ID}', `
+ + `a ${cell.rowspan}-row cell and ${rows.length - 1 - found.rowIndex} empty row(s) under it.`);
+ };
+
const reconcileForm = async (formId, def) => {
await provision.fetchArtifact('form', formId);
// The def's field cells are already push-ready ({ control: { fieldName, isRequired? } }); index by
@@ -3116,9 +3927,12 @@ async function runSdkBuildPhases(spec, opts, owed) {
// "holds no cells" cannot tell a section we just emptied from one a maker created empty and may
// show/hide from a form script, and deleting the latter is invisible to the destructive preflight.
const vacatedSections = new Set();
+ // What the topology pass resolved on an explicit layout, for placing sub-grids by it (none on an auto layout).
+ let topology = null;
if (def.__explicitLayout) {
declaredSection = declaredSectionByField(def.tabs);
- sectionTargets = await reconcileFormTopology(formId, def);
+ topology = await reconcileFormTopology(formId, def);
+ sectionTargets = topology.sectionTargets;
}
// RAW authored spans, kept off the compiled cells because a cell is pushed verbatim to the SDK.
// Reconcile re-clamps them against the section it actually writes into: the compiled span is
@@ -3130,7 +3944,11 @@ async function runSdkBuildPhases(spec, opts, owed) {
const created = await placeFieldInSection(formId, logical, wantCellByLogical[logical], sectionTargets[declaredSection[logical]], vacatedSections, rawSpans[logical], def.name);
if (created) newCells.push(created);
}
- await addSubgrids(formId, def.__subgrids);
+ // The Notes timeline: added to an auto layout that has none. Before the sub-grids, so a host an auto form gains
+ // here sits where it does on a new form: ahead of the grids appended after it. An older host's repair comes last
+ // (repairTimelineHost), once the prune and the field moves have emptied it of fields.
+ await addTimelineHost(formId, def);
+ await addSubgrids(formId, def, { topology, sectionTargets });
// Re-assert per-control attributes (read-only / hidden) on fields that were ALREADY on the form.
// New cells already carry their compiled flags; existing ones need this assertion before the
// combined layout plan. Without it an author who marks an
@@ -3141,6 +3959,7 @@ async function runSdkBuildPhases(spec, opts, owed) {
// `/…/control` with `{ isReadOnly: true }` preserves classId, label and every other adapter-derived
// value. It does NOT mint ids, which is exactly right here — the cell already has one.
await applyFieldControlOptions(formId, def, want, wantCellByLogical);
+ await repairLookupCellLabelsOn(formId, def);
// Reposition any field the spec anchors after another (`fieldOptions[x].after`). Runs AFTER the
// attribute pass; new cells and all anchored moves then persist together in one artifact edit.
await applyFieldPositions(formId, def, vacatedSections, newCells);
@@ -3245,15 +4064,24 @@ async function runSdkBuildPhases(spec, opts, owed) {
}
}
}
- requireSuccessfulPush(await provision.pushArtifact('form', formId), `form ${def.name}`, opts.warn);
- reportPartialPush(await provision.publishArtifact('form', formId), `form ${def.name}`, opts.warn);
- await provision.addSolutionComponent({ componentId: formId, componentType: COMPONENT_TYPE.form, solutionUniqueName: sol.uniqueName });
+ // The Notes timeline of an older build, repaired in place — LAST of the passes that change a form's fields and
+ // sections, so a host the prune and the field moves have just emptied is the clean host the repair needs.
+ // It edits the workspace copy only, so the check below sees it: a repaired form is pushed, an unchanged one is not.
+ await repairTimelineHost(formId, def);
+ // Push only when the copy holds an edit the server has not seen: an unchanged form would be sent back
+ // as the document the server already holds (three version reads, a PATCH and a read-back). A copy an
+ // earlier interrupted run left edited still differs from its snapshot, so it is pushed as before.
+ if (await hasUnsyncedEdits(provision, 'form', formId)) {
+ requireSuccessfulPush(await provision.pushArtifact('form', formId), `form ${def.name}`, opts.warn);
+ }
+ await publishReconciled('form', formId, def.entityLogicalName, `form ${def.name}`);
+ await ensureInSolution(formId, COMPONENT_TYPE.form, def.entityLogicalName);
return formId;
};
// Reconcile an EXISTING author view: fetch it, UNION its current columns with the spec's (so a
- // manual column add in Maker is preserved AND the spec's new lookup columns land), set, push,
- // publish. Editing a view's column set (e.g. to surface a parent lookup) now takes effect.
+ // manual column add in Maker is preserved AND the spec's new lookup columns land), set, push when that
+ // changed anything, publish. Editing a view's column set (e.g. to surface a parent lookup) now takes effect.
const reconcileView = async (viewId, def, authoredQuery) => {
await provision.fetchArtifact('view', viewId);
const current = await provision.getArtifact('view', viewId) || {};
@@ -3295,9 +4123,15 @@ async function runSdkBuildPhases(spec, opts, owed) {
if (authoredQuery && typeof opts.warn === 'function') {
opts.warn(`view '${def.name}' 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.`);
}
- requireSuccessfulPush(await provision.pushArtifact('view', viewId), `view ${def.name}`, opts.warn);
- reportPartialPush(await provision.publishArtifact('view', viewId), `view ${def.name}`, opts.warn);
- await provision.addSolutionComponent({ componentId: viewId, componentType: COMPONENT_TYPE.view, solutionUniqueName: sol.uniqueName });
+ // Push only when the copy holds an edit the server has not seen — a new column or description above, or
+ // one an earlier interrupted run left in the workspace. The columns this build writes are the fetched ones
+ // verbatim plus any the spec adds, so an ordinary rebuild changes nothing and issues no write here; this is
+ // what the description guard above already promises.
+ if (await hasUnsyncedEdits(provision, 'view', viewId)) {
+ requireSuccessfulPush(await provision.pushArtifact('view', viewId), `view ${def.name}`, opts.warn);
+ }
+ await publishReconciled('view', viewId, def.entityLogicalName, `view ${def.name}`);
+ await ensureInSolution(viewId, COMPONENT_TYPE.view, def.entityLogicalName);
return viewId;
};
@@ -3576,18 +4410,20 @@ async function runSdkBuildPhases(spec, opts, owed) {
createdFormsThisRun.add(normalizeFormId(id));
// AB#6736948: on a table whose order the build does not set, the form is created in its place.
await createInPlace(id, meta && meta.specForm);
- await addSubgrids(id, def.__subgrids);
+ await addSubgrids(id, def, null);
} else {
id = (await provision.createArtifact(type, def)).id;
}
const pushed = requireSuccessfulPush(await provision.pushArtifact(type, id), `${type} ${def.name}`, opts.warn);
+ noteSaved(def.entityLogicalName, `${type} ${def.name}`);
await provision.addSolutionComponent({ componentId: pushed.id, componentType: COMPONENT_TYPE[type], solutionUniqueName: sol.uniqueName });
return pushed.id;
});
// 4. Views (independent -> parallel).
if (has('views')) {
- const ids = await runner.mapLimit(spec.views || [], concurrency, (v) => buildArtifact('view', viewDef(spec, v), { authoredQuery: !!((v.filters || []).length || (v.sort || []).length) }));
+ const labelResolution = await resolveViewLabelsOrHalt(spec, provision, sayViewLabel, preflightResolved);
+ const ids = await runner.mapLimit(spec.views || [], concurrency, (v) => buildArtifact('view', viewDef(spec, v, labelResolution), { authoredQuery: !!((v.filters || []).length || (v.sort || []).length) }));
// Key by `entity|name` (matching identityOf.view + the snapshot canonical id). View names are unique
// only PER ENTITY, so a name-only key lets a same-named view on another entity OVERWRITE this id and
// cross-wire dashboards / sub-grids / AI-summaries to the wrong entity's view.
@@ -3606,11 +4442,17 @@ async function runSdkBuildPhases(spec, opts, owed) {
// carries the same record on its error. Without --publish nothing is deferred: the SDK publishes
// the enrichment itself, as before. What is still owed when a phase halts leaves with the halt
// (runSdkBuild), and the caller publishes it once no retry follows (settleOwedPublishes).
- const deferDefaultViewPublish = has('publish') && publish;
+ //
+ // The saved default views are named in the table's owed record, whether the enrichment makes the record or
+ // joins one an authored view's reconcile already made (oweTablePublish): the SDK reports a view as pending only
+ // when its push SAVED, so the name is there whenever the enrichment saved, which the SDK does on every build (an
+ // unchanged rebuild re-sends both generated views with identical content), and a failed publish then says that the
+ // generated Active/Inactive pair is not live either.
+ const deferDefaultViewPublish = publishInPhase8;
const recordOwed = (logical, record) => {
for (const pending of (record && record.pendingPublish) || []) {
const first = (pending.artifacts || [])[0];
- if (first && first.id && !owed.tables.has(logical)) owed.tables.set(logical, [first.type || 'view', first.id]);
+ if (first && first.id) oweTablePublish(logical, first.type || 'view', first.id, `default views of ${logical}`);
}
};
if (has('views')) {
@@ -3701,6 +4543,7 @@ async function runSdkBuildPhases(spec, opts, owed) {
// text to be served. Safe to queue only here: the fetch above has put the chart in the
// workspace, which publishArtifact requires.
chartsToPublish.set(String(def.entityLogicalName || '').toLowerCase(), existingId);
+ noteSaved(def.entityLogicalName, `chart ${def.name}`);
}
} catch (err) {
// Best-effort — a description is an inspection aid and must not fail a build. But it must
@@ -3721,7 +4564,7 @@ async function runSdkBuildPhases(spec, opts, owed) {
// charts by name from `spec.charts` rather than by solution membership.) Previously this
// branch returned without adding it; the create path below and reconcileView both add theirs.
try {
- await provision.addSolutionComponent({ componentId: existingId, componentType: COMPONENT_TYPE.chart, solutionUniqueName: sol.uniqueName });
+ await ensureInSolution(existingId, COMPONENT_TYPE.chart, def.entityLogicalName);
} catch { /* already a component, or not ours to add — never fail a build over it */ }
return existingId;
}
@@ -3731,6 +4574,7 @@ async function runSdkBuildPhases(spec, opts, owed) {
await provision.addSolutionComponent({ componentId: pushed.id, componentType: COMPONENT_TYPE.chart, solutionUniqueName: sol.uniqueName });
// Created here, so it IS workspace-resident and publishable.
chartsToPublish.set(String(def.entityLogicalName || '').toLowerCase(), pushed.id);
+ noteSaved(def.entityLogicalName, `chart ${def.name}`);
return pushed.id;
});
});
@@ -3744,6 +4588,8 @@ async function runSdkBuildPhases(spec, opts, owed) {
const defs = await Promise.all((spec.forms || []).map(async (f) => {
const def = compileFormIntent(spec, f, { notesClassId: NOTES_CLASS_ID });
const subs = [];
+ // The tabs, form-columns and sections this form declares — what a sub-grid's placement is resolved against.
+ const layoutNames = formLayoutNames(f);
// Gap 7: opt-in auto sub-grids. `forms[].autoSubgrids: true` adds a sub-grid for every child
// relationship of this form's entity (1:N where it's the parent + N:N) that isn't already
// declared in subgrids[], so a hub table's form lists its children without hand-authoring each.
@@ -3756,10 +4602,8 @@ async function runSdkBuildPhases(spec, opts, owed) {
}
for (const sg of subgridSpecs) {
// A sub-grid can hang off a 1:N (child has the lookup) or an N:N (intersect) relationship.
- const oneToMany = relationshipFor(spec, f.entity, sg.childEntity);
- const nn = oneToMany ? null : manyToManyFor(spec, f.entity, sg.childEntity);
- if (!oneToMany && !nn) continue;
- const relationshipName = oneToMany ? relationshipSchemaName(oneToMany, spec.solution && spec.solution.publisherPrefix) : manyToManySchemaName(nn, spec.solution && spec.solution.publisherPrefix);
+ const relationshipName = subgridRelationshipName(spec, f.entity, sg.childEntity);
+ if (!relationshipName) continue;
const childLogical = sg.childEntity.toLowerCase();
const viewId = await subgridViewId(provision, result.created.views, spec, sg, childLogical);
// Every sub-grid needs a concrete view id (the SDK embeds it in the control XML). If the
@@ -3769,9 +4613,19 @@ async function runSdkBuildPhases(spec, opts, owed) {
// #5: title the sub-grid with the child's display name, not its logical name. Shared pure
// helper (subgridLabel) so the eval harness grades the same title the engine writes.
const gridLabel = subgridLabel(spec, sg);
- subs.push({ targetEntity: childLogical, relationshipName, viewId, label: gridLabel });
+ const entry = { targetEntity: childLogical, relationshipName, viewId, label: gridLabel };
+ // Where the entry places its grid (tab / column / after / before), resolved against the layout this form
+ // declares. A key-less entry carries no `placement` at all, which is what keeps it on the original path.
+ const raw = placementOf(sg);
+ if (raw) {
+ const resolved = resolvePlacement(layoutNames, raw);
+ if (resolved.ok) entry.placement = { raw, resolved };
+ else reportLayoutSkip(`form ${f.name || f.entity}: the placement of the sub-grid for '${childLogical}' was ignored — the layout does not declare what it names, so the grid goes where it always does.`);
+ }
+ subs.push(entry);
}
def.__subgrids = subs;
+ def.__subgridLayout = layoutNames;
return { f, def };
}));
const ids = await runner.mapLimit(defs, concurrency, async (d) => {
@@ -3784,7 +4638,7 @@ async function runSdkBuildPhases(spec, opts, owed) {
// handler was appended, so re-runs don't duplicate a handler or a second <events> root).
if (await wireFormEvents(id, wantedEvents)) {
requireSuccessfulPush(await provision.pushArtifact('form', id), `form ${d.f.name || d.f.entity} events`, opts.warn);
- reportPartialPush(await provision.publishArtifact('form', id), `form ${d.f.name || d.f.entity} events`, opts.warn);
+ await publishReconciled('form', id, d.f.entity, `form ${d.f.name || d.f.entity} events`);
}
});
}
@@ -3887,7 +4741,8 @@ async function runSdkBuildPhases(spec, opts, owed) {
// Quick-view placement: embed a built QuickView form onto a host form via a lookup column,
// added as a canonical quick-view control cell (semantic identity = the lookup field, so a
// rebuild doesn't duplicate it). Runs after ALL forms are built so a host can reference a
- // QuickView form created concurrently. Placed in the host's first section.
+ // QuickView form created concurrently. Placed in the host's first FIELD section: a sub-grid placed ahead of the
+ // form's own sections, or the Notes section, is a section the engine owns and holds nothing else.
const formIdByEntityName = {};
// Only QuickView forms are quick-view targets. Keying ALL forms by (entity, name) let a same-named
// Main form on the SAME entity OVERWRITE the QuickView entry (order-dependent), embedding the wrong
@@ -3908,14 +4763,14 @@ async function runSdkBuildPhases(spec, opts, owed) {
if (!qvFormId) throw new Error(`form "${f.name || f.entity}" quick-view references form '${qv.form}' on '${qv.targetEntity}' which wasn't built — declare it in forms[] with formType: "QuickView", entity "${qv.targetEntity}", and a matching name`);
const lookup = String(qv.lookup).toLowerCase();
if (hasQuickView(await provision.getArtifact('form', hostId) || {}, lookup)) continue; // idempotent
- const rowsPtr = firstSectionRowsPointer(await provision.getArtifact('form', hostId) || {});
+ const rowsPtr = firstFieldSectionRowsPointer(await provision.getArtifact('form', hostId) || {});
if (!rowsPtr) continue;
await provision.addElement('form', hostId, rowsPtr, { cells: [quickViewCellIntent({ quickViewClassId: QUICK_VIEW_CLASS_ID, lookupFieldName: lookup, targetEntity: String(qv.targetEntity).toLowerCase(), quickViewFormId: qvFormId, label: qv.label })] });
changed = true;
}
if (changed) {
requireSuccessfulPush(await provision.pushArtifact('form', hostId), `form ${f.name || f.entity} quick-views`, opts.warn);
- reportPartialPush(await provision.publishArtifact('form', hostId), `form ${f.name || f.entity} quick-views`, opts.warn);
+ await publishReconciled('form', hostId, f.entity, `form ${f.name || f.entity} quick-views`);
}
});
}
@@ -4028,12 +4883,13 @@ async function runSdkBuildPhases(spec, opts, owed) {
// where the rule was written but the component add failed — or a rule created by an earlier
// build of a DIFFERENT solution — is reused forever and never joins this one, leaving it out
// of export/import with nothing in the output saying so. The SDK treats an already-present
- // component as success, so re-issuing it every build is safe.
+ // component as success, so re-issuing it every build is safe; the membership read
+ // (solution-membership.js) spares the write when the solution is proven to hold the rule.
//
// A failure here warns rather than halts: the rule itself is correct and running, and
// blocking an otherwise-good build over solution bookkeeping would be the worse outcome.
try {
- await provision.addSolutionComponent({ componentId: existingId, componentType: COMPONENT_TYPE.workflow, solutionUniqueName: sol.uniqueName });
+ await ensureInSolution(existingId, COMPONENT_TYPE.workflow);
} catch (e) {
if (typeof opts.warn === 'function') {
opts.warn(`business rule "${rule.name}" on ${rule.entity} exists but could not be added to solution '${sol.uniqueName}' (${e && e.message}). The rule works, but it will not travel on solution export until it is added.`);
@@ -4182,10 +5038,11 @@ async function runSdkBuildPhases(spec, opts, owed) {
// add failed (or a flow created by an earlier build of a different solution) would be reused
// forever and never join this solution — leaving it out of export/import with nothing in the
// output saying so. The SDK treats an already-present component as success, so this is safe
- // to re-issue every build; a failure here is a warning, not a halt, because the flow itself
+ // to re-issue every build, and the membership read (solution-membership.js) spares the write when the
+ // solution is proven to hold the flow. A failure here is a warning, not a halt, because the flow itself
// is correct and blocking the build over solution bookkeeping would be worse than reporting it.
try {
- await provision.addSolutionComponent({ componentId: existingId, componentType: COMPONENT_TYPE.workflow, solutionUniqueName: sol.uniqueName });
+ await ensureInSolution(existingId, COMPONENT_TYPE.workflow);
} catch (e) {
if (typeof opts.warn === 'function') {
opts.warn(`business process flow "${flow.name}" on ${flow.entity} exists but could not be added to solution '${sol.uniqueName}' (${e && e.message}). The flow works, but it will not travel on solution export until it is added.`);
@@ -4445,6 +5302,8 @@ async function runSdkBuildPhases(spec, opts, owed) {
const iconWebResourceId = await ensureAppIcon(spec, result.created, { provision, sol, runner });
const def = appDef(spec, result.created, { omitUnbuiltPages: true, iconWebResourceId, mainFormsByTable });
result.created.app = await runner.run('app-shell', `app "${def.name}"`, async () => {
+ // Before anything below publishes the app: see publishReconciledTables.
+ await publishReconciledTables();
const existingId = await provision.findArtifact('app', { uniqueName: def.uniqueName });
if (existingId) {
appWasExisting = true;
@@ -4459,9 +5318,10 @@ async function runSdkBuildPhases(spec, opts, owed) {
// Re-assert the app module's own solution membership on every reuse, as the page manifest's is. A
// create that failed after its push (a pin, its read-back, a publish) left the app outside the
// solution, and a re-run lands here: without this add, a later green build exported a solution
- // without its app. Adding a component that is already a member is a no-op. Teardown deletes the
- // app by its unique name, never by this membership, so the add changes nothing it removes.
- await provision.addSolutionComponent({ componentId: existingId, componentType: COMPONENT_TYPE.app, solutionUniqueName: sol.uniqueName });
+ // without its app. Adding a component that is already a member is a no-op, so it is skipped when the
+ // solution is proven to hold it (solution-membership.js). Teardown deletes the app by its unique name,
+ // never by this membership, so the add changes nothing it removes.
+ await ensureInSolution(existingId, COMPONENT_TYPE.app);
// Existing-app app-shell often makes NO SDK push: its sitemap commit is in the pages finalizer.
// Pin now, independently, and let that normal publish make the proven current layer live.
await pinTables(existingId, false);
@@ -4523,11 +5383,18 @@ async function runSdkBuildPhases(spec, opts, owed) {
reportPartialPush(await provision.publishArtifact('app', existingId), `app ${def.name}`, opts.warn);
}
}
- await ensureSitemapInSolution(provision, sol, def.uniqueName);
+ await ensureSitemapInSolution(provision, sol, def.uniqueName, solutionMembers);
return existingId;
}
// Create: the full def (siteMap + explicit components + iconWebResourceId) serializes unchanged
// through createArtifact, and push emits appmodule -> sitemap -> AddAppComponents -> publish.
+ // The def leaves `published` unset on purpose, so the push above publishes the app. The SDK can
+ // create a never-published draft (`published: false`) for the final publish to cover — one publish
+ // round trip less — but a draft answers 404 by id and is missing from the PUBLISHED projection that
+ // every probe here reads (findArtifact('app'), the collision gate, the sitemap/navigation reads of
+ // the pages phase that follows, verify, download). A failed first build would leave an app its own
+ // re-run cannot see (it would POST the same unique name again), the pages phase would find no sitemap
+ // and halt, and a build without --publish would never publish it. Pinned in sdk-opt-ins.test.js.
const art = await provision.createArtifact('app', def);
const pushed = requireSuccessfulPush(await explainAppPushWarnings(provision.dataverse, await provision.pushArtifact('app', art.id), def.name), `app ${def.name}`, opts.warn);
// Join the solution straight after the push, before the hidden-table pin, its read-back and the
@@ -4596,10 +5463,10 @@ async function runSdkBuildPhases(spec, opts, owed) {
const live = new Set(enumd.ids.map((id) => String(id).toLowerCase()));
const declaredKeys = new Set((spec.pages || []).map((p) => p.key || p.name));
// Ownership proof for an UPDATE is this app's PUBLISHED navigation or a local creation receipt. A page
- // that is only in the app's saved but unpublished navigation is not bound: the shared-page scan below
- // reads other apps' published navigation only, so binding it could overwrite a page another app has
- // also saved into its navigation. Such a page halts as unproven, with advice to publish first
- // (navigationProof reads the saved layer for that message).
+ // that is only in the app's saved but unpublished navigation is not bound by this build: it halts as
+ // unproven, with advice to publish first (navigationProof reads the saved layer for that message). The
+ // shared-page scan below reads OTHER apps' saved navigation as well as their published navigation, so a
+ // page another app has saved into its navigation is caught there before it is updated.
const placed = new Set(sitemapIds.map((id) => String(id).toLowerCase()));
let ownership;
try { ownership = readPageOwnership(opts.workspaceDir, appUnique, opts.env); } catch (e) {
@@ -4701,22 +5568,48 @@ async function runSdkBuildPhases(spec, opts, owed) {
// its content would mutate a page another app uses. GROUNDED (live probe): a genpage has NO
// appmodulecomponent row, so the ONLY membership signal is the sitemap XML; there is no direct
// genpage→apps join, so we scan every OTHER app's sitemap (fetchAppsForPages; `excludeAppUnique` self-
- // skips, so a single-app env reads zero other sitemaps). FAIL-CLOSED: an env-scan failure OR any app
+ // skips, so a single-app env reads zero other sitemaps). BOTH layers count: an app's published sitemap
+ // and its saved (current, unpublished) one — a page another app has saved into its navigation but not
+ // yet published is still that app's, and publishes at any moment. An app that was NEVER published has no
+ // published layer and no row in the published app list, so the scan lists those too (one request; a
+ // single-app env pays that one request and nothing more). The saved layer of all other apps is
+ // one extra request. FAIL-CLOSED: an env-scan failure (the saved read included) OR any app
// whose sitemap we cannot read HALTs — an unreadable app could be the one that shares the page, so we
// cannot prove non-sharing. On positive detection (id in ≥1 other app) → HALT (never auto-modify);
// --allow-destructive does NOT authorize cross-app mutation (this HALT has no escape by design).
- const updateIds = Array.from(keyToId.values());
- if (updateIds.length) {
- const scan = await fetchAppsForPages(provision, updateIds, { excludeAppUnique: appUnique });
+ //
+ // The scan is a snapshot, and another maker can add a page to another app's navigation while this build runs: no lease reaches
+ // another app (the one above is this workspace's), Dataverse offers no write conditional on another app's sitemap, and the update
+ // itself goes through `pac`, which takes no precondition. So a build that writes a page in place takes the same scan twice more
+ // (sharedPagesNow, in the upload loop below): right before the first page is written in place, which halts on a page that became
+ // shared while pages were created and navigation resolved; and after the last — or after the loop stops early — which REPORTS a page
+ // that became shared while the uploads ran: written by then, so it names the app rather than claim a protection it could not give.
+ // A page this run created is left out of both: it was not there to share when the build began. Each scan reads every other app's
+ // navigation (three requests per other app, and three more), so it is taken those two times, not before every page.
+ const scanShared = async (ids) => {
+ const scan = await fetchAppsForPages(provision, ids, { excludeAppUnique: appUnique });
+ if (!scan.ok || scan.unreadable.length) return { scan, entries: null };
+ // An app that has the page ONLY in its saved navigation is named as such: nothing in its published app shows the page yet.
+ return { scan, entries: Array.from(scan.byId, ([id, apps]) => {
+ const savedOnly = (scan.savedOnly && scan.savedOnly.get(id)) || [];
+ return { id, published: apps.some((app) => !savedOnly.includes(app)), text: `${id} (also in ${apps.map((app) => (savedOnly.includes(app) ? `${app} [saved, not published]` : app)).join(', ')})` };
+ }) };
+ };
+ const sharedPagesNow = async (ids) => {
+ const { scan, entries } = await scanShared(ids);
if (!scan.ok) throw new BuildHalt(`could not scan the environment for pages shared across apps (${scan.error}) — refusing to UPDATE a page without verifying it is not shared. Re-run to retry.`, { phase: 'pages', code: 'pages-shared-check-failed', recoverable: true });
if (scan.unreadable.length) throw new BuildHalt(`cannot verify pages are not shared across apps — ${scan.unreadable.length} app(s) had an unreadable sitemap (${scan.unreadable.join(', ')}); one of them could share a page we are about to UPDATE. Fix or remove the unreadable app(s), then rebuild.`, { phase: 'pages', code: 'pages-shared-check-failed', recoverable: true });
- if (scan.byId.size) {
- const shared = Array.from(scan.byId, ([id, apps]) => `${id} (also in ${apps.join(', ')})`);
- throw new BuildHalt(`generative page(s) shared across apps: ${shared.join('; ')} — refusing to UPDATE a page another app's sitemap references (a rebuild would mutate shared content). Detach it in Maker, or give this app its own page.`, { phase: 'pages', code: 'pages-shared-across-apps', recoverable: false });
+ return entries;
+ };
+ const updateIds = Array.from(keyToId.values());
+ if (updateIds.length) {
+ const shared = await sharedPagesNow(updateIds);
+ if (shared.length) {
+ throw new BuildHalt(`generative page(s) shared across apps: ${shared.map((s) => s.text).join('; ')} — refusing to UPDATE a page another app's sitemap references (a rebuild would mutate shared content). Detach it in Maker, or give this app its own page.`, { phase: 'pages', code: 'pages-shared-across-apps', recoverable: false });
}
}
- const persistNow = async () => { const pr = await persistPageManifest(provision, spec, keyToId, sol, appUnique, manifestId, lastManifestContent); manifestId = pr.id; lastManifestContent = pr.content; };
+ const persistNow = async () => { const pr = await persistPageManifest(provision, spec, keyToId, sol, appUnique, manifestId, lastManifestContent, solutionMembers); manifestId = pr.id; lastManifestContent = pr.content; };
const recordCreate = (p, id) => {
// No workspace means no durable creation authority. Normal CLI builds always supply one.
if (!opts.workspaceDir) {
@@ -4724,7 +5617,9 @@ async function runSdkBuildPhases(spec, opts, owed) {
return;
}
try { recordPageCreation(opts.workspaceDir, appUnique, p.key || p.name, id, p.name, opts.env); } catch (e) {
- throw new BuildHalt(`page "${p.name}" was created as ${id}, but its local receipt could not be saved (${e.message}); stopping before manifest or sitemap changes`, { phase: 'pages', code: 'pages-creation-receipt-failed', recoverable: false });
+ // `transient: false`: the page exists and nothing records it, so the build's own re-run of a halt it takes for transient (isTransientHalt, build-model-app.js — which reads this
+ // message, and so the page's name: "SQL Timeouts" would match) would create a second one beside it.
+ throw Object.assign(new BuildHalt(`page "${p.name}" was created as ${id}, but its local receipt could not be saved (${e.message}); stopping before manifest or sitemap changes`, { phase: 'pages', code: 'pages-creation-receipt-failed', recoverable: false }), { transient: false });
}
};
@@ -4756,9 +5651,49 @@ async function runSdkBuildPhases(spec, opts, owed) {
// call sites — a decoy "PAGEREF_" string or a stray GUID in a comment can never pass.
// new-Important-1 (OVERRIDE 2): additionally reject `dynamic` (variable/expression) and `literal`
// (hardcoded GUID) nav pageIds — a nav target must always be a declared "PAGEREF_<key>" symbol.
+ // The Griffel check (AB#6691124) rides the same scan: a `makeStyles` key Griffel drops at runtime ships a page
+ // without its border, colour or reset, and nothing else on the way to the service notices — so a page that would
+ // ship one is refused here, with the file, line, column and longhands, whoever wrote it and whatever instructions
+ // they followed (scripts/check-griffel-styles.js is the same check, run earlier for quicker feedback).
+ // Which pages THIS run uploads: the Griffel check is held only against those. A changed-only run uploads its selected keys and
+ // mints an absent navigation target, and nothing else; a page it does not upload is not shipped, so it is not refused for a defect
+ // it is not shipping (the rest of this scan still covers every page, because navigation resolves across all of them).
+ const navTargets = new Set();
+ for (const p of implemented) for (const n of p.navigatesTo || []) navTargets.add(n.targetKey);
+ const selectedKeys = opts.changedOnly && Array.isArray(opts.changedOnly.selectedKeys) ? new Set(opts.changedOnly.selectedKeys) : null;
+ const uploadedThisRun = (p) => !selectedKeys || selectedKeys.has(keyOf(p)) || (navTargets.has(keyOf(p)) && !keyToId.has(keyOf(p)));
+ // …and of those, which would ship something NEW. A full build re-sends every page, and a page deployed by an earlier version of the plugin can already carry a key
+ // Griffel drops (its only guard was a grep for `borderWidth`, so `borderColor` under `:hover` passed). Re-sending the same bytes ships nothing new, and refusing it would stop
+ // a rebuild after a change to a view — over a page nobody touched, with earlier phases already written — whose only way through is to edit the page, and switching to
+ // longhands changes how it renders. So the page's standing decides, without a download per page (the build holds no copy of what is deployed):
+ // 'new' no deployed page (it is created): held to the check.
+ // 'changed' the page exists and its source is not the one the last recorded apply sent — last-applied.json (written by every apply and download, for this app in
+ // this environment only: opts.baselineSpec) records each page's `__contentSha`, the changed-only flow's own measure of "this page changed": held to the check.
+ // 'unchanged' its source hashes to that record: it ships nothing new, so it is warned about.
+ // 'unrecorded' the page exists, but there is no record for it (a workspace that is new, moved or cleared, or an apply that predates the record): the build cannot tell, and
+ // warns. This fails OPEN, on purpose — a release that predates this check built such pages (the key silently dropped), and a build that stops them now
+ // regresses a rebuild it used to complete; the cost is that an edit that ADDS a key to such a page is warned about, not stopped, until a recorded apply exists.
+ const griffelStanding = (p, sourceSha) => {
+ if (!keyToId.has(keyOf(p))) return 'new';
+ const recorded = recordedContentSha(opts.baselineSpec, keyOf(p));
+ if (recorded === null) return 'unrecorded';
+ return recorded === sourceSha ? 'unchanged' : 'changed';
+ };
+ const griffelWarnings = [];
const sourceByKey = new Map();
+ // The hash of each page's source as this scan READ it — what every check below is made on, and so what the apply may record as the source it sent (`created.pageSourceShas`, below).
+ // The baseline (deployed-baseline.js) used to hash the files again when the build ENDED, so a page saved while the build ran was recorded as applied: the next build then found the
+ // source it was about to send "unchanged" and let a key it never checked through with a warning.
+ const scannedSha = new Map();
+ // The bytes themselves, as the scan read them: every upload below sends a staging copy of these (writeStagingFile), never the canonical file, which may have been
+ // saved again since — the checks above and the hash recorded for the page are then about exactly what was sent.
+ const scannedBytes = new Map();
for (const p of implemented) {
- const code = fs.readFileSync(canonicalPath(p), 'utf8');
+ const bytes = fs.readFileSync(canonicalPath(p));
+ scannedBytes.set(keyOf(p), bytes);
+ const sourceSha = sha256(bytes);
+ scannedSha.set(keyOf(p), sourceSha);
+ const code = bytes.toString('utf8');
sourceByKey.set(keyOf(p), code);
const malformed = navMalformedRefs(code);
if (malformed.length) throw new BuildHalt(`page "${p.name}" has malformed navigation reference(s): ${malformed.join(', ')} — a cross-page link must be a double-quoted "PAGEREF_<key>" pageId literal, alone or followed only by casts such as \`as const\`; ${PAGEREF_RULE}`, { phase: 'pages', code: 'pages-malformed-navref', recoverable: false });
@@ -4777,10 +5712,28 @@ async function runSdkBuildPhases(spec, opts, owed) {
// string — a dead link — so it halts here, before any page is created, naming the page and where the token is.
const stray = strayPageRefs(code);
if (stray.length) throw new BuildHalt(`page "${p.name}" has PAGEREF_ token(s) that no navigation rewrite will resolve, so they would ship as literal text: ${describePageRefLocations(stray)} — ${pageRefAdvice(stray)}`, { phase: 'pages', code: 'pages-stray-pageref', recoverable: false });
+ // The Griffel check, last, so a page's navigation problems — which a style fix does not touch — are reported first. The file named is the canonical source, as the spec gives it.
+ // A page that is created, or whose source changed since the last recorded apply, is held to it; one that is sent again as it is gets a warning (griffelStanding above).
+ if (uploadedThisRun(p)) {
+ const problems = griffelStyleProblems(code).problems;
+ if (problems.length) {
+ const standing = griffelStanding(p, sourceSha);
+ const words = { surface: 'build', subject: `page "${p.name}"`, command: 'node scripts/check-griffel-styles.js --file <page.tsx>' };
+ const file = normalizePageSource(p).codeFile;
+ if (standing === 'new' || standing === 'changed') {
+ const note = standing === 'changed' ? 'Its source changed since the last build recorded for it, so it is held to the check as a new page is; left as it was, it would only be warned about.' : '';
+ // `transient: false`, as for the receipt halt: this refuses the page's own source, before anything in the pages phase is written, so running the build again cannot change
+ // the answer — but isTransientHalt (build-model-app.js) reads the halt's TEXT, which opens with the page's name, and a page called "SQL Timeout Report" would read as a
+ // transient error: three more runs of every earlier phase, and a log that blames the service.
+ throw Object.assign(new BuildHalt(describeGriffelRefusal(problems, file, { ...words, note }), { phase: 'pages', code: 'pages-griffel-shorthand', recoverable: false }), { transient: false });
+ }
+ griffelWarnings.push(describeGriffelWarning(problems, file, { ...words, standing }));
+ }
+ }
}
+ // After the whole scan, so a build that halts on a later page says only why it halted. Nothing has been written yet, and the pages that are warned about are sent as they are.
+ if (typeof opts.warn === 'function') for (const warning of griffelWarnings) opts.warn(warning);
- const navTargets = new Set();
- for (const p of implemented) for (const n of p.navigatesTo || []) navTargets.add(n.targetKey);
const mintedKeys = new Set();
const deployment = new Map(); // key -> resolved code (nav sources only)
@@ -4793,10 +5746,11 @@ async function runSdkBuildPhases(spec, opts, owed) {
for (const p of implemented) {
const key = keyOf(p);
if (keyToId.has(key) || !navTargets.has(key)) continue; // only ABSENT targets need pre-minting
- const up = await genpageCli.upload({ appId: result.created.app, codeFile: canonicalPath(p), name: p.name, prompt: p.prompt, agentMessage: p.agentMessage, dataSources: p.dataSources, model: p.model });
+ const up = await genpageCli.upload({ appId: result.created.app, codeFile: writeStagingFile(stagingDir, key, scannedBytes.get(key)), name: p.name, prompt: p.prompt, agentMessage: p.agentMessage, dataSources: p.dataSources, model: p.model, caller: 'build' });
recordCreate(p, up.pageId);
keyToId.set(key, up.pageId);
result.created.pages[key] = up.pageId;
+ result.created.pageSourceShas[key] = scannedSha.get(key);
mintedKeys.add(key);
await persistNow();
}
@@ -4827,35 +5781,85 @@ async function runSdkBuildPhases(spec, opts, owed) {
// re-uploading an UNCHANGED page would clobber an out-of-band Maker edit to it (Sol #1 / data loss).
// keyToId already holds every existing page's live id (reconciled from the manifest/enumerate), so a
// changed page that navigates to an unchanged page still resolves its target without re-uploading it.
- const selectedKeys = opts.changedOnly && Array.isArray(opts.changedOnly.selectedKeys) ? new Set(opts.changedOnly.selectedKeys) : null;
- for (const p of implemented) {
+ // (`selectedKeys` is the one read above, ahead of the scan.)
+ //
+ // The pages the loop writes IN PLACE — a page id the build began with, which it now overwrites; never one this run created (step 2's
+ // navigation targets included), which no other app could have held when the build began — are checked for sharing once more right
+ // before the first of them is written, and once after the last (see "The scan is a snapshot" above). A halt there comes before any page
+ // the build began with is written in place, so it says so. `transient: false`: another app's navigation still holds the page, so the build's own re-run of a
+ // halt it takes for transient (isTransientHalt, build-model-app.js, which reads the message) would only halt again — marked outright,
+ // since the message quotes other apps' names, which no transient pattern should ever be able to turn into a re-run.
+ const writesInPlace = new Set(implemented.filter((p) => {
const key = keyOf(p);
- if (selectedKeys && !selectedKeys.has(key)) { runner.skip('pages', `page "${p.name}" (unchanged — changed-only)`); continue; }
- const isNav = (p.navigatesTo || []).length > 0;
- if (!isNav && mintedKeys.has(key)) { runner.skip('pages', `page "${p.name}" (created)`); continue; }
- await runner.run('pages', `page "${p.name}"`, async () => {
- const requestedId = keyToId.get(key);
- // Capture the EXACT bytes we upload so the caller can record a MEASURED deployedSha (a nav source's
- // deployed bytes differ from its canonical source — PAGEREF_ is resolved to GUIDs — so deployedSha
- // must never be assumed equal to the source hash). For a non-nav page the deployed bytes ARE the
- // canonical file content.
- const deployedBytes = isNav ? deployment.get(key) : fs.readFileSync(canonicalPath(p), 'utf8');
- const codeFile = isNav ? writeStagingFile(stagingDir, key, deployment.get(key)) : canonicalPath(p);
- // `model` rides along because pac stores whatever `--model` an upload sends: re-uploading without it
- // wiped a deployed page's model id to "". A downloaded spec carries it (pages[].model).
- const up = await genpageCli.upload({ appId: result.created.app, pageId: requestedId, codeFile, name: p.name, prompt: p.prompt, agentMessage: p.agentMessage, dataSources: p.dataSources, model: p.model });
- if (!requestedId) recordCreate(p, up.pageId);
- // I7: an UPDATE (requestedId set) must return the SAME id, else a resolved sibling could point at
- // a stale target. Case-insensitive (Dataverse may echo a differently-cased GUID).
- if (requestedId && String(up.pageId).toLowerCase() !== String(requestedId).toLowerCase()) throw new BuildHalt(`page "${p.name}" UPDATE returned a different id (${up.pageId} != ${requestedId}) — refusing to finalize with an inconsistent target`, { phase: 'pages', code: 'pages-update-identity-mismatch', recoverable: false });
- // Key by the STABLE key (p.key||p.name): appDef resolves result.pages[s.page] where s.page is the
- // migrated KEY (:506). Keying by name left v2 key-referenced subareas unresolved.
- keyToId.set(key, up.pageId);
- result.created.pages[key] = up.pageId;
- result.created.pageDeployedShas[key] = sha256(deployedBytes);
- await persistNow(); // manifest carries this id BEFORE the next create (crash-safety, design §9 / C5)
- return up.pageId;
- });
+ if (selectedKeys && !selectedKeys.has(key)) return false;
+ return keyToId.has(key) && !mintedKeys.has(key);
+ }).map(keyOf));
+ let checkedBeforeWritingInPlace = false;
+ const updatedInPlace = new Map();
+ // The last scan: a page another app took in while the uploads ran has been written all the same, so it is reported, with the app it is
+ // in; one only SAVED there shows the new content once that app is published. It runs when the loop stops early too, since what it wrote
+ // before stopping is written. It never throws: the pages are written, nothing is left to refuse, and the halt that stopped the loop
+ // must reach the caller as it was.
+ const reportSharedAfterWrites = async () => {
+ if (!updatedInPlace.size) return;
+ const report = (message) => { if (typeof opts.warn === 'function') opts.warn(message); };
+ let checked;
+ try { checked = await scanShared(Array.from(updatedInPlace.keys())); } catch (e) { checked = { scan: { ok: false, error: String((e && e.message) || e) } }; }
+ const { scan, entries } = checked;
+ if (!entries) {
+ const why = !scan.ok ? scan.error : `${scan.unreadable.length} app(s) had an unreadable sitemap (${scan.unreadable.join(', ')})`;
+ report(`could not check again, once they were written, that the ${updatedInPlace.size} page(s) this build updated in place are not shared with another app: ${why}`);
+ return;
+ }
+ for (const s of entries) {
+ report(`generative page "${updatedInPlace.get(String(s.id).toLowerCase()) || s.id}" ${s.text} was taken into another app's navigation while this build was updating it, so its new content ${s.published ? 'shows there too' : 'will show there once that app is published'}. Detach it in Maker, or give this app its own page.`);
+ }
+ };
+ try {
+ for (const p of implemented) {
+ const key = keyOf(p);
+ if (selectedKeys && !selectedKeys.has(key)) { runner.skip('pages', `page "${p.name}" (unchanged — changed-only)`); continue; }
+ const isNav = (p.navigatesTo || []).length > 0;
+ if (!isNav && mintedKeys.has(key)) { runner.skip('pages', `page "${p.name}" (created)`); continue; }
+ // Taken here, ahead of the page's step rather than inside it, so a halt reaches the caller as raised: a scan that fails stays recoverable,
+ // as it is at the first scan, and the message is its own.
+ if (writesInPlace.has(key) && !checkedBeforeWritingInPlace) {
+ checkedBeforeWritingInPlace = true;
+ const shared = await sharedPagesNow(Array.from(writesInPlace, (k) => keyToId.get(k)));
+ if (shared.length) {
+ throw Object.assign(new BuildHalt(`generative page(s) became shared across apps while this build ran: ${shared.map((s) => s.text).join('; ')} — refusing to UPDATE a page another app's sitemap references (a rebuild would mutate shared content); no page this build began with has been updated in place. Detach it in Maker, or give this app its own page.`, { phase: 'pages', code: 'pages-shared-across-apps', recoverable: false }), { transient: false });
+ }
+ }
+ await runner.run('pages', `page "${p.name}"`, async () => {
+ const requestedId = keyToId.get(key);
+ // Capture the EXACT bytes we upload so the caller can record a MEASURED deployedSha (a nav source's
+ // deployed bytes differ from its canonical source — PAGEREF_ is resolved to GUIDs — so deployedSha
+ // must never be assumed equal to the source hash). For a non-nav page they are the bytes the scan read
+ // and checked, which its staging copy holds — not a new read of the canonical file, saved again maybe.
+ const deployedBytes = isNav ? deployment.get(key) : sourceByKey.get(key);
+ const codeFile = writeStagingFile(stagingDir, key, isNav ? deployment.get(key) : scannedBytes.get(key));
+ // `model` rides along because pac stores whatever `--model` an upload sends: re-uploading without it
+ // wiped a deployed page's model id to "". A downloaded spec carries it (pages[].model).
+ // `caller: 'build'` only words the advice for an UPDATE that timed out or failed (genpage-cli.js lookFirst): the build keeps no base marker, and every page's `codeFile` is a staging copy deleted when the build ends.
+ const up = await genpageCli.upload({ appId: result.created.app, pageId: requestedId, codeFile, name: p.name, prompt: p.prompt, agentMessage: p.agentMessage, dataSources: p.dataSources, model: p.model, caller: 'build' });
+ if (!requestedId) recordCreate(p, up.pageId);
+ // I7: an UPDATE (requestedId set) must return the SAME id, else a resolved sibling could point at
+ // a stale target. Case-insensitive (Dataverse may echo a differently-cased GUID).
+ if (requestedId && String(up.pageId).toLowerCase() !== String(requestedId).toLowerCase()) throw new BuildHalt(`page "${p.name}" UPDATE returned a different id (${up.pageId} != ${requestedId}) — refusing to finalize with an inconsistent target`, { phase: 'pages', code: 'pages-update-identity-mismatch', recoverable: false });
+ if (requestedId && writesInPlace.has(key)) updatedInPlace.set(String(requestedId).toLowerCase(), p.name);
+ // Key by the STABLE key (p.key||p.name): appDef resolves result.pages[s.page] where s.page is the
+ // migrated KEY (:506). Keying by name left v2 key-referenced subareas unresolved.
+ keyToId.set(key, up.pageId);
+ result.created.pages[key] = up.pageId;
+ result.created.pageDeployedShas[key] = sha256(deployedBytes);
+ // The source this send was judged on, which is the one the baseline records for the page (see `scannedSha`).
+ result.created.pageSourceShas[key] = scannedSha.get(key);
+ await persistNow(); // manifest carries this id BEFORE the next create (crash-safety, design §9 / C5)
+ return up.pageId;
+ });
+ }
+ } finally {
+ await reportSharedAfterWrites();
}
// (5) Persist the FINAL manifest (deduped no-op after per-create persists). Skipped for a page-less
@@ -5000,17 +6004,23 @@ async function runSdkBuildPhases(spec, opts, owed) {
// Features the SDK did not put in `applied`, deferred for a post-publish re-issue (see inside the
// ai-features phase for why the verdict cannot honestly be decided at write time).
const pendingAiReconfirm = [];
+ // Set by the publish phase when it published the app: an override the SDK saved in the app's unpublished layer
+ // (`pendingPublish`) is then in force, and only needs proving (8b), not writing again.
+ let appPublishedByPublishPhase = false;
if (has('ai-features') && specOptsIntoAi(spec)) {
const solutionUniqueName = spec.solution && spec.solution.uniqueName;
const appUnique = appUniqueName(spec);
const flags = resolveAiFlags(spec);
- // NOTE: this first write frequently NO-OPS. An app-scope setting write does nothing until the
- // app is published, and this phase runs moments after `app-shell` created it (the `publish`
- // phase is later, and is opt-in). It is still issued here so an ALREADY-published app — the
- // common case on a rebuild/edit — applies immediately and needs no retry. Anything it does not
- // apply is re-issued after publish by the block at the end of this function, which replicates
- // the fetch → publish → write sequence measured to work live.
+ // NOTE: an app-scope setting write lands in the app's UNPUBLISHED layer, and does nothing until the
+ // app is published. The SDK proves it where it is and reports it `applied` with `pendingPublish`
+ // (rebucketPendingPublish moves that to a bucket of its own; before the SDK could read that layer, the
+ // same write came back `notPersisted`). This phase runs moments after `app-shell` created the app, and
+ // the `publish` phase is later and opt-in — so what is not in force yet is put there after publish by
+ // the block at the end of this function: a saved override only needs the publish (which the publish
+ // phase has already done, when it ran) and is then PROVED, while one the SDK did not save at all is
+ // re-issued by the fetch → publish → write sequence measured to work live. An ALREADY-published app —
+ // the common case on a rebuild/edit — applies immediately and needs neither.
await runner.run('ai-features', 'enable app AI features', async () => {
// The SDK confirms each app-scope write by polling for its `appsettings` override row, keyed by
// appmoduleid. That id is normally resolved from the app's unique NAME — but a freshly created
@@ -5027,17 +6037,22 @@ async function runSdkBuildPhases(spec, opts, owed) {
// after the write (measured live), so the SDK's 4-attempt/500ms default is tight but the budget
// is only ever spent when the row is genuinely absent.
const encodedFlags = encodeAiFlags(flags);
- const r = rebucketNonEnablingSkips(await provision.setAppAiFeatures(appUnique, encodedFlags, {
+ const r = rebucketPendingPublish(rebucketNonEnablingSkips(await provision.setAppAiFeatures(appUnique, encodedFlags, {
solutionUniqueName,
appModuleId: result.created.app || undefined,
verifyAttempts: 8,
verifyDelayMs: 1000,
- }), encodedFlags);
+ }), encodedFlags));
result.created.ai.appFeatures = r;
// `applied` is the SDK's ONLY success bucket: a feature reaches it only when the APP-SCOPE
// override row is proven present holding the requested value. Every other bucket is a
// non-success the build must surface, because reporting them as plain success was the
// false-PASS half of ADO 6603383 (features were pushed onto `applied` while writing nothing):
+ // pendingPublish — the plugin's own bucket (rebucketPendingPublish): the SDK proved the row in
+ // the app's UNPUBLISHED layer, so it is saved and takes effect once the app is
+ // published. Deferred like the rest: the publish phase puts it in force when the
+ // build publishes, and otherwise the post-publish pass publishes the app — it is
+ // not written again, its row is already saved.
// notPersisted — the write returned 204 but no override was observed for the whole retry
// budget; Dataverse can accept an app-scope write and store nothing.
// skipped — as notPersisted, PLUS the feature's org readiness gate reads off, which is
@@ -5228,8 +6243,10 @@ async function runSdkBuildPhases(spec, opts, owed) {
// (created, then the add failed, then reused — a `!reused` gate would skip the repair forever).
// NOT swallowed: a real failure means the exported solution would omit the role and silently break
// access in the target env, so it fails the phase fail-closed — same as the app/sitemap adds.
+ // A role the SDK just created cannot be a member yet, so only a REUSED one consults the membership read.
if (sol && sol.uniqueName) {
- await provision.addSolutionComponent({ componentId: rr.roleId, componentType: COMPONENT_TYPE.role, solutionUniqueName: sol.uniqueName });
+ if (rr.reused) await ensureInSolution(rr.roleId, COMPONENT_TYPE.role);
+ else await provision.addSolutionComponent({ componentId: rr.roleId, componentType: COMPONENT_TYPE.role, solutionUniqueName: sol.uniqueName });
}
// Reconcile app availability to match `appAccess`: associate so the app appears for the persona
// (default), or DISSOCIATE when the persona opted out — otherwise a role flipped true->false would
@@ -5471,11 +6488,20 @@ async function runSdkBuildPhases(spec, opts, owed) {
}
// 8. Publish (opt-in). Publish ONE artifact per entity (covers that entity's customizations)
- // + the app — far fewer PublishXml round-trips than publishing every artifact.
- if (has('publish') && publish) {
+ // + the app — far fewer PublishXml round-trips than publishing every artifact. Every reconcile
+ // publish deferred to this phase (`publishInPhase8`) names its table in `owed.tables`, read below.
+ if (publishInPhase8) {
await runner.run('publish', 'publish customizations', async () => {
const seen = new Set();
- const perEntity = []; // [type, id] — first artifact found per entity
+ const perEntity = []; // [type, id, names?] — first artifact found per entity
+ // The table's target carries the names of what its one publish ships: what was deferred onto it (its reconciled views
+ // and forms, its enriched default views — oweTablePublish), then what this run created or wrote there (savedOnTable,
+ // sorted because artifacts are created concurrently), each name once. A failure of THIS publish then says which saved
+ // changes are not live — a first build's included — instead of naming only the artifact that carries the request.
+ const forTable = (k, [type, id]) => {
+ const names = [...new Set([...((owed.tables.get(k) || [])[2] || []), ...[...(savedOnTable.get(k) || [])].sort()])];
+ return names.length ? [type, id, names] : [type, id];
+ };
for (const f of spec.forms || []) {
const k = f.entity.toLowerCase();
// Prefer the entity's Main form (what `created.forms` holds), but fall back to THIS form's
@@ -5485,9 +6511,9 @@ async function runSdkBuildPhases(spec, opts, owed) {
// restriction would silently not take effect. Publishing is per-ENTITY, so any one of its
// forms covers the rest.
const id = result.created.forms[k] || result.created.formIds[formIdentityKey(f)];
- if (id && !seen.has(k)) { seen.add(k); perEntity.push(['form', id]); }
+ if (id && !seen.has(k)) { seen.add(k); perEntity.push(forTable(k, ['form', id])); }
}
- for (const v of spec.views || []) { const k = v.entity.toLowerCase(); const vid = result.created.views[`${k}|${v.name}`]; if (vid && !seen.has(k)) { seen.add(k); perEntity.push(['view', vid]); } }
+ for (const v of spec.views || []) { const k = v.entity.toLowerCase(); const vid = result.created.views[`${k}|${v.name}`]; if (vid && !seen.has(k)) { seen.add(k); perEntity.push(forTable(k, ['view', vid])); } }
// Charts too — but ONLY the ones this run created or fetched. `publishArtifact` requires the
// artifact to be workspace-resident (readRaw -> readLocal throws ArtifactNotFoundError rather
// than lazily fetching), and `findArtifact` does not populate the workspace. Deriving the id
@@ -5495,11 +6521,13 @@ async function runSdkBuildPhases(spec, opts, owed) {
// existing chart with no description to reconcile, and the throw escapes publishArtifact and
// halts the phase. `chartsToPublish` is populated at exactly the two points that put a chart in
// the workspace, and keyed by entity because publishing is per-entity.
- for (const [k, cid] of chartsToPublish) { if (cid && !seen.has(k)) { seen.add(k); perEntity.push(['chart', cid]); } }
- // Tables whose enriched default views still owe their publish (4b), when nothing above names them.
- for (const [k, target] of owed.tables) { if (!seen.has(k)) { seen.add(k); perEntity.push(target); } }
+ for (const [k, cid] of chartsToPublish) { if (cid && !seen.has(k)) { seen.add(k); perEntity.push(forTable(k, ['chart', cid])); } }
+ // Tables whose publish was deferred to this phase — the enriched default views (4b) and the existing
+ // views and forms the reconcile paths touched — when nothing above names them.
+ for (const [k, target] of owed.tables) { if (!seen.has(k)) { seen.add(k); perEntity.push(forTable(k, target)); } }
const appTarget = result.created.app ? ['app', result.created.app, `app ${(spec.app && spec.app.name) || result.created.app}`] : null;
- await publishTargets(provision, runner, concurrency, perEntity, appTarget, opts.warn);
+ const publishedTargets = await publishTargets(provision, runner, concurrency, perEntity, appTarget, opts.warn);
+ appPublishedByPublishPhase = publishedTargets.appPublished;
});
// Paid. A target that failed to publish was reported above, and the build is idempotent, so its
// re-run publishes it; a halt from here on owes nothing more, nor does an earlier attempt's.
@@ -5507,13 +6535,19 @@ async function runSdkBuildPhases(spec, opts, owed) {
owed.tables.clear();
}
- // 8b. AI feature re-issue + re-confirmation. An app-scope setting write is a NO-OP on a freshly
- // created app: measured live on two different apps, the write returned `notPersisted` and a
- // direct `appsettings` query showed no override row at ALL, while fetching + publishing that
- // same app and re-issuing the identical call produced every feature `applied` with real rows
- // holding the requested values. So this pass RE-ISSUES the write (re-proving alone cannot help
- // — there is nothing to find), then falls back to proving the override row for anything the
- // retry still did not claim. It can only ever UPGRADE a feature, never hide a real failure.
+ // 8b. AI feature re-issue + re-confirmation. An app-scope setting write lands in the app's UNPUBLISHED
+ // layer, which the published `appsettings` projection cannot show: measured live on two different
+ // apps, the write used to come back `notPersisted` with no override row at ALL, while fetching +
+ // publishing that same app and re-issuing the identical call produced every feature `applied` with
+ // real rows holding the requested values. The SDK now reads the unpublished layer and calls a
+ // saved-but-unpublished feature `applied` with `pendingPublish`; rebucketPendingPublish files it as
+ // the plugin's own `pendingPublish` bucket, because it is not in force until a publish. Such a
+ // feature needs the PUBLISH, not a second write, so it is published here unless the publish phase
+ // already did that. Anything the SDK did not save at all is RE-ISSUED after the publish, as before.
+ // Then the override row is PROVED for whatever is left. A re-issue's own `pendingPublish` is filed
+ // the same way: a publish that failed, or could not be confirmed, leaves the row in the unpublished
+ // layer, and that is not "applied". This pass can only ever UPGRADE a feature, never hide a real
+ // failure.
if (pendingAiReconfirm.length) {
const flags = resolveAiFlags(spec);
const appUnique = appUniqueName(spec);
@@ -5526,31 +6560,56 @@ async function runSdkBuildPhases(spec, opts, owed) {
skipped: ['ADMIN GATE OFF', 'the write was issued, no app-scope override appeared, and the feature\u2019s org readiness gate reads off \u2014 an environment admin must enable it first'],
unverified: ['UNVERIFIED', 'the write was issued but could not be confirmed \u2014 verify manually before relying on it'],
failed: ['FAILED', 'the write threw'],
+ // The SDK proved the row, in the app's unpublished layer; this is what is left to say when no publish
+ // has since put it in force (or its publish could not be confirmed by reading the row back).
+ pendingPublish: ['NOT YET PUBLISHED', 'the override is saved but not in force: it takes effect once the app is published, and the published row could not be read back'],
};
// Replicate the sequence proven to work live, in order: fetch the app (so the workspace holds the
// server's copy), publish it, then write. Each step is best-effort — a failure here must not fail
// the build, it just leaves the original non-success verdict standing and reported.
+ //
+ // A feature the SDK SAVED but flagged `pendingPublish` is not written again: its row is already in the
+ // unpublished layer, so a second write would only save it again. It needs the publish — and not even that
+ // when the publish phase has published the app this run. The proof below reads the row where the runtime
+ // does, so whatever the publish did not put in force is reported, never claimed.
const retryApplied = new Set();
+ // Features whose re-issue the SDK saved in the unpublished layer only, with its reason for saying so.
+ const retryPending = new Map();
if (result.created.app) {
const retryFlags = {};
- for (const p of pendingAiReconfirm) if (flags && Object.prototype.hasOwnProperty.call(flags, p.feature)) retryFlags[p.feature] = flags[p.feature];
- if (Object.keys(retryFlags).length) {
+ let owesPublish = false;
+ for (const p of pendingAiReconfirm) {
+ if (p.bucket === 'pendingPublish') {
+ if (!appPublishedByPublishPhase) owesPublish = true;
+ continue;
+ }
+ if (flags && Object.prototype.hasOwnProperty.call(flags, p.feature)) retryFlags[p.feature] = flags[p.feature];
+ }
+ const rewrite = Object.keys(retryFlags).length > 0;
+ if (rewrite || owesPublish) {
try {
await provision.fetchArtifact('app', result.created.app);
reportPartialPush(await provision.publishArtifact('app', result.created.app), `app ${(spec.app && spec.app.name) || result.created.app}`, opts.warn);
- const retry = await provision.setAppAiFeatures(appUnique, encodeAiFlags(retryFlags), {
- solutionUniqueName: spec.solution && spec.solution.uniqueName,
- appModuleId: result.created.app,
- verifyAttempts: 6,
- verifyDelayMs: 1000,
- });
- for (const f of (retry && retry.applied) || []) retryApplied.add(f);
+ if (rewrite) {
+ // Filed like the first write: after a publish that failed or could not be confirmed, the SDK proves
+ // this write only in the unpublished layer and answers `applied` + `pendingPublish`.
+ const retry = rebucketPendingPublish(await provision.setAppAiFeatures(appUnique, encodeAiFlags(retryFlags), {
+ solutionUniqueName: spec.solution && spec.solution.uniqueName,
+ appModuleId: result.created.app,
+ verifyAttempts: 6,
+ verifyDelayMs: 1000,
+ }));
+ for (const f of (retry && retry.applied) || []) retryApplied.add(f);
+ for (const o of (retry && retry.outcomes) || []) if (o && o.status === 'pendingPublish') retryPending.set(o.feature, o.reason);
+ }
} catch { /* leave the original verdict standing; it is reported below */ }
}
}
const app = await resolveAppModuleId(provision, appUnique);
const stillBad = [];
const reproven = [];
+ // Saved in the unpublished layer by the re-issue though the first write said otherwise (`notPersisted`, say).
+ const movedToPending = [];
// Track HOW each feature was recovered so the reported reason is true for that path. Claiming a
// re-issue applied something the proof merely found is the same "report what you did not verify"
// failure this whole phase exists to remove.
@@ -5563,16 +6622,25 @@ async function runSdkBuildPhases(spec, opts, owed) {
}
const setting = AI_APP_SETTING[p.feature];
let proof = { error: app.error };
- if (!app.error && setting) proof = await proveAppOverride(provision, app.appModuleId, setting);
+ // The same reads, as many and as far apart, as `--verify` makes (proofBudget): the publish can answer before the
+ // published row is readable, and a single read reported that lag as NOT YET PUBLISHED in a run whose own verify passed.
+ if (!app.error && setting) proof = await proveAppOverride(provision, app.appModuleId, setting, proofBudget(opts));
if (!proof.error && proof.exists && sameSettingValue(proof.value, featureWantValue(flags && flags[p.feature], p.feature), p.feature)) {
reproven.push(p.feature);
reprovenBy.set(p.feature, 'confirmed present after publish by the build\u2019s own override-row proof');
continue;
}
- const [label, why] = BUCKET_LABELS[p.bucket] || [String(p.bucket).toUpperCase(), 'reported by the SDK as a non-success outcome'];
- // Prefer the SDK's OWN per-feature reason: it carries the real error text for `failed`, which
- // a canned bucket description throws away.
- stillBad.push({ feature: p.feature, label, why: p.reason || proof.error || why });
+ // What the re-issue found supersedes what the first write said: the row IS saved, it is just not in force.
+ const savedUnpublished = retryPending.has(p.feature);
+ const bucket = savedUnpublished ? 'pendingPublish' : p.bucket;
+ if (savedUnpublished && p.bucket !== 'pendingPublish') movedToPending.push(p.feature);
+ const [label, why] = BUCKET_LABELS[bucket] || [String(bucket).toUpperCase(), 'reported by the SDK as a non-success outcome'];
+ // A check that could not run says so FIRST: the verdict that stands is then the one from before it, and a reader who
+ // sees only that verdict takes the check for having looked. What the SDK said (prefer its OWN per-feature reason: it
+ // carries the real error text for `failed`, which a canned bucket description throws away) follows it.
+ const said = savedUnpublished ? retryPending.get(p.feature) : p.reason;
+ const checkFailed = proof.error ? `the check after the publish could not run: ${proof.error}` : null;
+ stillBad.push({ feature: p.feature, label, why: [checkFailed, said].filter(Boolean).join(' \u2014 ') || why });
}
// Reflect the corrected verdict in the machine-readable result too, so a caller reading
// `created.ai.appFeatures` is not told a feature failed when it demonstrably did not.
@@ -5585,7 +6653,14 @@ async function runSdkBuildPhases(spec, opts, owed) {
// move from `skipped` to `applied`, and leaving it listed in both would make
// `created.ai.appFeatures` contradict itself for any `--json` consumer.
for (const key of Object.keys(af)) if (Array.isArray(af[key]) && key !== 'applied' && key !== 'outcomes') af[key] = af[key].filter((f) => !reproven.includes(f));
- for (const o of af.outcomes || []) if (reproven.includes(o.feature)) { o.status = 'applied'; o.appOverrideExists = true; o.reason = reprovenBy.get(o.feature); }
+ for (const o of af.outcomes || []) if (reproven.includes(o.feature)) { o.status = 'applied'; o.appOverrideExists = true; o.reason = reprovenBy.get(o.feature); delete o.pendingPublish; }
+ }
+ // ...and the same for a feature the re-issue saved but could not put in force: it leaves the bucket the first
+ // write put it in, for `pendingPublish`, so the result says what the warning below does.
+ if (af && movedToPending.length) {
+ for (const key of Object.keys(af)) if (Array.isArray(af[key]) && key !== 'applied' && key !== 'outcomes') af[key] = af[key].filter((f) => !movedToPending.includes(f));
+ af.pendingPublish = [...(af.pendingPublish || []), ...movedToPending];
+ for (const o of af.outcomes || []) if (movedToPending.includes(o.feature)) { o.status = 'pendingPublish'; o.appOverrideExists = true; o.pendingPublish = true; o.reason = retryPending.get(o.feature); }
}
// `runner.skip` renders as `⊘ <label>` — the closest thing the narrator has to a warning — and
// advances the step counter correctly, which a hand-built `runner.emit` did not.
@@ -5600,4 +6675,4 @@ async function runSdkBuildPhases(spec, opts, owed) {
return result;
}
-module.exports = { runSdkBuild, publishTargets, partialEnrichment, settleOwedPublishes, normalizeFormId, planFor, annotateLivePlan, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, findPinnedDashboard, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, applyAppAiDescription, haltOnUnpublishedAppHeader, pushAppHeader, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, bpfDef, bpfFilter, webResourceOpts, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause, roleGrantLabel, resolveRoleGrantTarget };
+module.exports = { runSdkBuild, publishTargets, partialEnrichment, settleOwedPublishes, collectOwedPublishes, normalizeFormId, planFor, annotateLivePlan, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, findPinnedDashboard, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, applyAppAiDescription, haltOnUnpublishedAppHeader, pushAppHeader, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, bpfDef, bpfFilter, webResourceOpts, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause, roleGrantLabel, resolveRoleGrantTarget };
diff --git a/plugins/model-apps/scripts/lib/sdk-http-client.js b/plugins/model-apps/scripts/lib/sdk-http-client.js
index e5a4acb8d..e5af02959 100644
--- a/plugins/model-apps/scripts/lib/sdk-http-client.js
+++ b/plugins/model-apps/scripts/lib/sdk-http-client.js
@@ -17,7 +17,24 @@ const { dataverseOrigin, getAuthToken, makeRequest, tokenFailureMessage } = requ
// HTTP 500 from …/api/data/v9.0/workflows(<id>): Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205
// {"error":{"code":"0x80044150","message":" Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205"}}
// Only the SQL number identifies it; the code and message text are shared with every other SQL error.
-// The vendored SDK recognizes the same marker for its own re-send of reads, app creates and PublishXml.
+// The vendored SDK recognizes the same marker for its own re-send (1 s / 2 s / 4 s) of reads, an app create,
+// PublishXml, a form create, a view create and a publisher create — requests this client has already re-sent by
+// then, because it re-sends every 5xx that is not a record delete or a $batch (TRANSIENT, below). So a deadlock the
+// client clears costs one re-send in all and the SDK's never fires; one that never clears is attempted up to the
+// client's six times per SDK attempt (24 in all, measured on a form create and on a view create), a ceiling on a
+// pathological case. A record DELETE and a conditional-delete $batch are the exception: this client re-sends their
+// deadlocks itself (below), and the SDK re-sends an app delete only for a different answer — the platform's
+// search-index race (HTTP 400, SQL 547) — so the two never act on the same one. The deletes of a row-summary
+// removal are the one record delete whose deadlock the SDK re-sends as well (a 500 carrying SQL 1205, or a 400
+// quoting SQL's "chosen as the deadlock victim"): a 500 is re-sent by this client first, so one that clears costs
+// one re-send in all and one that never clears at most 16 attempts (this client's four per SDK attempt). All of it
+// is pinned against the real bundle in sdk-resend-layers.test.js.
+//
+// The one other `$batch` this client sends again is a change set that only CREATES columns (a new table's ordinary columns, see
+// isColumnCreateBatch), and only after a 429: the platform refused to start it, so nothing in it committed (a change set is
+// atomic) and it goes out again on the throttle schedule. After any other answer, a deadlock included, it is sent once, because a
+// change set can commit behind a lost or failed answer; the SDK has no re-send of its own for it, so the layers never multiply
+// here either. Pinned through the real client and bundle in table-columns-in-create.test.js and in sdk-http-client.test.js.
const SQL_DEADLOCK_VICTIM = /\bSql Number:\s*1205\b/i;
// At most this many re-sends of a deadlock victim, 1 s / 2 s / 4 s apart — the SDK's own schedule.
const DEADLOCK_RESENDS = 3;
@@ -56,6 +73,28 @@ function isSqlDeadlockVictim(res) {
return SQL_DEADLOCK_VICTIM.test(typeof res.body === 'string' ? res.body : JSON.stringify(res.body));
}
+/**
+ * The operations a `$batch` REQUEST carries, as `{ method, url, ifMatch }` in the order sent, read from the request lines
+ * (`<METHOD> <url> HTTP/1.1`) the SDK renders — see isConditionalDeleteBatch and isColumnCreateBatch for the shapes. `ifMatch` is the
+ * operation's own `If-Match` header when it has one. A body that is not text carries none.
+ */
+function batchOperations(body) {
+ if (typeof body !== 'string') return [];
+ const lines = body.split(/\r?\n/);
+ const ops = [];
+ for (let i = 0; i < lines.length; i += 1) {
+ const request = /^([A-Z]+) (\S+) HTTP\/1\.1$/.exec(lines[i]);
+ if (!request) continue;
+ let ifMatch;
+ for (let j = i + 1; j < lines.length && lines[j] !== ''; j += 1) {
+ const m = /^If-Match:\s*(\S.*?)\s*$/i.exec(lines[j]);
+ if (m) ifMatch = m[1];
+ }
+ ops.push({ method: request[1], url: request[2], ifMatch });
+ }
+ return ops;
+}
+
/**
* True when a `$batch` REQUEST may be sent again after a proven rollback: every operation in it is a
* DELETE conditioned on the exact row version its caller read. That is the vendored SDK's atomic app
@@ -73,28 +112,48 @@ function isSqlDeadlockVictim(res) {
* --changeset_<id>--
* --batch_<id>--
* A second send of such a batch meets the rows exactly as the first did, or is refused with 412: it cannot
- * remove anything its caller did not read. No other batch qualifies. Notably the SDK updates a generative
+ * remove anything its caller did not read. No other batch qualifies, bar the column creates of
+ * isColumnCreateBatch (after a 429 only). Notably the SDK updates a generative
* page's files in a batch of `If-Match: *` writes after checking their versions itself; sent again after
* a backoff, that batch would skip the check and overwrite another maker's edit. An unconditional DELETE
* does not qualify either (the SDK's create rollback sends those; it is sent once, as before).
*/
function isConditionalDeleteBatch(body) {
- if (typeof body !== 'string') return false;
- const lines = body.split(/\r?\n/);
- const ops = [];
- for (let i = 0; i < lines.length; i += 1) {
- const request = /^([A-Z]+) \S+ HTTP\/1\.1$/.exec(lines[i]);
- if (!request) continue;
- let ifMatch;
- for (let j = i + 1; j < lines.length && lines[j] !== ''; j += 1) {
- const m = /^If-Match:\s*(\S.*?)\s*$/i.exec(lines[j]);
- if (m) ifMatch = m[1];
- }
- ops.push({ method: request[1], ifMatch });
- }
+ const ops = batchOperations(body);
return ops.length > 0 && ops.every((op) => op.method === 'DELETE' && op.ifMatch && op.ifMatch !== '*');
}
+// The collection a column is created in: `…/EntityDefinitions(LogicalName='new_ticket')/Attributes`.
+const COLUMN_COLLECTION_URL = /\/EntityDefinitions\([^)]*\)\/Attributes$/;
+
+/**
+ * True when a `$batch` REQUEST only CREATES columns: every operation is a POST to a table's `Attributes` collection. That is the
+ * vendored SDK's createColumns, the ordinary columns of a new table in one change set (abridged):
+ * --batch_<id>
+ * Content-Type: multipart/mixed;boundary=changeset_<id>
+ *
+ * --changeset_<id>
+ * Content-Type: application/http
+ * Content-ID: 1
+ *
+ * POST https://contoso.crm.dynamics.com/api/data/v9.0/EntityDefinitions(LogicalName='new_ticket')/Attributes HTTP/1.1
+ * Content-Type: application/json;type=entry
+ * MSCRM.SolutionUniqueName: <solution>
+ *
+ * {"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",...}
+ * --changeset_<id>--
+ * --batch_<id>--
+ * It carries no delete and no write conditioned on a row version, so — unlike every other batch — a second send after an answer that
+ * proves nothing in it committed (HTTP 429, see isBatchThrottled; a change set is atomic) cannot remove or overwrite anything. The worst a second send can meet is
+ * a column that is already there, which the platform refuses whole ("already exists", 0x80060304); the caller falls back to one
+ * request per column, where an existing column is skipped. Sent once after any other answer, as before: a change set can commit
+ * behind a lost answer.
+ */
+function isColumnCreateBatch(body) {
+ const ops = batchOperations(body);
+ return ops.length > 0 && ops.every((op) => op.method === 'POST' && COLUMN_COLLECTION_URL.test(op.url));
+}
+
/**
* True when a `$batch` ANSWER proves nothing in it committed, because SQL rolled every operation back as a
* deadlock victim. A change set is atomic: when an operation in it fails, the whole set is rolled back and
@@ -151,7 +210,8 @@ function batchResults(res) {
}
/**
- * True when a `$batch` ANSWER proves the server refused to START it (HTTP 429), so nothing in it ran.
+ * True when a `$batch` ANSWER proves the server refused it (HTTP 429), so nothing in it committed. A plain 429 means no operation
+ * was even read; in a change set, which is atomic, an operation refused with a 429 takes the operations before it with it.
* Two shapes qualify:
* - the whole request refused before any operation was read: a plain error answer with status 429, not
* a multipart one — service protection limits answer this way, e.g.
@@ -306,8 +366,9 @@ function createAzHttpClient(orgUrl, deps = {}) {
// its sitemap in one atomic change set), so it inherits the record-delete hazard above. It is
// also ambiguous on failure: the server may have committed while the response was lost, so a
// blind re-issue is exactly the racing retry that wedges the row. Issue it once and let the
- // SDK surface the unknown outcome to the caller — unless it is a batch of conditional deletes and
- // its answer proves no operation in it ran (see the re-sends below).
+ // SDK surface the unknown outcome to the caller — unless its answer proves no operation in it ran,
+ // and it is a batch of conditional deletes or, for a 429 only, one of column creates (see the
+ // re-sends below).
const method_ = String(method).toUpperCase();
const isMetadataDelete = /\/(EntityDefinitions|RelationshipDefinitions|GlobalOptionSetDefinitions)\b/i.test(url);
const isBatch = method_ === 'POST' && /\/\$batch(\?|$)/i.test(url);
@@ -385,9 +446,14 @@ function createAzHttpClient(orgUrl, deps = {}) {
// process-flow delete failed exactly this way, and so did a teardown's app delete — a change set —
// which stopped the whole teardown with nothing removed; both were clean on a re-run.
// A batch is re-sent only when it is made of conditional deletes (isConditionalDeleteBatch) and its
- // answer shows that no operation in it ran (isBatchThrottled, isBatchDeadlockVictim).
+ // answer shows that no operation in it ran (isBatchThrottled, isBatchDeadlockVictim) — or when it only
+ // creates columns (isColumnCreateBatch) and the answer is a 429 (isBatchThrottled). That change set
+ // follows the create of its table, and a table's customization lock can stay held for ~20 s behind
+ // that (see maxAttempts): one column's own POST rides it out on this schedule, so the change set that
+ // replaces a column's POST gets the same treatment instead of a refusal the caller has to work around.
const conditionalDeleteBatch = isBatch && isConditionalDeleteBatch(bodyStr);
- const throttled = (recordDelete && res.statusCode === 429) || (conditionalDeleteBatch && isBatchThrottled(res));
+ const columnCreateBatch = isBatch && isColumnCreateBatch(bodyStr);
+ const throttled = (recordDelete && res.statusCode === 429) || ((conditionalDeleteBatch || columnCreateBatch) && isBatchThrottled(res));
if (throttled && !last) {
// 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));
@@ -428,4 +494,4 @@ function createAzHttpClient(orgUrl, deps = {}) {
};
}
-module.exports = { createAzHttpClient, SQL_DEADLOCK_VICTIM, isBatchDeadlockVictim, isBatchThrottled, batchRetryAfterMs, isConditionalDeleteBatch, retryAfterMs, RETRY_AFTER_CAP_MS };
+module.exports = { createAzHttpClient, SQL_DEADLOCK_VICTIM, isBatchDeadlockVictim, isBatchThrottled, batchRetryAfterMs, isConditionalDeleteBatch, isColumnCreateBatch, retryAfterMs, RETRY_AFTER_CAP_MS };
diff --git a/plugins/model-apps/scripts/lib/sdk-teardown.js b/plugins/model-apps/scripts/lib/sdk-teardown.js
index c153bf08b..71bb22cbd 100644
--- a/plugins/model-apps/scripts/lib/sdk-teardown.js
+++ b/plugins/model-apps/scripts/lib/sdk-teardown.js
@@ -54,7 +54,7 @@
// the identical phase-grouped, status-marked log.
const { topoOrderEntities } = require('./_graph.js');
-const { appUniqueName, commandsByEntity, defaultViewColumns, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, findPinnedDashboard, resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, bpfFilter } = require('./sdk-build.js');
+const { appUniqueName, commandsByEntity, defaultViewColumns, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, findPinnedDashboard, resolveExistingFormId, resolveRoleBusinessUnit, roleBuClause, bpfFilter, partialEnrichment } = require('./sdk-build.js');
const { manifestResourceName, parseManifestBase64 } = require('./page-manifest.js');
const { relationshipSchemaName, manyToManySchemaName, lookupColumnsFor, SDK_ROLE_MARKER, canonicalPersonaName, FORM_GUID_RE } = require('./app-spec.js');
const { selectSummaryTables } = require('./ai-candidates.js');
@@ -116,6 +116,80 @@ function isUndeletable(err) {
// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/dependency
const DEPENDENT_COMPONENT_LABELS = { 1: 'table', 2: 'column', 10: 'relationship', 26: 'view', 59: 'chart', 60: 'form' };
+function canBatchResetDefaultViewPublishes(sdk) {
+ return typeof (sdk && sdk.publishArtifacts) === 'function'
+ && typeof (sdk && sdk.publishArtifact) === 'function'
+ && typeof (sdk && sdk.enrichDefaultViews) === 'function';
+}
+
+function recordDeferredResetPublish(ctx, logical, record) {
+ if (!ctx || !record) return;
+ for (const pending of record.pendingPublish || []) {
+ const first = (pending.artifacts || [])[0];
+ if (!first || !first.id || ctx.owedByTable.has(logical)) continue;
+ ctx.owedByTable.set(logical, { table: logical, type: first.type || 'view', id: first.id });
+ }
+}
+
+function warnDeferredResetPublishFailure(ctx, table, err) {
+ if (!ctx) return;
+ const message = `default-view reset for ${table} is saved but may still be unpublished: ${errMsg(err)} — `
+ + 'the next relationship delete may still report the lookup as still referenced until that table publishes';
+ ctx.warnings.push(message);
+ if (typeof ctx.warn === 'function') ctx.warn(message);
+}
+
+function publishFailure(outcome) {
+ return outcome && outcome.publish && outcome.publish.kind === 'failed'
+ ? (outcome.publish.error || new Error('publish failed'))
+ : null;
+}
+
+// The reset step exists only so relationship deletes stop seeing those lookups on the built-in
+// default views. Saving the reset is not enough: until Dataverse publishes the table, the
+// relationship delete can still report the lookup as referenced. So every reset defers its publish
+// and this barrier pays that debt ONCE, after the last reset and before the first relationship
+// delete. One target still uses publishArtifact (request-for-request unchanged); several use the
+// SDK's publishArtifacts envelope and retry each failed target on its own, which the SDK README
+// prescribes because a shared failure can still have published some scopes.
+async function settleDeferredResetPublishes(sdk, ctx) {
+ if (!ctx || ctx.flushing || !ctx.owedByTable.size || typeof (sdk && sdk.publishArtifact) !== 'function') return;
+ ctx.flushing = true;
+ try {
+ const owed = [...ctx.owedByTable.values()];
+ ctx.owedByTable.clear();
+ const publishOne = async (target) => {
+ try {
+ const failed = publishFailure(await sdk.publishArtifact(target.type, target.id));
+ if (failed) warnDeferredResetPublishFailure(ctx, target.table, failed);
+ } catch (err) {
+ warnDeferredResetPublishFailure(ctx, target.table, err);
+ }
+ };
+ if (owed.length === 1 || typeof (sdk && sdk.publishArtifacts) !== 'function') {
+ for (const target of owed) await publishOne(target);
+ return;
+ }
+ let outcomes = null;
+ try {
+ outcomes = await sdk.publishArtifacts(owed.map((target) => ({ type: target.type, id: target.id })));
+ } catch {
+ outcomes = null;
+ }
+ const retry = [];
+ if (Array.isArray(outcomes) && outcomes.length === owed.length) {
+ outcomes.forEach((outcome, i) => {
+ if (outcome && outcome.publish && outcome.publish.kind === 'failed') retry.push(owed[i]);
+ });
+ } else {
+ retry.push(...owed);
+ }
+ for (const target of retry) await publishOne(target);
+ } finally {
+ ctx.flushing = false;
+ }
+}
+
// Turn a blocked relationship delete into something an operator can act on.
//
// Dataverse refuses with a COUNT and no identities, e.g.:
@@ -871,9 +945,19 @@ const KIND_HANDLERS = {
async resolve(sdk, target) {
return [{ id: target.entityLogical, cols: target.cols }];
},
- async del(sdk, item) {
+ async del(sdk, item, ctx) {
if (typeof sdk.enrichDefaultViews === 'function') {
- try { await sdk.enrichDefaultViews(item.id, item.cols); } catch { /* best-effort — a reset that fails just leaves the surfacing lookup, which the delete will then report */ }
+ if (!ctx || !ctx.deferPublish) {
+ try { await sdk.enrichDefaultViews(item.id, item.cols); } catch { /* best-effort — a reset that fails just leaves the surfacing lookup, which the delete will then report */ }
+ return;
+ }
+ try {
+ recordDeferredResetPublish(ctx, item.id, await sdk.enrichDefaultViews(item.id, item.cols, { publish: false }));
+ } catch (err) {
+ recordDeferredResetPublish(ctx, item.id, partialEnrichment(err));
+ // Best-effort exactly as before: a reset failure is swallowed, because the relationship
+ // delete that follows is what reports the actionable leftover.
+ }
}
},
},
@@ -1271,12 +1355,12 @@ function planTeardown(spec) {
// Reporting both as "undeletable" would send an operator hunting a platform problem that isn't
// there. `skippedIds` is retained as the union of both for callers that only need the count.
// A not-found error counts as already-gone. Throws only on a genuine failure.
-async function deleteStep(sdk, handler, items) {
+async function deleteStep(sdk, handler, items, ctx) {
const deletedIds = [];
const skipped = [];
for (const item of items) {
try {
- await handler.del(sdk, item);
+ await handler.del(sdk, item, ctx);
deletedIds.push(item.id);
} catch (err) {
if (handler.tolerateNotFound && isNotFound(err)) {
@@ -1322,8 +1406,31 @@ async function deleteStep(sdk, handler, items) {
// Execute a teardown. Dry-run discovers page candidates when an SDK reader is supplied, without writes.
// Apply resolves each step's live id(s) and deletes them, emitting per-step status. Best-effort:
// a failed step is recorded and teardown CONTINUES (halting mid-way would strand orphans), then
-// ok=false with an `errors[]` is returned. deps: { sdk (MakerSdk client), emit(event) }.
+// ok=false with an `errors[]` is returned. deps: { sdk (MakerSdk client), emit(event), warn(message) }.
+//
+// `warn` hears (and `result.warnings` lists, when there are any) the default-view resets whose publish
+// could not be confirmed. This wrapper exists so the batched publish of those resets is settled however
+// the steps end — normally, through the app-delete stop, or because a callback threw — without wrapping
+// the step loop (and re-indenting every line of it) in a try/finally.
async function runTeardown(spec, opts = {}, deps = {}) {
+ const deferredResetPublishes = {
+ deferPublish: canBatchResetDefaultViewPublishes(deps.sdk),
+ owedByTable: new Map(),
+ warnings: [],
+ warn: deps.warn,
+ flushing: false,
+ };
+ let result;
+ try {
+ result = await runTeardownSteps(spec, opts, deps, deferredResetPublishes);
+ return result;
+ } finally {
+ await settleDeferredResetPublishes(deps.sdk, deferredResetPublishes);
+ if (deferredResetPublishes.warnings.length && result) result.warnings = deferredResetPublishes.warnings;
+ }
+}
+
+async function runTeardownSteps(spec, opts, deps, deferredResetPublishes) {
const emit = deps.emit || (() => undefined);
const sdk = deps.sdk;
const apply = opts.apply === true;
@@ -1402,6 +1509,9 @@ async function runTeardown(spec, opts = {}, deps = {}) {
let n = 0;
for (const step of plan) {
const myN = (n += 1);
+ // The barrier for the batched default-view resets: nothing past the resets may run before they are
+ // published (the relationship deletes that follow them are what the resets unblock).
+ if (step.kind !== 'resetDefaultViews') await settleDeferredResetPublishes(sdk, deferredResetPublishes);
emit({ phase: step.phase, status: 'start', label: step.label, n: myN, total });
if (step.kind === 'webResource' && pagesFailed && pageManifests.has(String(step.target.name).toLowerCase())) {
const why = `${step.label} (kept — the generative pages step failed, and a re-run needs this manifest to find remaining page candidates; it is deleted once that step succeeds)`;
@@ -1460,7 +1570,7 @@ async function runTeardown(spec, opts = {}, deps = {}) {
emit({ phase: step.phase, status: 'skip', skip: skipReason ? 'kept' : 'not-found', label: `${step.label} (${skipReason || 'not found'})`, n: myN, total });
continue;
}
- const { deletedIds, skipped } = await deleteStep(sdk, handler, items);
+ const { deletedIds, skipped } = await deleteStep(sdk, handler, items, step.kind === 'resetDefaultViews' ? deferredResetPublishes : undefined);
(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/sitemap-pages.js b/plugins/model-apps/scripts/lib/sitemap-pages.js
index cded3e0e9..ec68088f8 100644
--- a/plugins/model-apps/scripts/lib/sitemap-pages.js
+++ b/plugins/model-apps/scripts/lib/sitemap-pages.js
@@ -7,7 +7,7 @@
// existence check — a page can exist env-wide yet not be in this app's sitemap (see genpage-cli.enumerateEnv).
const { odataLit } = require('./odata.js');
-const { appComponentRows, currentAppLayer } = require('./app-components.js');
+const { appComponentRows, currentAppLayer, collectionRows, currentLayerRows } = require('./app-components.js');
const { subAreaTargetKey } = require('./sitemap-merge.js');
// Match a <SubArea …> START TAG carrying a GenPageId, capturing the id and (optionally) the Title.
@@ -165,7 +165,7 @@ function isMalformed(xml) {
//
// componenttype 62 == sitemap:
// https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/appmodulecomponent
-async function fetchSitemap(sdk, appUnique, { currentLayer } = {}) {
+async function fetchSitemap(sdk, appUnique, { currentLayer, includeSitemapId } = {}) {
let app;
if (currentLayer !== undefined) {
// Download supplies the SAME current layer as its table/form inventory. Default callers
@@ -207,10 +207,7 @@ async function fetchSitemap(sdk, appUnique, { currentLayer } = {}) {
if (!response || response.status < 200 || response.status >= 300) throw new Error(`current sitemap read returned HTTP ${response && response.status}`);
const rows = response.body && response.body.value;
if (!Array.isArray(rows)) throw new Error('current sitemap read returned no readable result set');
- // A projection can return { value: [{ componentstate: 0, sitemapxml: "old" },
- // { componentstate: 1, sitemapxml: "draft" }] }; only the authored row is current.
- sms = rows.length <= 1 ? rows : rows.filter((row) => row && Number(row.componentstate) === 1);
- if (sms.length > 1 || (rows.length > 1 && sms.length !== 1)) throw new Error('current sitemap read returned no single current row');
+ sms = currentSitemapRows(rows);
} else {
sms = await sdk.queryRecords('sitemap', {
select: ['sitemapxml'],
@@ -230,7 +227,22 @@ async function fetchSitemap(sdk, appUnique, { currentLayer } = {}) {
// sitemap accepted as { ok:true, ids:[] } would cause the build to treat all pages as absent and recreate them.
if (isMalformed(String(xml))) return { ok: false, reason: 'malformed' };
- return { ok: true, xml: String(xml), ids: sitemapGenPageIds(String(xml)) };
+ // `sitemapId` (opt-in, so the default result keeps its shape) is the id the read resolved, normalized as guidKey does, for a caller that
+ // has to match this app's sitemap to a row it read elsewhere (fetchAppsForPages joins the saved layer by it).
+ return { ok: true, xml: String(xml), ids: sitemapGenPageIds(String(xml)), ...(includeSitemapId ? { sitemapId: guidKey(smId) } : {}) };
+}
+
+const guidKey = (id) => String(id || '').replace(/^\{|\}$/g, '').toLowerCase();
+
+// The one CURRENT row among the rows RetrieveUnpublishedMultiple returned for a sitemap. With a pending edit the platform can answer with
+// both layers —
+// { value: [{ componentstate: 0, sitemapxml: "old" }, { componentstate: 1, sitemapxml: "draft" }] }
+// — and only the authored row (componentstate 1) is current. Two rows that do not name exactly one current row are ambiguous, and throw.
+// Returns [] for no rows, so the caller decides what an absent row means.
+function currentSitemapRows(rows) {
+ const current = rows.length <= 1 ? rows : rows.filter((row) => row && Number(row.componentstate) === 1);
+ if (current.length > 1 || (rows.length > 1 && current.length !== 1)) throw new Error('current sitemap read returned no single current row');
+ return current;
}
// Env-wide MEMBERSHIP scan (Imp5): which apps' sitemaps reference each id in `pageIds`. GROUNDED by a live
@@ -239,8 +251,24 @@ async function fetchSitemap(sdk, appUnique, { currentLayer } = {}) {
// ONLY inside the sitemap XML (`GenPageId="…"`), with NO direct genpage→apps join. The ONLY way to find a
// page shared across apps is to scan every OTHER app's sitemap XML for the id.
//
-// Cost: O(number of apps) — one appmodule list + one sitemap read per OTHER app. `excludeAppUnique` skips the
-// app being built (self can't share with itself), so a SINGLE-APP environment reads ZERO other sitemaps.
+// Cost: O(number of apps) — one appmodule list + one PUBLISHED sitemap read per OTHER app, plus ONE read of every sitemap's SAVED layer (below), plus ONE
+// request for the apps that were never published and one component read for each of those (further below; its saved sitemap rides the one saved-layer read).
+// `excludeAppUnique` skips the app being built (self can't share with itself), so a SINGLE-APP environment reads ZERO other sitemaps: it costs the one small
+// list of apps that were never published, and nothing more when there are none (with a never-published app whose layer has no sitemap component, one saved-layer read as well).
+//
+// TWO LAYERS. A page another app has saved into its navigation but not published belongs to that app as much as a published one: the maker can
+// publish at any moment, and an UPDATE now rewrites a page that app is about to show. So an app counts for an id when its published sitemap OR its saved
+// (current, unpublished) sitemap has it. The saved layer is read for ALL other apps in ONE request, however many there are — the `sitemap` collection's
+// RetrieveUnpublishedMultiple, which is composable with $select
+// (https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/retrieveunpublishedmultiple) — and joined to each app by the
+// sitemap id its published read resolved. It is the reader, and the current-row rule (currentSitemapRows), that navigationProof applies to this
+// app's own saved layer. A draft that REMOVES a page does not clear it: the published layer is what that app's users see until the maker publishes.
+//
+// NEVER-PUBLISHED APPS. An app that was created in the maker and saved but never published has no row in the published list above, so none of that app's
+// navigation was read — yet a page it holds is its page, and publishing it would show the page there. draftOnlyApps lists such apps (one request), and each
+// one's saved sitemap is joined from the same one saved-layer read, by the sitemap id its layer's sitemap component names — or, for an app whose layer has no such
+// component, by the sitemap whose unique name is the app's (the vendored SDK links an app to its sitemap by that name). It has no published layer, so
+// whatever it holds is "saved only".
//
// COMPLETE ENUMERATION (`paginate: true`): the vendored SDK's queryRecords now follows the OData
// `@odata.nextLink` to completion, so the appmodule list is the FULL set even past the ~5000-row server
@@ -252,11 +280,17 @@ async function fetchSitemap(sdk, appUnique, { currentLayer } = {}) {
//
// FAIL-CLOSED on the enumeration itself: a failed appmodule list → { ok:false } (caller refuses to proceed
// without full visibility). BEST-EFFORT per app: an app whose sitemap we cannot read is recorded in `unreadable`
-// and skipped (one bad app doesn't block the whole env — the caller warns about partial coverage).
+// and skipped (one bad app doesn't block the whole env — the caller warns about partial coverage). The saved layer
+// is held to the same rule: a read that fails as a whole is { ok:false } (no app's draft is then known), and an app
+// whose saved sitemap is missing, ambiguous or malformed is recorded in `unreadable`. So is the list of never-published apps: one that cannot be read
+// is { ok:false }, and a draft app whose layer or sitemap cannot be resolved is `unreadable` — except one whose component read succeeds and finds no sitemap
+// component AND whose name no sitemap in the saved layer carries, which has no navigation and holds no page.
+// -> { ok:true, byId: Map<id, appUniqueName[]> (an app holding the id in either layer), savedOnly: Map<id, appUniqueName[]> (the
+// apps that hold it ONLY in the saved layer), unreadable: appUniqueName[] } | { ok:false, error }
async function fetchAppsForPages(sdk, pageIds, opts) {
opts = opts || {};
const want = new Set(Array.from(pageIds || []).map((x) => String(x).toLowerCase()));
- if (!want.size) return { ok: true, byId: new Map(), unreadable: [] };
+ if (!want.size) return { ok: true, byId: new Map(), savedOnly: new Map(), unreadable: [] };
const self = opts.excludeAppUnique ? String(opts.excludeAppUnique).toLowerCase() : null;
let apps;
@@ -292,26 +326,172 @@ async function fetchAppsForPages(sdk, pageIds, opts) {
(a) => a && a.uniquename && String(a.uniquename).toLowerCase() !== self,
);
+ // The apps that were never published, which the list above cannot show. One small request, and in a single-app environment normally the only one beyond the
+ // list itself. Fail-closed as a whole, before any sitemap is read: with no answer there is no knowing which apps the scan has not seen.
+ const drafts = await draftOnlyApps(sdk, apps, self);
+ if (!drafts.ok) return { ok: false, error: `could not list the apps that have never been published: ${drafts.reason}` };
+
const byId = new Map();
+ const savedOnly = new Map();
const unreadable = [];
+ // `app` references `id` — once, whichever layer says so. A set of apps per id, kept as the arrays the callers print.
+ const reference = (map, id, app) => {
+ const arr = map.get(id) || [];
+ if (!arr.includes(app)) arr.push(app);
+ map.set(id, arr);
+ };
+ // Each app whose sitemap is to be joined to the saved layer below: a published app whose PUBLISHED sitemap read, and a never-published app whose sitemap component was
+ // found — with the sitemap id and the page ids its PUBLISHED layer holds (a never-published app has none).
+ const readable = [];
for (const a of others) {
// Reuse the discriminated fetchSitemap reader (DRY) — any ok:false goes into unreadable.
- const r = await fetchSitemap(sdk, a.uniquename);
+ const r = await fetchSitemap(sdk, a.uniquename, { includeSitemapId: true });
if (!r.ok) {
// Best-effort: record for caller to surface partial-coverage warning; do NOT throw.
unreadable.push(a.uniquename);
continue;
}
- for (const id of r.ids) {
- if (!want.has(id)) continue;
- const arr = byId.get(id) || [];
- arr.push(a.uniquename);
- byId.set(id, arr);
+ readable.push({ app: a.uniquename, sitemapId: r.sitemapId, ids: new Set(r.ids) });
+ for (const id of r.ids) if (want.has(id)) reference(byId, id, a.uniquename);
+ }
+
+ // A never-published app's sitemap is the one its layer's sitemap component names — the read fetchSitemap makes for any layer key (componenttype 62). A read that FAILS,
+ // or one that answers with a component it cannot name, proves nothing about the app: it is unreadable, and the caller halts. A read that SUCCEEDS and finds no sitemap
+ // component does not show that the app has no navigation, though: the vendored SDK ties an app to its sitemap by NAME — it looks the sitemap up with `sitemapnameunique eq
+ // '<the app's unique name>'` and takes one for the app only while that column holds the app's name, and ensureSitemapInSolution (sdk-build.js) resolves it the same way — so
+ // such an app may hold a sitemap, and pages in it, that no component row links to it. The saved-layer read below shows whether it does (`unlinked`); an app with no sitemap of
+ // its name has no navigation at all — one saved in the maker with only a name, say — so it holds no page, and one such app must not stop every page update in the environment.
+ unreadable.push(...drafts.unreadable);
+ const unlinked = [];
+ for (const d of drafts.apps) {
+ let components;
+ try { components = await appComponentRows(sdk, d.layerKey, 62, { top: 1 }); } catch {
+ unreadable.push(d.name);
+ continue;
+ }
+ if (!components.length) {
+ unlinked.push(d);
+ continue;
+ }
+ const sitemapId = guidKey(components[0].objectid);
+ if (!sitemapId) {
+ unreadable.push(d.name);
+ continue;
+ }
+ readable.push({ app: d.name, sitemapId, ids: new Set() });
+ }
+
+ // The SAVED layer of every readable app, in one request — which also shows the sitemap of an app that is linked to it by name only. A single-app environment with no draft app
+ // has no other app, so it reads nothing here; one with a draft app that has no sitemap component reads it once, to rule such a sitemap out.
+ if (readable.length || unlinked.length) {
+ const saved = await savedSitemaps(sdk);
+ // Fail-closed as a whole: with no answer there is nothing known about ANY app's draft, so none can be ruled out.
+ if (!saved.ok) return { ok: false, error: `could not read the other apps' saved (unpublished) navigation: ${saved.reason}` };
+ for (const d of unlinked) {
+ const ids = saved.idsByName.get(String(d.name).toLowerCase());
+ if (!ids) continue; // no sitemap carries the app's name: it has no navigation
+ // More than one sitemap claiming the name leaves it unknown which is the app's, and either may hold the page.
+ if (ids.size !== 1) {
+ unreadable.push(d.name);
+ continue;
+ }
+ readable.push({ app: d.name, sitemapId: [...ids][0], ids: new Set() });
+ }
+ for (const a of readable) {
+ const layer = savedLayerIds(saved.byId.get(a.sitemapId));
+ // Fail-closed per app, as the published read is: a saved layer that is missing, ambiguous or malformed cannot prove the app does not hold the page.
+ if (!layer.ok) {
+ if (!unreadable.includes(a.app)) unreadable.push(a.app);
+ continue;
+ }
+ for (const id of layer.ids) {
+ if (!want.has(id)) continue;
+ reference(byId, id, a.app);
+ if (!a.ids.has(id)) reference(savedOnly, id, a.app);
+ }
}
}
- return { ok: true, byId, unreadable };
+ return { ok: true, byId, savedOnly, unreadable };
+}
+
+// The apps that have NEVER been published. The published `appmodule` list that fetchAppsForPages walks has no row for an app that is only saved in the maker, though its navigation is
+// saved all the same. The same collection's RetrieveUnpublishedMultiple answers with the CURRENT layer of every app, drafts included, in one request (paged) however many there are:
+// { "value": [ { "appmoduleid": "…", "appmoduleidunique": "…", "uniquename": "contoso_draft", "componentstate": 1 }, … ] }
+// An app that has a published row — matched by `appmoduleid`, which a pending edit leaves alone, unlike the layer key `appmoduleidunique` — is read through its published layer and skipped
+// here, as is `self`. What is left exists only as a draft, and its one current layer (the only row, or the authored one: currentLayerRows) carries the layer key its components hang off.
+// FAIL-CLOSED: a list that cannot be read, or a row with no id, is { ok:false } — what the rows leave out cannot be known; a draft app whose layer cannot be told is named in `unreadable`.
+// -> { ok:true, apps:[{ name, layerKey }], unreadable:[name] } | { ok:false, reason }
+async function draftOnlyApps(sdk, published, self) {
+ if (!sdk || !sdk.dataverse || typeof sdk.dataverse.get !== 'function') return { ok: false, reason: 'no Dataverse client to read it' };
+ let rows;
+ try {
+ rows = await collectionRows(sdk.dataverse, '/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,uniquename,componentstate', 'apps that have never been published');
+ } catch (e) {
+ return { ok: false, reason: String((e && e.message) || e) };
+ }
+ const havePublishedRow = new Set(published.map((app) => guidKey(app && app.appmoduleid)));
+ const byApp = new Map();
+ for (const row of rows) {
+ const id = row && guidKey(row.appmoduleid);
+ if (!id) return { ok: false, reason: 'a row came back with no appmoduleid' };
+ if (havePublishedRow.has(id)) continue;
+ if (!byApp.has(id)) byApp.set(id, []);
+ byApp.get(id).push(row);
+ }
+ const apps = [];
+ const unreadable = [];
+ for (const [id, group] of byApp) {
+ const named = group.find((row) => typeof row.uniquename === 'string' && row.uniquename.trim());
+ const name = named ? named.uniquename : id;
+ if (name.toLowerCase() === self) continue;
+ const current = currentLayerRows(group);
+ if (current.length !== 1 || !GUID_36.test(guidKey(current[0].appmoduleidunique))) unreadable.push(name);
+ else apps.push({ name, layerKey: guidKey(current[0].appmoduleidunique) });
+ }
+ return { ok: true, apps, unreadable };
+}
+
+// Every sitemap's CURRENT layer in ONE request: { ok:true, byId: Map<sitemapid, row[]>, idsByName: Map<lower-cased sitemapnameunique, Set<sitemapid>> } or { ok:false, reason }. The rows
+// of one sitemap are all those the platform returned for its id (currentSitemapRows picks the current one), grouped here so the caller reads each app's by its own id. `idsByName` is
+// the same rows seen by the unique name the vendored SDK ties an app to its sitemap by (see fetchAppsForPages): a row looks like
+// { "sitemapid": "5111e0f2-…", "sitemapnameunique": "contoso_orders", "componentstate": 1, "sitemapxml": "<SiteMap>…" }
+// and names are lower-cased because Dataverse compares them without regard to case.
+// The read pages with @odata.nextLink like every other collection read in app-components.js (collectionRows): a repeated link, a failed page or a
+// body that is no result set is a failure, never a shorter list.
+async function savedSitemaps(sdk) {
+ if (!sdk || !sdk.dataverse || typeof sdk.dataverse.get !== 'function') return { ok: false, reason: 'no Dataverse client to read it' };
+ let rows;
+ try {
+ rows = await collectionRows(sdk.dataverse, '/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapxml,componentstate,sitemapnameunique', 'saved sitemaps');
+ } catch (e) {
+ return { ok: false, reason: String((e && e.message) || e) };
+ }
+ const byId = new Map();
+ const idsByName = new Map();
+ for (const row of rows) {
+ const id = row && guidKey(row.sitemapid);
+ if (!id) continue;
+ if (!byId.has(id)) byId.set(id, []);
+ byId.get(id).push(row);
+ const name = typeof row.sitemapnameunique === 'string' ? row.sitemapnameunique.trim().toLowerCase() : '';
+ if (name) {
+ if (!idsByName.has(name)) idsByName.set(name, new Set());
+ idsByName.get(name).add(id);
+ }
+ }
+ return { ok: true, byId, idsByName };
+}
+
+// The genpage ids in one app's saved layer — { ok:true, ids } — or { ok:false } when its rows cannot be trusted: none came back for its sitemap, they do
+// not name one current row, or the current one has no XML or malformed XML (the same structural check a published sitemap must pass).
+function savedLayerIds(rows) {
+ let current;
+ try { [current] = currentSitemapRows(rows || []); } catch { return { ok: false }; }
+ const xml = current && current.sitemapxml;
+ if (!xml || isMalformed(String(xml))) return { ok: false };
+ return { ok: true, ids: sitemapGenPageIds(String(xml)) };
}
// This app's navigation as OWNERSHIP PROOF for page ids. `published` is a fetchSitemap result for the
diff --git a/plugins/model-apps/scripts/lib/solution-membership.js b/plugins/model-apps/scripts/lib/solution-membership.js
new file mode 100644
index 000000000..764f3312d
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/solution-membership.js
@@ -0,0 +1,159 @@
+'use strict';
+// What a solution already holds, read once per build, so a rebuild adds only the components it is missing.
+//
+// The build re-asserts the solution membership of every component it REUSES — views, forms, charts, business
+// rules, the process flow, the app, its sitemap, the page manifest, persona roles — on every run. That is
+// deliberate: a component whose add failed after its create (or one made by a build of a different solution)
+// is reused forever, and without the re-assert it would stay out of the exported solution with nothing saying
+// so. AddSolutionComponent treats an already-present component as success, so the re-assert was always safe;
+// it was also one write per component on a rebuild that changed nothing.
+//
+// One read answers all of them: the `solutioncomponent` rows of this solution, restricted to the component
+// types the build adds and to tables. Two things count as proof, and nothing else does:
+// 1. A row for (type, id). The add is provably unnecessary and is skipped.
+// 2. For a VIEW, CHART or FORM (types 26, 59, 60): a row showing that the solution holds the component's TABLE
+// with ALL its subcomponents (`rootcomponentbehavior` 0). Such a component is a member WITHOUT a row of its
+// own. A table created inside a solution is added that way ("Include all objects"), and the platform does not
+// list its forms, views and charts one by one — the SDK's own solution reader says so ("members the solution
+// does not list one by one"), and a live rebuild showed the consequence: the explicit AddSolutionComponent of
+// such a view leaves no row, so a read that looked only for rows sent those adds again on every rebuild.
+// A component with neither is added exactly as before. Caveats, all in the safe direction:
+// * Only behavior 0 proves anything about subcomponents. A table held at 1 ("Do not include subcomponents": the
+// table's own metadata only) or 2 ("Include As Shell Only": just the subcomponents added one by one, each with
+// a row of its own) carries none of its views, forms or charts, so those still need the row and are added
+// without it. A table row with no behavior (null) is no proof either.
+// * Other kinds are never inferred from a table. Business rules, flows, roles, the app, its sitemap and the
+// page manifest are root components that get a row of their own when added, and are judged by it alone.
+// * The set is a snapshot taken at first use. A component added during this run is recorded (`note`), so a
+// second assert of it in the same run is skipped too; one removed from the solution by someone else mid-build
+// is a race this does not try to win.
+// * ANY failure to read — no such solution, a built-in container (it holds every unmanaged customization, so
+// membership proves nothing), a page that cannot be followed, or a table whose MetadataId cannot be resolved —
+// proves nothing, and the component is added as it always was. The optimisation may never be the reason a
+// component is left out.
+//
+// Row shapes (OData JSON; ids are lower-case and unbraced):
+// a component { "solutioncomponentid": "…", "objectid": "3f2a9c6e-…", "componenttype": 26, "rootcomponentbehavior": null }
+// a table { "solutioncomponentid": "…", "objectid": "<the table's MetadataId>", "componenttype": 1, "rootcomponentbehavior": 0 }
+// `objectid` is the component's own id (a savedquery id for type 26, a systemform id for 60, a
+// savedqueryvisualization id for 59, …) and, for a table, its MetadataId — which is why a view's table is resolved
+// to a MetadataId before it can be looked up. `rootcomponentbehavior` is an Edm.Int32 choice, null on components
+// that are not roots: 0 Include Subcomponents, 1 Do not include subcomponents, 2 Include As Shell Only.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/solutioncomponent
+const { odataLit } = require('./odata.js');
+const { isRestrictedSolution } = require('./system-solutions.js');
+
+const GUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+const bare = (value) => String(value === undefined || value === null ? '' : value).replace(/[{}]/g, '').trim().toLowerCase();
+const keyOf = (type, id) => `${Number(type)}:${bare(id)}`;
+
+// A table's component type code: its solutioncomponent `objectid` is the table's MetadataId.
+const TABLE = 1;
+// The component types a table held with all its subcomponents carries without listing them. These are the three
+// the SDK's own solution reader documents for it (forms, views, charts); widening the set to a kind that gets a
+// row of its own when added — a role, a workflow, a web resource — would skip adds the platform needs.
+const TABLE_SUBCOMPONENT_TYPES = new Set([26, 59, 60]);
+// `rootcomponentbehavior` 0 — Include Subcomponents. The SDK's reader also accepts the string form, and a bare
+// `Number(value) === 0` would read null and '' as 0, which is exactly the mistake that would fake a proof.
+const isWholeTable = (behavior) => behavior === 0 || behavior === '0';
+
+// What `solutionUniqueName` holds among `componentTypes`: `{ members, wholeTables }` — `members` a Set of
+// `<type>:<id>` keys, `wholeTables` a Set of the bare MetadataIds of the tables held with all their
+// subcomponents — or null when it cannot be known (see above). `read` is anything with the SDK's
+// `queryRecords`. Throws on a failed read; createSolutionMembership turns that into null.
+async function readSolutionMembers(read, solutionUniqueName, componentTypes) {
+ if (!read || typeof read.queryRecords !== 'function') return null;
+ if (!solutionUniqueName || isRestrictedSolution(solutionUniqueName)) return null;
+ const types = [...new Set((componentTypes || []).map(Number).filter(Number.isInteger))];
+ if (!types.length) return null;
+ const solutions = await read.queryRecords('solution', { select: ['solutionid'], filter: `uniquename eq '${odataLit(solutionUniqueName)}'`, top: 1 });
+ const solutionId = bare(solutions && solutions[0] && solutions[0].solutionid);
+ // Interpolated unquoted into an Edm.Guid comparison below, so it must be a GUID and nothing else.
+ if (!GUID_RE.test(solutionId)) return null;
+ // Tables are read in the same query when a view, chart or form is among the kinds asked about: they are what
+ // can vouch for those without a row of their own.
+ const asked = types.some((type) => TABLE_SUBCOMPONENT_TYPES.has(type)) ? [...new Set([...types, TABLE])] : types;
+ // Restricted to the types the build adds: a solution also holds a row per column, relationship and option set
+ // of every table in it, none of which this build re-asserts. `paginate` follows @odata.nextLink, so a large
+ // solution is read in full, and a paging fault throws (and so reads as unknown) rather than as a short list.
+ const rows = await read.queryRecords('solutioncomponent', {
+ select: ['objectid', 'componenttype', 'rootcomponentbehavior'],
+ filter: `_solutionid_value eq ${solutionId} and (${asked.map((type) => `componenttype eq ${type}`).join(' or ')})`,
+ paginate: true,
+ });
+ if (!Array.isArray(rows)) return null;
+ const members = new Set();
+ const wholeTables = new Set();
+ for (const row of rows) {
+ const id = bare(row && row.objectid);
+ const type = Number(row && row.componenttype);
+ // A component type is a positive integer; `Number(null)` and `Number('')` are 0, which is no type at all.
+ if (!id || !Number.isInteger(type) || type <= 0) continue;
+ members.add(keyOf(type, id));
+ if (type === TABLE && isWholeTable(row.rootcomponentbehavior)) wholeTables.add(id);
+ }
+ return { members, wholeTables };
+}
+
+// A lazily-read, memoised view of one solution's membership. The read starts at the first `has`, so a build
+// that never asks — it reuses nothing and deploys no pages, whose manifest always asks — never pays for it, and
+// concurrent callers share the one read.
+//
+// `resolveTableId(logicalName)` answers a table's MetadataId. It is called only for a view, chart or form that
+// has no row of its own while the solution holds some table with all its subcomponents, once per table (a
+// failure is remembered too, not retried per component), and a throw or an answer that is no GUID simply proves
+// nothing. Without it the table check is off and only rows count.
+function createSolutionMembership({ read, solutionUniqueName, componentTypes, resolveTableId }) {
+ let pending;
+ let known = null;
+ const members = () => {
+ if (!pending) {
+ pending = Promise.resolve()
+ .then(() => readSolutionMembers(read, solutionUniqueName, componentTypes))
+ .catch(() => null)
+ .then((held) => { known = held; return held; });
+ }
+ return pending;
+ };
+ const tableIds = new Map();
+ const tableIdOf = (table) => {
+ const logical = String(table).trim().toLowerCase();
+ if (!tableIds.has(logical)) {
+ tableIds.set(logical, Promise.resolve()
+ .then(() => resolveTableId(logical))
+ .then((id) => (GUID_RE.test(bare(id)) ? bare(id) : null), () => null));
+ }
+ return tableIds.get(logical);
+ };
+ return {
+ // True only when the solution is PROVEN to hold the component: it has a row, or — for a view, chart or form
+ // given with its `table` — the solution holds that table with all its subcomponents.
+ async has(componentId, componentType, { table } = {}) {
+ const held = await members();
+ if (!held) return false;
+ if (held.members.has(keyOf(componentType, componentId))) return true;
+ if (!table || typeof resolveTableId !== 'function' || !held.wholeTables.size) return false;
+ if (!TABLE_SUBCOMPONENT_TYPES.has(Number(componentType))) return false;
+ const tableId = await tableIdOf(table);
+ return !!tableId && held.wholeTables.has(tableId);
+ },
+ // Records a component this run added, so a repeated assert of it is skipped. Never invents membership
+ // the read did not establish: with nothing known there is nothing to add to.
+ note(componentId, componentType) {
+ if (known) known.members.add(keyOf(componentType, componentId));
+ },
+ };
+}
+
+// Add a component to the solution unless it is already proven to be in it. Returns whether the add was made.
+// A failure of the add propagates, exactly as a direct `addSolutionComponent` would — each call site keeps its
+// own policy (fail the phase, or warn and carry on). `table` is the logical name of the table a view, chart or
+// form belongs to; it is only evidence for the membership check and never reaches the add.
+async function ensureSolutionComponent(sdk, membership, { componentId, componentType, solutionUniqueName }, { table } = {}) {
+ if (membership && await membership.has(componentId, componentType, { table })) return false;
+ await sdk.addSolutionComponent({ componentId, componentType, solutionUniqueName });
+ if (membership) membership.note(componentId, componentType);
+ return true;
+}
+
+module.exports = { readSolutionMembers, createSolutionMembership, ensureSolutionComponent };
diff --git a/plugins/model-apps/scripts/lib/source-literals.js b/plugins/model-apps/scripts/lib/source-literals.js
index 6c6f93153..c8ab30517 100644
--- a/plugins/model-apps/scripts/lib/source-literals.js
+++ b/plugins/model-apps/scripts/lib/source-literals.js
@@ -808,8 +808,10 @@ function readRuleToken(src, j) {
}
// Whether the `<` at `i`, where an assignment expression may start, opens a generic arrow's type parameters (`generic`) or an element, and the kind of
-// guess the answer rests on, or null where the rule decides: { generic, ambiguity }. See above.
-function opensTypeParameters(src, i, budget = null) {
+// guess the answer rests on, or null where the rule decides: { generic, ambiguity }. See above. `inExpression` says the `<` is known to start an expression (a default value after an `=`): a name and a
+// `>` is then an element, as the rule says, and no function type's `<T>` is read there (genericFunctionTypeFollows), which a `<` in a type may be. `noMember` says that no member of a type begins at the `<` (NO_MEMBER_BEFORE),
+// which settles a parameter list with neither `=>` nor `:` after it.
+function opensTypeParameters(src, i, budget = null, inExpression = false, noMember = false) {
let escaped = false;
const read = (j) => {
const token = readRuleToken(src, skipSpaceAndComments(src, j));
@@ -835,13 +837,15 @@ function opensTypeParameters(src, i, budget = null) {
const fourth = read(third.end);
// TypeScript's rule makes `<T extends` and a `=`, a `>` or a `/` an element where an expression starts. In a type a `=` or a `>` there is no constraint (TS1110), but a `/` starts one:
// parseTypeParameter reads a constraint that starts no type as an expression, a regex, and only the checker objects (`let f: <T extends />;…/>(a: T) => T` is a FunctionType). The lexer
- // cannot tell a type from an expression there, so the `/` is the guess, with the element read.
- if (fourth.kind === 'slash') return verdict(false, 'generic');
+ // cannot tell a type from an expression there, so the `/` is the guess, with the element read — unless the regex does not close on its line: it is unterminated then (TS1161, a parse
+ // error), no type has the text, and the element is certain (`const e = <T extends />;` and the end of the line). A regex that closes leaves both: `<T extends />; const r = a / b;`.
+ if (fourth.kind === 'slash') return verdict(false, regexEnd(src, fourth.end - 1) === -1 ? null : 'generic');
return verdict(!(fourth.kind === 'equals' || fourth.kind === 'gt'));
}
if (third.kind === 'comma' || third.kind === 'equals') return verdict(true);
if (third.kind === 'gt' && identifier.kind === 'word') {
- const type = genericFunctionTypeFollows(src, third.end, i, budget);
+ if (inExpression) return verdict(false);
+ const type = genericFunctionTypeFollows(src, third.end, i, budget, noMember);
return verdict(type.generic, type.ambiguity);
}
return verdict(false);
@@ -903,6 +907,14 @@ const ANGLE_CLASS = new Map([
]);
const ANGLE_CLASS_AFTER_LINE_BREAK = new Map(Object.entries(ANGLE_AFTER_LINE_BREAK).map(([token, kind]) => [token, { read: 'guess', kind }]));
+// The tokens of the `rule` class after which no member of a type begins and no name stands that a signature's type parameters could follow: an assignment's `=` and the compound ones, the `=>` of an arrow, a `(` or a `[` that opens
+// what an expression or a type must fill, and a `:`, after which a type is a function type only with an `=>`. So a head `<Name>` and a parameter list that neither `=>` nor `:` follows is an element there in every program that
+// parses — there is no call signature for its text to be the start of (callSignatureOrElement). Any other token that the rule is asked after can end a member, or can be the name of one: a separator or a bracket (`,`, `;`, `{`, `}`, `)`), a
+// `?` (`m?<T>(x)` is a method with an optional mark) and a keyword (`return <T>(x)` is a method named `return`; every keyword is a name in a type), and the text after the head is read to tell the two apart.
+// const help = <p>(optional); foo( // note /docs</p>; f(<p>(a)</p>) [<p>(a)</p>] o = { k: <p>(a)</p> } () => <p>(a)</p>
+// (not: `interface I { m? <T>(x); a: '</T>…' }`, `interface I { return <T>(x); a: '</T>…' }`, `f(x), <p>(a)</p>`)
+const NO_MEMBER_BEFORE = new Set(['=', '+=', '-=', '*=', '**=', '/=', '%=', '<<=', '&=', '|=', '^=', '&&=', '||=', '??=', '=>', '(', '[', ':']);
+
// The characters of an operator, and the operators a run of them is cut into — longest first; a `>` is read on its own. A run longer than RUN_LIMIT is read from its
// end: every operator is shorter than that, and a scan that went back over the whole of a long `=====…` — or of `<></>=<></>=…`, where every character is one of
// them — before each `<` would be quadratic.
@@ -983,7 +995,7 @@ function angleBefore(src, i) {
if (star === 'cut') return { read: 'guess', kind: 'identifier' };
}
const cls = (newline && ANGLE_CLASS_AFTER_LINE_BREAK.get(token)) || ANGLE_CLASS.get(token) || { read: 'guess', kind: 'operator' };
- return cls.read === 'guess' ? { ...cls, token } : cls;
+ return { ...cls, token };
}
// Whether the head of the `<` at `i`, read as a tag to its `>`, is followed by no parameter list and arrow that type parameters could take: `<T extends X>text</T>`, `<T extends X>(text)`.
@@ -1046,7 +1058,8 @@ function angleOpens(src, out, i, budget = null, certainOperator = false) {
// Directly after the head of a type alias a `<` is a function type's whatever follows it (afterTypeAliasHead). The head ends in a lone `=`, so no token of
// another class can precede it.
if (afterTypeAliasHead(out, i)) return { generic: true, ambiguity: null };
- const rule = opensTypeParameters(src, i, budget);
+ // After one of these tokens no member of a type begins, so a head with a parameter list that neither `=>` nor `:` follows is no call signature (NO_MEMBER_BEFORE).
+ const rule = opensTypeParameters(src, i, budget, false, before.read === 'rule' && NO_MEMBER_BEFORE.has(before.token));
// After a guess token, a head with a constraint and no parameter list is an element in every program that parses (headWithoutParameterList). That holds after the cut `>=`, `>>=`
// and `>>>=` too: where the first `>` ends type arguments, `>=` compares and the head is an element; where the run is one operator, an assignment, the rule reads the head as
// type parameters, TypeScript attempts the arrow it then must be, and with no parameter list that is an error (`v >>= <T extends X>text</T>`).
@@ -1262,55 +1275,452 @@ function commentEnd(src, open, last) {
// leaves it out (it is a contextual word there, a guess): its heritage clause takes an expression, as `extends` does, so in a computed name a type may hold `[class C implements /re/ {}]`, and the
// closing tag in that regex (parseHeritageClause, parseExpressionWithTypeArguments, https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts).
// and/or 1/2 a / b (not: `(a) /x/`, `= /x/`, `return /x/`, `implements /x/`, `</b> /x/`)
-function slashFollowsAnOperand(src, at) {
- const before = prevSignificant(src, at);
- if (!/[\w$]/.test(before.ch)) return false;
+// The text is read as written, comments included, and prevSignificant skips white space only: after a comment it finds the comment's last character, which says nothing — a block comment ends in a `/` and a line comment in
+// whatever its text does — where the comment is trivia, and what the `/` follows is the token before it. A regex may follow a line comment on the next line, after the operator that the comment stands behind:
+// x = 1 + // fallback the last token is the `+`, the comment is trivia, and `fallback` is no operand
+// /\)/ a regex, whose `)` is not the one that ends a parameter list
+// A `/` read as a division there ended the scan of the list at that `)` (genericFunctionTypeFollows) and hid the closing tag of a signature's text in a regex (readChildren). So a `/` after a line comment that the caller
+// has not found itself follows no operand (see lineMayEndInComment); one that has passes the comments (`comments`, { from, to }: the run of comments, and the white space between them, that ends before the `/`) and
+// the token before the run decides, as it does to a parser: `b // c` and a line break, then `/d`, divides, and `1 + // c` and a line break, then `/d/`, does not.
+// A `/` after a `)` or `]` divides as well, where the caller says so (`brackets`): no regex follows a parenthesised expression, a call, an index or an array literal, and no type has a `/` after a bracket
+// (`(x) // c` and a line break, then `/d`). A `)` is where a regex could follow only after the head of a statement (`if (x) /re/.test(y)`), which has a block to hold it, and the caller reads none: a `{` in the text it reads
+// is an expression container, which it skips or does not read (containerFailsAt).
+// (x) // c m[0] // c f(a, b) [1, 2] (not: `if (x)` in a block that is not read, `(x) => /re/`: a `/` after `=>` follows the `>`)
+function slashFollowsAnOperand(src, at, comments = null, brackets = false) {
+ let before = prevSignificant(src, at);
+ if (comments !== null && before.index >= comments.from && before.index < comments.to) before = prevSignificant(src, comments.from);
+ const bracket = brackets && (before.ch === ')' || before.ch === ']');
+ // Only a word, a number or a bracket is an operand — and lineMayEndInComment depends on that: it starts before `before.index`, whose character is then no `/` that could end a `//` and no line terminator, so where it starts cannot matter.
+ if (!bracket && !/[\w$]/.test(before.ch)) return false;
+ if (before.newline && lineMayEndInComment(src, before.index)) return false;
+ if (bracket) return true;
let start = before.index;
while (start > 0 && /[\w$]/.test(src[start - 1])) start -= 1;
const word = src.slice(start, before.index + 1);
+ // A hex, binary or octal literal takes no check for a word after it (`0x1Fin`: the literal and `in`, scanner.ts scanNumber checks only a decimal one), and `in` and `instanceof` are operators that a regex follows.
+ if (/^0[xXbBoO]/.test(word) && /(?:in|instanceof)$/.test(word)) return false;
return !EXPR_START_WORDS.has(word) && word !== 'implements';
}
+// The run of comments that the comment at `at`, which ends at `end` (commentEnd), belongs to, for slashFollowsAnOperand: it goes on from `comments` where nothing but white space stands between them, and
+// is the start of a new one where something else does.
+function commentRun(src, comments, at, end) {
+ if (comments !== null) {
+ const previous = prevSignificant(src, at).index;
+ if (previous >= comments.from && previous < comments.to) return { from: comments.from, to: Math.max(comments.to, end) };
+ }
+ return { from: at, to: end };
+}
+
+// Whether the character at `index`, which is last on its line (a line break follows it), may be in a line comment: a `//` stands before it on its line. A line comment runs to the line terminator, so what is last on a
+// line is in one if a `//` begins a comment before it. A `//` that begins none — in a string, a template or a regex, which a line may begin inside of — is not told from one, since nothing before the line is read: the `/`
+// after it stays a guess, which is the safe side (a regex read as a division hides a `)` or a closing tag, and a division read as a regex only refuses). A line that begins before the window is not read at all: the
+// answer is yes. Line comments and line terminators: https://tc39.es/ecma262/#sec-comments, isLineTerminator.
+// a = 1 + // fallback `fallback` is in the comment
+// b = "http://x" + y `y` is code, but a `//` stands before it on its line: the guess all the same
+function lineMayEndInComment(src, index) {
+ const floor = Math.max(0, index - LOOKAHEAD);
+ for (let k = index - 1; k >= floor; k -= 1) {
+ if (isLineTerminator(src[k])) return false;
+ if (src[k] === '/' && src[k + 1] === '/') return true;
+ }
+ return floor > 0;
+}
+
// The words that can stand before a member's name in a type, so that a name after one is no second name: every reserved word, every contextual one, and the modifiers TypeScript takes.
const MEMBER_MODIFIERS = new Set(['public', 'private', 'protected', 'const', 'interface', 'package']);
-// Whether the text from `from` to `to` cannot be the members of a type. It is what follows the `)` of a call or construct signature, up to the first place that could hide the closing tag the text reaches
-// (a string, a template, a comment, a regex): where no type can be valid up to there, no program has one that holds the closing tag in anything, and nothing after it hides it. A member is a name, and what follows
-// a name on its line is `:`, `?`, `(`, `<`, a separator or the end of the line (parseTypeMemberSemicolon, https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts); a second name or a string
-// there is TS1005, and a `/` has no place after a name in a type (it divides in an expression, where a name may stand but a member does not). A template or a regex that opens at `to` is no member's
-// start either (TS1131, "Property or signature expected"; parseTypeMember): with only names and separators before it, it stands where a member begins or right after a name. (After a `:` a template is
-// a type, `m: \`a${string}\``, and the reading stops at the colon, undecided.) Only plain prose is read — names, numbers, `,` and `;` — and a word that may be a modifier, or any other character, leaves it
-// undecided (false):
+// The keywords that TypeScript's parser may take for the modifier of a member, which a name follows, and the two that start an accessor (isModifierKind, parseModifiers and parseContextualModifier in
+// https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts). Any other keyword that stands where a member begins is its name: every keyword is a name there (parsePropertyName).
+const MODIFIER_WORDS = new Set(['abstract', 'accessor', 'async', 'const', 'declare', 'default', 'export', 'in', 'out', 'override', 'private', 'protected', 'public', 'readonly', 'static', 'get', 'set']);
+
+// The characters that no member of a type begins with, wherever one may: a sign, an operator, a closing bracket (TS1131, "Property or signature expected").
+const STARTS_NO_MEMBER = '-+*%^~)]';
+// The characters that no member begins with where nothing goes on the member before it — right after a `,` or a `;`, or after a signature's `)`: also `&` and `|`, which a line break puts at the start of a line
+// that goes on the type before it (`m: A` and a line break, then `| B`), `=` (an initializer, `m` and a line break, then `= 1`), `?`, `:`, `.` (when no digit follows: `.5` is a number), `!`, and `>`, `{` and `@`.
+// Measured over every ASCII character: each is TS1131 there, and each of the others (a letter, a digit, `_`, `$`, a quote, `(`, `<`, `[`, a back-tick, `}`) can begin a member; so can a `#` that a name follows
+// (a private name, `#x`, which the parser takes for a member's name, and only the checker objects), where a `#` that nothing follows is an invalid character (TS1127).
+const STARTS_NO_HARD_MEMBER = `${STARTS_NO_MEMBER}!&=>?@|{.`;
+// The characters that no name is followed by on its line (TS1005, "';' expected"). `&` and `|` go on a type from the next line, `=` starts an initializer, a quote is read as a string (typeMembersFail), and a backslash
+// may go on the name (`a\u0061b` is ONE identifier, a name with an escape in it), so nothing is said of them.
+const NO_AFTER_NAME = `${STARTS_NO_MEMBER}&|!.>@`;
+// After a word that may be a modifier (a name, or a modifier that a name follows): the same, but a quote is a name, a backslash may start one (`readonly \u0061b: T`), and `=` is an initializer's (`get = 1` is a
+// member; any other word and `=` is not, which is not said).
+const NO_AFTER_MODIFIER = `${STARTS_NO_MEMBER}&|!.>@`;
+// After a line break that follows a name — `m` and a line break, then the next line: the member goes on with `:`, `?`, `=`, `(` or `<`, or another begins, so what is dead is what none of them starts with. `&` and `|` do not
+// go on a name (a type needs its `:` first), nor do `.`, `!`, `>` and `@`.
+const NO_NEXT_LINE_AFTER_NAME = `${STARTS_NO_MEMBER}&|!.>@`;
+// After a line break that follows a type — `m: A` and a line break: the type goes on with `&`, `|` and `.`, or the member with an initializer's `=`, or another begins; a `:` and a `?` are TS1005 there, and so are `!`, `>` and `@`.
+const NO_NEXT_LINE_AFTER_TYPE = `${STARTS_NO_MEMBER}!>@?`;
+// Where a type must follow — after a `:`, a leading `|` or `&`, a `.` — the characters that no type starts with (TS1110, "Type expected"), of those measured over every ASCII character that can be said of one character: a
+// `-` starts a number (`-1`: its own rule), a `.` that no digit follows starts nothing (`.5` is read as a number before this), a `#` and a backslash may start a name, `*`, `!`, `?`, `<`, a bracket, a quote and a back-tick start
+// a type, and a `,`, `;`, `:` and `/` have a rule of their own.
+const NO_START_OF_TYPE = '%^~)]+=@.';
+
+// Where the prose after a signature's `)` is, read as the members of a type (typeMembersFail):
+const PROSE_START = 0; // a member begins and no member goes on there: after the `)`, a `,` or a `;`
+const PROSE_NAME = 1; // a member's name — or the name and the parameters of a signature — was read on this line
+const PROSE_COLON = 2; // `name:` was read: a type must follow, on this line or on a later one
+const PROSE_TYPE = 3; // `name: type` was read on this line
+const PROSE_OTHER = 4; // anything else was read: nothing more is said
+const PROSE_LINE = 5; // a member begins, or the one before it goes on: after a line break that follows a name
+const PROSE_MODIFIER = 6; // a word was read where a member begins that is a modifier if a name follows, and a name if not
+const PROSE_TPARAMS = 7; // a signature's type parameters were read: its parameter list must follow
+const PROSE_INIT = 8; // a member's `=` was read: an initializer follows, and nothing of it has been
+const PROSE_OPERAND = 9; // ... and a name, a number or a string, with no keyword before it: the initializer's first operand, on the line it began on
+const PROSE_SIGNATURE = 10; // the `)` of the signature that the text follows: a member begins after it, as after a separator, but a `:` is the signature's return type
+const PROSE_LINE_TYPE = 11; // a member begins, or the type before it goes on: after a line break that follows a type
+const PROSE_QUALIFIED = 12; // a `.` in a type was read, or `typeof` or `infer`: a name follows, and any word is one there (`A.new`, `A.keyof`, `typeof new`, `infer keyof`)
+const PROSE_OPERATOR = 13; // `keyof`, `readonly` or `unique` was read: a type follows, which may be another of them, and any other word is a name (`keyof new`)
+
+// Every keyword TypeScript has (ts.SyntaxKind.FirstKeyword to LastKeyword in 5.8): the words that may stand beside another operand in an expression. No other word may — `a b` is an error, whatever they are — so two
+// side by side that are not on this list are TS1005.
+const TS_KEYWORDS = new Set(['break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'enum', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'import', 'in',
+ 'instanceof', 'new', 'null', 'return', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while', 'with', 'implements', 'interface', 'let', 'package', 'private', 'protected', 'public',
+ 'static', 'yield', 'abstract', 'accessor', 'as', 'asserts', 'assert', 'any', 'async', 'await', 'boolean', 'constructor', 'declare', 'get', 'infer', 'intrinsic', 'is', 'keyof', 'module', 'namespace', 'never', 'out',
+ 'readonly', 'require', 'number', 'object', 'satisfies', 'set', 'string', 'symbol', 'type', 'undefined', 'unique', 'unknown', 'using', 'from', 'global', 'bigint', 'override', 'of']);
+
+// A character of a name, or of a word that no token of a type is made of: every character beyond ASCII that is no white space is part of an identifier or is no token at all (TS1127), and either way
+// it is no punctuation that a name could be followed by.
+function isProseWordChar(ch) {
+ return /[\w$]/.test(ch) || (ch.charCodeAt(0) > 0x7f && !isTrivia(ch));
+}
+
+// Whether `ch`, the character after a `#`, makes it the start of a private name (`#x`): any character that may start a name — a digit and a backslash may not.
+function isPrivateNameStart(ch) {
+ return ch !== undefined && ch !== '\\' && isProseWordChar(ch) && !isDigit(ch);
+}
+
+// The end of the numeric literal that starts at `at` — a digit, or a `.` and a digit — as the scanner reads one (scanNumber, https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/scanner.ts): digits and `_`, a `.`
+// and more digits, and an exponent whose `e` or `E` takes a sign, all of it ONE token, which is a valid name for a member. The characters of a word go on with a decimal literal (`1n`: and a word after one is an error).
+// 1.5 .5 1. 1e5 1e+5 1E-5 1_0e+1 1.5e-3 0x1e+5 is `0x1e`, `+` and `5`: a hex literal has no exponent 0x1Fin is `0x1F` and `in`
+// A sign that no digit follows (`1e+x`) is not part of the literal: the scanner reports TS1124 ("Digit expected") there, and the page has no valid reading.
+function numericLiteralEnd(src, at, to) {
+ let k = at;
+ if (src[k] === '0' && /^[xXbBoO]$/.test(src[k + 1] || '')) {
+ // A hex, binary or octal literal ends at its last digit, or at the `n` of a BigInt: what follows is another token (`0x1Fin` is `0x1F` and `in`, and no check forbids it, where a word right after a decimal literal is
+ // TS1351, which no page has). scanner.ts, scan: the `0x`, `0b` and `0o` cases.
+ const digit = /^[xX]$/.test(src[k + 1]) ? /[0-9a-fA-F_]/ : /^[bB]$/.test(src[k + 1]) ? /[01_]/ : /[0-7_]/;
+ k += 2;
+ while (k < to && digit.test(src[k])) k += 1;
+ if (src[k] === 'n') k += 1;
+ return k;
+ }
+ const digits = () => { while (k < to && (isDigit(src[k]) || src[k] === '_')) k += 1; };
+ if (src[k] !== '.') digits();
+ if (src[k] === '.') {
+ k += 1;
+ digits();
+ }
+ if (src[k] === 'e' || src[k] === 'E') {
+ let sign = k + 1;
+ if (src[sign] === '+' || src[sign] === '-') sign += 1;
+ if (isDigit(src[sign])) {
+ k = sign;
+ digits();
+ }
+ }
+ while (k < to && isProseWordChar(src[k])) k += 1;
+ return k;
+}
+
+const CLOSERS = Object.freeze({ '(': ')', '[': ']', '{': '}' });
+
+// The index just past the bracket that closes the `(`, `[` or `{` at `open`, or -1 where it is not known to be the one: the text up to `last` is read as code in which no literal can hide a bracket. A string is
+// skipped (it ends on its line, which stringEnd says), and so is a comment, and everything else that has a bracket in it is not read: a template, a regex or a division (a `/` that starts no comment), an element (a `<`) and
+// a backslash. So the brackets that are read are the ones TypeScript reads, and they match, where the text is a parameter list, a computed name or an index signature (`(x, y?: string)`, `[k: string]`, `[a.b]`, `(a = f(1))`).
+function bracketEnd(src, open, last) {
+ const expected = [];
+ for (let k = open; k <= last; k += 1) {
+ const c = src[k];
+ if (CLOSERS[c] !== undefined) {
+ expected.push(CLOSERS[c]);
+ } else if (c === ')' || c === ']' || c === '}') {
+ if (expected.pop() !== c) return -1;
+ if (expected.length === 0) return k + 1;
+ } else if (c === '"' || c === "'") {
+ const end = stringEnd(src, k, last);
+ if (end === -1) return -1;
+ k = end - 1;
+ } else if (c === '/') {
+ const end = commentEnd(src, k, last);
+ if (end === -1 || end > last) return -1;
+ k = end - 1;
+ } else if (c === '`' || c === '<' || c === '\\') {
+ return -1;
+ }
+ }
+ return -1;
+}
+
+// The type parameters that start at the `<` at `open`, read where the list is names and commas — what a signature's `<T>` and `<T, U>` are — and told from the text of an element that starts with a tag: { end } is the index
+// just past the `>` of a list that may be one, { fails } where what stands in it is no list's, and null where this does not say (it is not closed before `to`, or holds a constraint, a default, a modifier or a character
+// that is read no further). A name must be followed by `,` or `>`, or `extends` or `=`, which begin what is not read here: anything else is TS1005, and so is anything but a name where one must stand (TS1003)
+// (parseTypeParameter, parseBracketedList, https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts).
+// <T> <T, U> <T,> <> lists: after one, only a parameter list may follow
+// <b/> <b x="1"> <b x> <1> <"a"> no list: a `/`, a second name, a string, a number
+function typeParameterList(src, open, to) {
+ let k = skipSpaceAndComments(src, open + 1);
+ let named = false;
+ for (;;) {
+ if (k >= to) return null;
+ const c = src[k];
+ if (c === '>') return { end: k + 1 };
+ if (c === ',') {
+ if (!named) return null;
+ named = false;
+ k = skipSpaceAndComments(src, k + 1);
+ continue;
+ }
+ if (c === '=' || c === '<' || c === '\\' || (c.charCodeAt(0) > 0x7f && !isTrivia(c))) return null;
+ if (!/[A-Za-z_$]/.test(c)) return { fails: true };
+ let end = k + 1;
+ while (end < src.length && /[A-Za-z0-9_$]/.test(src[end])) end += 1;
+ const after = src[end];
+ if (after === '\\' || (after !== undefined && after.charCodeAt(0) > 0x7f && !isTrivia(after))) return null;
+ const word = src.slice(k, end);
+ if (word === 'extends') return named ? null : { fails: true };
+ if (named) return { fails: true };
+ // A modifier may stand before the name (`<const T>`, `<in out T>`: parseTypeParameter takes every one, and only the checker objects), and a reserved word is no name.
+ if (word === 'const' || PARAMETER_MODIFIERS.has(word) || RESERVED_WORDS.has(word)) return null;
+ named = true;
+ k = skipSpaceAndComments(src, end);
+ }
+}
+
+// Whether the `typeof` that ends at `end` is followed by `import`, through white space and comments: an import type, `typeof import('m')`, and not a type query (`typeof A.import`, whose `import` is a name, is read by the
+// qualified-name state). An import type needs its `(` and has no line-break rule before it (isStartOfTypeOfImportType, parseImportType), so the `(` may stand on a line of its own:
+// m: typeof import
+// ('./m') the import type's `(`, and no signature's parameter list
+// Read as a type that ends with `import` — a type query's name — the `(` at the start of the next line would be the parameter list of a call signature, which no string starts, and the text would be said to be no type's.
+function typeofImport(src, end) {
+ const at = skipSpaceAndComments(src, end);
+ return src.startsWith('import', at) && !isProseWordChar(src[at + 6] || ' ');
+}
+
+// Whether the text after a call or construct signature's `)` cannot be the members of a type, as far as it has been read: `prose` is the reading, which has come to `prose.at` and goes on to `to`, where
+// something that could hide the closing tag opens (a string, a template, a comment, a regex). It is asked at each of those until it says yes or reads something it cannot follow, so that comments, which
+// are trivia to a type and say nothing of its members, are read through. Where no type can be valid up to there, no program has one that holds the closing tag in anything, and nothing after it hides it.
+// A member is a name — an identifier, a keyword, a string or a number — and then `?`, `:` and a type, or the parameters of a signature, and a member ends at `,`, `;` or the end of its line (parseTypeMember,
+// parseTypeMemberSemicolon, https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts). The reading is where a member is — it begins, has a name, a `:`, a type, an initializer — and a type has no
+// expression in it, so a `/` that starts no comment is an error wherever one must not be. Each of the `PROSE_*` states is a place, and what fails there is TypeScript's: every character set below was measured over every
+// ASCII character against its parser, and a rule that is wrong is found by the sweeps in tests/source-literals.test.js (every text of a vocabulary, draws, runs of members, every keyword in each place a word may stand).
+// It fails
+// - at a second name on a line, or a name after a type: what follows a name on its line is `:`, `?`, `(`, `<`, a separator or the line's end, so a name, a string, a `[`, a `.`, a `!`, a sign, `&`, `|`, `>`, `@` or a
+// backslash after one is TS1005 (a `.` that continues a number is none: `1.5`, and `1e+5` is one name), and after a type on its line so is a keyword — but `extends` and `is` — a sign, a bracket, a `:`;
+// - at a `:` after a `:` or at the start of a member, and at a `/` that starts no comment where a type must be (TS1110, "Type expected"), after a name or a type (it divides in an expression, where a name may stand and a member
+// does not) and where a member begins (TS1131, "Property or signature expected"), as does a sign, an operator, a closing bracket, `=`, `?`, `!`, `.`, `@`, `#`, `>` or `{` there; where a type must be, `,`, `;`, `||`,
+// `&&`, `=`, `@` and a sign that no number follows are TS1110; and at a `/` right after a `[` that follows a `:` or a type, which is a tuple's or an indexed access's first type (`Total: [ // note` and a line break, then `/docs`);
+// - on the line after a name — `m` and a line break, then `&`, `|`, `.`, `!`, `>`, `@` or a sign — or after a type, which may go on with `&`, `|` and `.` and an initializer's `=` but not with a `:`, a `?`, `!`, `>`, `@`
+// or `||`: the member before it goes on only with what a name or a type goes on with (PROSE_LINE, PROSE_LINE_TYPE), and says nothing of `:`, `?`, `=`, `(`, `<` after a name;
+// - at a template or a string that opens at `to`, where no member has one: where a member begins or right after a name (after a `:` a template is a type, `m: \`a${string}\``, and a string is one), and at a
+// string that no quote closes on its line (TS1002);
+// - at `</`, which is one token in a .tsx file (TS1131 and TS1005 wherever a member or a type may stand), and at a `<` and a list of type parameters (typeParameterList) that no parameter list follows (parseSignatureMember);
+// - in an initializer (PROSE_INIT, PROSE_OPERAND: `=` after a name or a type): at a second operand beside the first on its line when no keyword is either of them (TS1005; TS_KEYWORDS is every keyword TypeScript has, as
+// any of them may be an operator).
+// A keyword is a name where a member begins, unless it may be a modifier (MODIFIER_WORDS): that is a name if no name follows it, and a modifier if one does (PROSE_MODIFIER: `readonly` and a line break, then `/`, and
+// `readonly x`, are read alike; every modifier a name may follow, and a `/` after one is TS1131 whichever it is). After a `:` a keyword is a type, or an operator that a type must follow (TYPE_PREFIX_WORDS: `keyof T`).
+// A group of brackets that is read to its end (bracketEnd) is one thing: after the start of a member a `(…)` is a signature's parameters, and a `[…]` an index signature or a computed name, which a name that follows
+// on the line fails; after a `:` either is a type, and a `[…]` after a type is an array or an indexed access. A type goes on with `.`, `|` and `&` (a type must follow). A group that is not closed on its line is read
+// as far as TypeScript's parser decides it: a `(` after a name or a keyword opens a parameter list, whose first parameters fail as a head's do (parameterListMayStart, parameterSyntaxFails) — but not the `(` of an import type,
+// `typeof import` or `import` and a line break, then `('m')`, which has no line-break rule (typeofImport) — and a `[`, a name and a `,` or a `:` are an index signature for certain, which no `/` follows
+// (indexSignatureThenSlash) — but not after `get` or `set`, whose `[` begins an accessor's computed name, `get [a, /x/]()` (lastWord). A name, a number, a string or a signature with a `=` right after it on its line is no member (`bare`: TS1131, and TS1005 after
+// a signature); after a `?`, a type, a computed name, `get` or `set`, or a line break, the `=` is an initializer, which the parser accepts and the checker rejects. Anything else leaves the rest undecided (false) —
+// a `[` that nothing closes, an initializer after a `?` or a type, a conditional type, an expression, a decorator — and the closing tag may be hidden there:
// (a), see https://x.y `see` and `https`, two names on a line
+// (a); https://x.y a name, a colon, and a comment: a type that a later line gives the name; nothing fails yet ...
+// /b ... and then a `/` where a type must be
+// (a), Docs: https://x.y a name, a colon, a type, and a second colon
+// (a), default: https://x.y the same, with a keyword for the name
+// (a); [x] https://x.y a computed name and a second name
+// (a); (x): https://x.y a signature, its return type, and a second colon
+// (a); 'x': https://x.y a string for a name, a type and a second colon
+// (a); 1.5 https://x.y a number for a name and a second name
+// (a); readonly https://x.y a modifier and a name, then a colon: the type that must follow is the `/` after the comment
+// (a); well-known // note a name and a sign
// (a); and/or more a name and a `/`
+// (a); x! // note a name and a `!`
+// (a); || // note a sign where no member begins
+// (a); <b>y</b> type parameters and no parameter list
// (a), see 'x a name and the string that opens at `to`
// (a); `x ${y} a template where a member begins
-function typeMembersFail(src, from, to, opener) {
- let named = false; // a member's name was read on this line
- let k = from;
- while (k < to) {
+// (a), m a name, a line break, and `&"x"`: a name is no type to go on
+// (a); m: A.B default // note a type that goes on with a name, a keyword
+// (a); m: A = 1 https://x.y an initializer's operand and a second one
+// (a); x = 1 // note a name and an `=` right after it: no member
+// (a); foo( // note a parameter list, and a `/` after the comment that follows its `(`: TS1138 (and a line break, then `/docs`)
+// (a); [ k, // note an index signature, and a `/` after the comment that follows its `,`: TS1138
+function typeMembersFail(src, prose, to, opener) {
+ // Nothing more is said once something that is no plain prose was read, nor of an opener inside a group of brackets that was read to its end past it (a default value's template, `(a = \`x</p>\`)`), which is the type's too.
+ if (prose.state === PROSE_OTHER || prose.at > to) return false;
+ let k = prose.at;
+ let state = prose.state;
+ // Whether the name the line is at was read with no `?` after it and is no computed name: a plain name, a number, a string, or a signature (`bare`).
+ let bare = prose.bare === true;
+ // The word that was read last with nothing but white space and comments since (null after any other token): a `[` after `get` or `set` begins an accessor's computed name, whatever its line (parseContextualModifier,
+ // canFollowGetOrSetKeyword: no line-break rule), and not an index signature.
+ let lastWord = prose.lastWord || null;
+ while (state !== PROSE_OTHER && k < to) {
const c = src[k];
+ const wordBeforeThis = lastWord;
+ if (!isTrivia(c) && !(c === '/' && (src[k + 1] === '/' || src[k + 1] === '*'))) lastWord = null;
+ const begins = state === PROSE_START || state === PROSE_LINE || state === PROSE_LINE_TYPE || state === PROSE_SIGNATURE;
+ const named = state === PROSE_NAME || state === PROSE_MODIFIER;
+ const initial = state === PROSE_INIT || state === PROSE_OPERAND;
+ // What a line break does: it ends the line a name or a type is on, where a member may begin or the one before it may go on, and it leaves an initializer undecided (an expression goes on over it, or ends at it).
+ const afterLineBreak = () => (named ? PROSE_LINE : state === PROSE_TYPE ? PROSE_LINE_TYPE : initial ? PROSE_OTHER : state);
if (isTrivia(c)) {
- if (isLineTerminator(c)) named = false;
+ if (isLineTerminator(c)) state = afterLineBreak();
k += 1;
- } else if (/[\w$]/.test(c)) {
- let end = k;
- while (end < to && /[\w$]/.test(src[end])) end += 1;
- if (named) return true;
+ } else if (c === '/') {
+ if (src[k + 1] !== '/' && src[k + 1] !== '*') {
+ // Where a type is, a `/` is an error. Where an initializer is, it divides, or starts a regex.
+ if (!initial) return true;
+ state = PROSE_OTHER;
+ } else {
+ // A comment is trivia: the line break at the end of a `//` comment is read as one (the next step), and a `/* */` comment that holds one is a line break too (scanner.ts, scan).
+ const end = commentEnd(src, k, to - 1);
+ for (let m = k; m < end; m += 1) if (isLineTerminator(src[m])) state = afterLineBreak();
+ k = end;
+ }
+ } else if (state === PROSE_TPARAMS && c !== '(') {
+ return true;
+ } else if (c === '#' && !isPrivateNameStart(src[k + 1])) {
+ // A `#` that no name follows is an invalid character (TS1127, scanner.ts scan); one that a backslash follows may start a name written with an escape, which is not read.
+ if (src[k + 1] !== '\\') return true;
+ state = PROSE_OTHER;
+ } else if (isProseWordChar(c) || (c === '.' && isDigit(src[k + 1])) || c === '#') {
+ let end = k + 1;
+ if (isDigit(c) || c === '.') end = numericLiteralEnd(src, k, to);
+ else while (end < to && isProseWordChar(src[end])) end += 1;
const word = src.slice(k, end);
- if (RESERVED_WORDS.has(word) || CONTEXTUAL_WORDS.has(word) || MEMBER_MODIFIERS.has(word)) return false;
- named = true;
+ lastWord = word;
k = end;
+ if (state === PROSE_QUALIFIED) {
+ // Every word is a name after a `.` in a type, a keyword too (`A.new`, `A.keyof`, `A.unique`: parseRightSideOfDot takes identifier names), and after `typeof` (an entity name), and no operator that a type follows.
+ state = PROSE_TYPE;
+ continue;
+ }
+ if (state === PROSE_OPERATOR) {
+ // After `keyof` and the like, a type: another of those words is an operator again, `typeof` takes a name, and any other word is the type, a keyword too (`keyof new` is the keys of a type named `new`). A word that
+ // starts a type that a word may follow (`asserts b` is a type predicate in any type) is not read.
+ state = TYPE_PREFIX_WORDS.has(word) ? PROSE_OPERATOR : word === 'typeof' && typeofImport(src, k) ? PROSE_COLON : word === 'typeof' || word === 'infer' ? PROSE_QUALIFIED : TYPE_OPERATOR_WORDS.has(word) ? PROSE_OTHER : PROSE_TYPE;
+ continue;
+ }
+ if (state === PROSE_NAME) return true;
+ if (initial) {
+ // Two operands side by side are an error whatever they are (TS1005), unless a keyword stands between them or is one of them: `typeof a`, `a in b`, `new A`.
+ if (TS_KEYWORDS.has(word)) state = PROSE_OTHER;
+ else if (state === PROSE_OPERAND) return true;
+ else state = PROSE_OPERAND;
+ } else if (RESERVED_WORDS.has(word) || CONTEXTUAL_WORDS.has(word) || MEMBER_MODIFIERS.has(word)) {
+ if (begins || state === PROSE_MODIFIER) {
+ state = MODIFIER_WORDS.has(word) ? PROSE_MODIFIER : PROSE_NAME;
+ bare = true;
+ }
+ // After a `:` a keyword is a type's name, or an operator that a type follows (`keyof T`, `typeof x`, `unique symbol`, `new (x)`): the ones that must have an operand leave a type to follow, and the others (`abstract`,
+ // `asserts`, `function`) may be a type on their own or go on, which is not read. After a type, on its line, only `extends` (a conditional type) and `is` (a type predicate, which a return type has) are no error (TS1005).
+ else if (state === PROSE_COLON) state = word === 'typeof' && typeofImport(src, k) ? PROSE_COLON : word === 'typeof' || word === 'infer' ? PROSE_QUALIFIED : TYPE_PREFIX_WORDS.has(word) ? PROSE_OPERATOR : word === 'new' || word === 'import' ? PROSE_COLON : TYPE_OPERATOR_WORDS.has(word) ? PROSE_OTHER : PROSE_TYPE;
+ else if (state === PROSE_TYPE && word !== 'extends' && word !== 'is') return true;
+ else state = PROSE_OTHER;
+ } else if (state === PROSE_TYPE) return true;
+ else {
+ state = state === PROSE_COLON ? PROSE_TYPE : PROSE_NAME;
+ bare = true;
+ }
+ } else if (c === ':') {
+ // A `:` follows a name, on its line or the next (`m\n: T` is a member). After a `:` where a type must be it is TS1110, and after a type, on its line or the next, TS1005, and where a member begins and no member goes
+ // on, TS1131. Where one may go on — after a line break that follows a name — the type is what must follow.
+ if (state === PROSE_COLON || state === PROSE_TYPE || state === PROSE_LINE_TYPE || state === PROSE_START) return true;
+ state = named || state === PROSE_LINE ? PROSE_COLON : PROSE_OTHER;
+ k += 1;
} else if (c === ',' || c === ';') {
- named = false;
+ // Where a type must be, or a name after a `.` or after the operator of a type, either is TS1110 or TS1003.
+ if (state === PROSE_COLON || state === PROSE_QUALIFIED || state === PROSE_OPERATOR) return true;
+ state = PROSE_START;
+ k += 1;
+ } else if ((named || state === PROSE_LINE) && c === '?') {
+ state = PROSE_NAME; // an optional member: `name?`, and `:` may follow, on its line or the next. No modifier is followed by one, so the word was the name.
+ bare = false;
+ k += 1;
+ } else if (state === PROSE_NAME && bare && c === '=' && src[k + 1] !== '>' && src[k + 1] !== '=') {
+ // A name, a number or a string, or a signature, with a `=` right after it on its line is no member: the parser takes a name for a member's only where `?`, `:`, `(`, `<`, `,` or the end of the line follows it (isTypeMemberStart,
+ // TS1131), and a signature wants its `;` (TS1005). Where a `?` stands before the `=` (`m? = 1`), the name is a computed one (`[x] = 1`) or a line break comes first (`m` and `= 1`), the initializer is kept for the checker, and is read below.
+ return true;
+ } else if ((named || state === PROSE_TYPE || state === PROSE_LINE || state === PROSE_LINE_TYPE) && c === '=' && src[k + 1] !== '>' && src[k + 1] !== '=') {
+ state = PROSE_INIT; // an initializer, which TypeScript parses for a property signature and leaves to the checker (`m` and `= 1`, `m: A` and `= 1`)
+ k += 1;
+ } else if ((c === '|' || c === '&') && src[k + 1] === c && (state === PROSE_COLON || state === PROSE_TYPE || state === PROSE_LINE_TYPE)) {
+ return true; // `||` and `&&` are one token each: a type may begin with a `|` or a `&`, and goes on with one, but not with these (TS1110, TS1005)
+ } else if ((state === PROSE_TYPE || state === PROSE_LINE_TYPE) && (c === '.' || c === '|' || c === '&')) {
+ state = c === '.' ? PROSE_QUALIFIED : PROSE_COLON; // a type goes on with `.A`, `| A` and `& A`, on its line or the next, and what follows must be a type (a name, after a `.`)
k += 1;
+ } else if (state === PROSE_COLON && (c === '|' || c === '&')) {
+ k += 1; // a leading `|` or `&`: a type must still follow
+ } else if (c === '"' || c === "'") {
+ // A string names a member where one begins, is a type after a `:`, and is an initializer's operand after a `=`; after a name, a type or an operand it is TS1005, and one that no quote closes on its line is TS1002
+ // wherever it stands. One that is read past `to` has an opener in it, which is not asked of.
+ const end = stringScan(src, k, prose.last);
+ if (end === -2 || end > to) state = PROSE_OTHER;
+ else if (end === -1 || state === PROSE_NAME || state === PROSE_TYPE || state === PROSE_OPERAND) return true;
+ else {
+ state = state === PROSE_COLON || state === PROSE_QUALIFIED || state === PROSE_OPERATOR ? PROSE_TYPE : state === PROSE_INIT ? PROSE_OPERAND : PROSE_NAME;
+ bare = true;
+ k = end;
+ }
+ } else if (c === '(' || c === '[') {
+ // The parameters of a signature, or a name that a signature follows (`m(x)`, `see (x)`), after the start of a member or a name; a parenthesised type or a function type's parameters after a `:`. A `[` is the name
+ // of an index signature or a computed property at the start of a member, which a name on the same line fails (TS1131), and a tuple, an array or an indexed access in a type.
+ let after = PROSE_OTHER;
+ if (c === '(') after = begins || named || state === PROSE_TPARAMS ? PROSE_NAME : state === PROSE_COLON ? PROSE_TYPE : PROSE_OTHER;
+ else if (state === PROSE_NAME) return true;
+ else after = begins || state === PROSE_MODIFIER ? PROSE_NAME : state === PROSE_COLON || state === PROSE_TYPE ? PROSE_TYPE : PROSE_OTHER;
+ // A signature's parameter list starts with a parameter or the `)`, and its first parameters are read the way a head's are (parameterListMayStart, parameterSyntaxFails): a `/` right after the `(` and its comments, a number,
+ // a string or an operator there, or two names, is no list in any signature, whether the `)` is found or not. So a text whose list cannot be one is no type's — `foo( // note` and a line break, then `/docs`: TS1138 at the `/`.
+ if (c === '(' && after === PROSE_NAME && (!parameterListMayStart(src, k) || parameterSyntaxFails(src, k))) return true;
+ if (c === '[' && after === PROSE_NAME && wordBeforeThis !== 'get' && wordBeforeThis !== 'set' && indexSignatureThenSlash(src, k)) return true;
+ // After a `:` or a type the `[` opens a tuple or an indexed access, whose first token is a type, and no type starts with a `/` that begins no comment (TS1110): `Total: [ // note` and a line break, then `/docs`.
+ if (c === '[' && after === PROSE_TYPE && src[skipSpaceAndComments(src, k + 1)] === '/') return true;
+ const end = after === PROSE_OTHER ? -1 : bracketEnd(src, k, prose.last);
+ state = end === -1 ? PROSE_OTHER : after;
+ bare = c === '('; // a computed name or an index signature (`[x] = 1`) keeps its initializer, a signature does not
+ if (end !== -1) k = end;
+ } else if (c === '<') {
+ // `</` is one token in a .tsx file, which no member, name or type has; `</*` is a `<` and a comment.
+ if (src[k + 1] === '/' && src[k + 2] !== '*') return true;
+ const list = begins || named ? typeParameterList(src, k, to) : null;
+ if (list !== null && list.fails) return true;
+ state = list === null ? PROSE_OTHER : PROSE_TPARAMS;
+ if (list !== null) k = list.end;
+ } else if (state === PROSE_COLON && c === '-') {
+ // A `-` where a type must be is the sign of a number (`m: -1`, TypeScript's isStartOfType looks past trivia for a numeric literal), and an error (TS1110) where no number follows.
+ const next = skipSpaceAndComments(src, k + 1);
+ if (next >= to) state = PROSE_OTHER;
+ else if (isDigit(src[next]) || (src[next] === '.' && isDigit(src[next + 1]))) k += 1;
+ else return true;
+ } else if (state === PROSE_START || state === PROSE_SIGNATURE ? STARTS_NO_HARD_MEMBER.includes(c)
+ : state === PROSE_LINE ? NO_NEXT_LINE_AFTER_NAME.includes(c)
+ : state === PROSE_LINE_TYPE ? NO_NEXT_LINE_AFTER_TYPE.includes(c)
+ : state === PROSE_NAME ? NO_AFTER_NAME.includes(c)
+ : state === PROSE_TYPE ? STARTS_NO_MEMBER.includes(c)
+ : state === PROSE_COLON ? NO_START_OF_TYPE.includes(c)
+ : state === PROSE_MODIFIER && NO_AFTER_MODIFIER.includes(c)) {
+ return true;
} else {
- return c === '/' && named && src[k + 1] !== '/' && src[k + 1] !== '*';
+ state = PROSE_OTHER;
}
}
- // Only an opener after the parameter list stands where a member does: one inside it (a default value's template, `(a = \`x</p>\`)`) is the type's too.
- if (from <= to && (opener === '`' || (opener === '/' && src[to + 1] !== '/' && src[to + 1] !== '*'))) return true;
- return named && (opener === '"' || opener === "'");
+ prose.at = k;
+ prose.state = state;
+ prose.bare = bare;
+ prose.lastWord = lastWord;
+ // A group of brackets that ends after `to` has the opener inside it.
+ if (state === PROSE_OTHER || k > to) return false;
+ // An initializer: a `/` divides or starts a regex and a template may be tagged, but a string right after an operand is an error.
+ if (state === PROSE_INIT || state === PROSE_OPERAND) return state === PROSE_OPERAND && (opener === '"' || opener === "'");
+ if (opener === '`') return state === PROSE_START || state === PROSE_LINE || state === PROSE_LINE_TYPE || state === PROSE_SIGNATURE || state === PROSE_NAME || state === PROSE_MODIFIER || state === PROSE_TPARAMS;
+ if (opener === '"' || opener === "'") return state === PROSE_NAME || state === PROSE_TPARAMS;
+ return opener === '/' && src[to + 1] !== '/' && src[to + 1] !== '*';
}
// Whether the quote at `at` comes right after a word that is no keyword: an apostrophe in prose (`it's`) or an inch mark (`5" wide`). A type has no string right after a name or a number — what follows
@@ -1322,7 +1732,9 @@ function quoteEndsAWord(src, at) {
let start = at;
while (isTagNamePart(src[start - 1])) start -= 1;
if (start === at) return false;
- const word = src.slice(start, at);
+ let word = src.slice(start, at);
+ // A hex, binary or octal literal and a word right after it are two tokens (`0x1Fin'a'`: see numericLiteralEnd), and the word is the one that a string may follow.
+ if (/^0[xXbBoO]/.test(word)) word = word.slice(numericLiteralEnd(word, 0, word.length)) || word;
return !RESERVED_WORDS.has(word) && !CONTEXTUAL_WORDS.has(word) && !MEMBER_MODIFIERS.has(word);
}
@@ -1574,6 +1986,100 @@ function readTag(src, at, arrow, closing = false) {
}
}
+// A tag whose name starts at `at` and whose `>` is at `close`: whether it can be something other than the opening tag of an element, as it is where the text is read as the members of a type — the type arguments of a name
+// (`Array<b>`, `Array<keyof X>`), a comparison (`x < b > y`, `x < a in b > y`, `x < typeof U > y`), the type parameters of a signature (`<U extends A>`, `<U = 'x'>`, `<in out U>`, `<const U>`, `<public U>`: parseTypeParameter takes every
+// modifier a member may have, and only the checker objects; https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts).
+// What stands in it is read as the attributes of a tag are: names, `=` and a string or a container. It may be code when
+// - it is one word, which is a type, a name or a type parameter, with a default or none;
+// - a keyword stands in it that no value follows (hasKeywordPart): a modifier of a type parameter, an operator of a type (`keyof`, `typeof`, `readonly`, `unique`, `infer`, `asserts`) or of an expression (`new`, `void`, `delete`, `await`, and the
+// infix `in`, `instanceof`, `as`, `satisfies`, `is`). A keyword that has a value (`type="button"`, `as="span"`, `for="x"`) is an attribute in every reading that keeps the tag on one line: no comparison or type has a `=`, and a type
+// parameter's default, the one place that does, belongs to its name or the last word of its constraint, which the other readings below see;
+// - a line break stands between a word and its `=` (`href` and a line break, then `="/x"`), or before a `get` or a `set` that has a value (`get="x"`): where the tag is inside the members of a type, a line break ends a member
+// (canParseSemicolon, parseTypeMemberSemicolon), and each line after it is a member of its own, so the tag is no attribute list there:
+// m: A = x <a the initializer `x < a` ends at the line break
+// href a member named `href`,
+// ="/x"> '</a>' + '</T>…' whose `=` takes an initializer, `"/x" > '</a>' + '</T>…'` (parsePropertyOrMethodSignature reads one after any name, and has no line-break rule before it)
+// A name and its `=` on one line are no member (isTypeMemberStart: TS1131), but `get` and `set` are: isTypeMemberStart takes either for the start of a member before it looks at what follows, so `get="/x"` on a line of its own is
+// a property named `get` with an initializer;
+// - it has the shape of a type parameter: some modifiers, a name, `extends` and a constraint, and `=` and a default.
+// So a name that `extends` does not introduce, a value before the `extends`, a value that is not the last word's, or a dotted name that anything follows is an element's attribute and no type's when no keyword is in it and no line break
+// stands before an `=` or a valued `get` or `set`: `<a href="/x">`, `<b d="//">`, `<button type="button">`. Anything that is not read here (a `<`, a comment, a spread) leaves it possible.
+// <b> <A.B> <U extends A> <U extends A = 'x'> <in out U> <const U> <public U> <keyof x> <a in b> <A.B as T> <U = {x}> <a⏎href⏎="/x"> <a⏎get="x"> (not: <a href="/x"> <b d> <button type="button"> <U = 'x' extends A> <A.B x>)
+// Whether a word of a tag holds a keyword, once it is split at the dots and dashes that the words of a tag may hold (`A.in`, `data-in`). `extends` is read on its own, by the shape of a type parameter.
+const hasKeywordPart = (word) => word.split(/[.-]/).some((part) => part !== 'extends' && TS_KEYWORDS.has(part));
+function tagMayBeCode(src, at, close) {
+ let k = tagNameEnd(src, at);
+ const words = [src.slice(at, k)];
+ const valued = [false];
+ let lineBreak = false; // a line break was read since the last token (a word, a `=` or a value)
+ let wordStartsLine = false; // ... and stood before the last word
+ while (k < close) {
+ const c = src[k];
+ if (isTagSpace(c)) {
+ // LF and CR are the line breaks in a tag's white space. U+2028 and U+2029 are no tag space (isTagSpace), nor are U+0085 and U+00A0: they reach the `return true` below, and leave the tag possible code.
+ if (c === '\n' || c === '\r') lineBreak = true;
+ k += 1;
+ } else if (c === '=') {
+ // A line break before the `=`, or before a valued `get` or `set`, makes the tag the members of a type (see above).
+ if (lineBreak) return true;
+ const word = words[words.length - 1];
+ if (wordStartsLine && (word === 'get' || word === 'set')) return true;
+ k += 1;
+ while (k < close && isTagSpace(src[k])) k += 1;
+ if (src[k] === '"' || src[k] === "'") {
+ const end = src.indexOf(src[k], k + 1);
+ if (end === -1 || end > close) return true;
+ k = end + 1;
+ } else if (src[k] === '{') {
+ let depth = 0;
+ let end = k;
+ for (; end < close; end += 1) {
+ if (src[end] === '{') depth += 1;
+ else if (src[end] === '}' && --depth === 0) break;
+ }
+ if (depth !== 0) return true;
+ k = end + 1;
+ } else {
+ return true;
+ }
+ valued[valued.length - 1] = true;
+ } else if (isTagNameStart(c)) {
+ let end = k + 1;
+ while (end < close && (isTagNamePart(src[end]) || src[end] === '-')) end += 1;
+ words.push(src.slice(k, end));
+ valued.push(false);
+ wordStartsLine = lineBreak;
+ lineBreak = false;
+ k = end;
+ } else {
+ return true;
+ }
+ }
+ if (words.length === 1) return true;
+ // A modifier before a type parameter's name (`<in out U>`, `<const U>`, `<public U>`) is a keyword, so no word that reaches the lines below holds one.
+ if (words.some((word, m) => !valued[m] && hasKeywordPart(word))) return true;
+ if (words[0].includes('.')) return false;
+ if (words[1] !== 'extends' || valued[0] || words.length === 2) return false;
+ for (let m = 2; m < words.length - 1; m += 1) if (valued[m]) return false;
+ return true;
+}
+
+// Whether the fragment `<>` at `open`, whose `>` is the character before `after`, may be code: an empty list of type parameters or of type arguments, which TypeScript parses and leaves to the checker (TS1098 and TS1099 are
+// checker errors, so a page with one has no parse diagnostic). Type parameters stand before a parameter list, and type arguments after a name or after the end of an operand — and before a parameter list or a template, or not
+// before anything in particular (`f(x)<>;` is an instantiation expression):
+// interface I { <>(y); m<>(y); new <>(y) } m: A<> f<>(1) f(x)<> || 1 a[0]<> x <>`t` class C<> {} a?.<>(1) 1.<> || 1
+// Anywhere else a `<>` is a fragment, and no type reads it: after an operator, a separator or an opening bracket, and after a `>` that ends a tag. The character before it is read as written (comments are not skipped: a `/` there may end a
+// block comment, and is taken for the end of an operand), and a `.` is an operand's end as well: the end of a number (`1.`) or of an optional chain (`a?.<>(1)`).
+// Where a line break stands before the fragment, the character before it may be the last one of a line comment, whatever it is, and the operand is what stands before the comment: `f // note:` and a line break, then `<> || …` is the
+// instantiation expression `f<> || …`, and its text opens no element. That is told as it is for a `/` after a comment (lineMayEndInComment): a line that has no `//` before the character is read as written.
+function fragmentMayBeList(src, open, after) {
+ const prev = prevSignificant(src, open);
+ if (prev.newline && lineMayEndInComment(src, prev.index)) return true;
+ if (/[\w$)\]}'"`!\\/.]/.test(prev.ch) || prev.ch.charCodeAt(0) > 0x7f) return true;
+ const next = src[skipSpaceAndComments(src, after)];
+ return next === '(' || next === '`';
+}
+
// The reading of the text that starts at `from` — just past the `>` of `<Name>` — as the children of an element, token by token, the way TypeScript's parser reads them (see above). It stops at the
// first character TypeScript rejects, and it is asked two things, which differ in where the text ends:
// `closing` null up to and including the `>` of the `=>` at `arrow`: is the text of `<Name>(…) =>` an element? A `>` or `}` in the text is the error, so reaching the arrow's own `>` in text is
@@ -1584,17 +2090,63 @@ function readTag(src, at, arrow, closing = false) {
// a container, tag or closing tag this does not read, or the end of the window. `hideable` is set where the closing tag could be inside a string, a template, a comment or a regex that the text
// opens, as part of a type that holds one, and not a closing tag at all. The text is scanned as the type would scan it, as code: a string that starts in it and ends after the closing tag (or may: the
// window ends first); a template that does (one with a `${` is code that is not read: it may); a comment, `//` to the end of its line or `/* */`, that does; and a `/` that is neither — a
-// regex, where one may start, is the one thing left that could — unless a word or a number stands before it, after which it divides, or is an error in a type (slashFollowsAnOperand). A quote with no
-// closing quote on its line is no string, and neither is one right after a word that is no keyword, an apostrophe or an inch mark (quoteEndsAWord). A nested tag's attribute strings and a container's
-// content are no text, and set nothing.
+// regex, where one may start, is the one thing left that could — unless a word or a number stands before it, after which it divides, or is an error in a type (slashFollowsAnOperand, with the comments that the text
+// opened: a comment is trivia, and the token before it is what the `/` follows). A quote with no closing quote on its line is no string, and neither is one right after a word that is no keyword, an apostrophe or an inch
+// mark (quoteEndsAWord). A nested tag's attribute strings and a container's content are no text, and set nothing. What the text of a nested element opens — a string, a template, a comment — and that is still open
+// at that element's closing tag takes the head's closing tag for hidden, as a type might read it: see skipUntil.
// An expression container is read for what it can be said to hold (containerFailsAt): an error, or nothing that matters, after which the text goes on.
function readChildren(src, from, last, arrow, closing) {
+ const read = scanChildren(src, from, last, arrow, closing, false);
+ // A string, a template or a comment that the text of a nested element opened and that is still open at the closing tag of an element that could be code has two readings of what follows (see skipUntil in
+ // scanChildren), and so has the pairing of the quotes after a tag that stands inside such a region (a ghost to the reading in which the region is code, an element's to the other). Such a place is read both ways, and the
+ // closing tag is hidden if either hides it; two crossings are taken for hidden, as the readings of the second depend on the choice made at the first.
+ if (read === null || read.closes === undefined || read.hideable || (read.crossed === 0 && !read.tagged)) return read;
+ const kept = scanChildren(src, from, last, arrow, closing, true);
+ // Both readings walk the same tags, so the closing tag that ends the element is the same: this guards a change that would make them differ, as the guess.
+ if (kept === null || kept.closes !== read.closes) return { closes: read.closes, hideable: true };
+ return { closes: read.closes, hideable: kept.hideable };
+}
+
+// readChildren's reading in one of the two ways that a nested element can be read where a region that its text opened crosses its closing tag: as an element, which ends the region there (`keep` false), or as code, in
+// which it goes on (`keep` true). { crossed } is how many such places the text has, and { tagged } says that a tag stood inside a region that the text of an element opened (in `keep`, such a tag is a ghost: the region
+// holds it as text).
+function scanChildren(src, from, last, arrow, closing, keep) {
const bound = closing === null ? arrow : last + 1;
const open = [];
let hideable = false;
- let hiddenUntil = 0; // the end of the furthest string, template or comment that the text opened
- let typeChecked = false; // the first thing in the text that could hide the closing tag was asked whether the type up to it can be valid (typeMembersFail)
- let typeDead = false; // ... and it cannot: nothing in the text hides the closing tag
+ let hiddenUntil = 0; // the end of the furthest string, template or comment that the text opened: a closing tag before it may be inside it
+ // Where the scan looks for what the text opens again (`skipUntil`: the end of the furthest region), and the depth (`realDepth`) of the opener of the region that ends there. A type reads a nested element `<b>…</b>` two
+ // ways. As an element (`m(a = <b>'x</b>)`), its text is JSX text, which holds no string, template or comment, and code goes on after its closing tag. As anything else — type arguments (`Array<b>`), a comparison
+ // (`x < b > y`), the type parameters of a signature (`<b>(y): T`) — the text after the `>` is code, which does, and the closing tag has no meaning there, so it is inside a string, a template or a comment that
+ // the text opened before it. The two read the rest alike, unless a region that the text of the element opened is still open at its closing tag: the quote that ends it in the second reading is an opener in the first
+ // (`<b>'x</b> + '</T>…'`, `Array<b> = '</b>' + '</T>…'`), and which of them holds the head's closing tag is for the type to say. The first reading ends the region at the closing tag (`keep` false) and the second
+ // keeps it (`keep` true), and readChildren asks both.
+ let skipUntil = 0;
+ let skipDepth = 0;
+ let skipFrom = -1; // where the region that ends at skipUntil starts: two regions may end at one place (two `//` comments on a line), and are two crossings
+ let crossed = 0; // how many regions a closing tag of a nested element that could be code is inside, where the text of that element opened them
+ let crossedFrom = -1; // where the region that the last of them was counted for starts: it crosses the closing tags of the elements around that one too, which are no more places to choose
+ let tagged = false; // a tag opened inside a region that the text of an element opened, which the reading where the region is code takes for text (a ghost): the two readings pair the quotes after it differently
+ const codeable = [];
+ // The elements of the text that are elements to every reading — a tag that is no code, which no region of the text covers — and how many are open: where one is, the text is JSX text, which holds no string, template, comment
+ // or regex, so that nothing in it opens anything (`<a href="/x">https://x.y</a>`, `<b title="t">it's</b>`).
+ const elements = [];
+ let jsxText = 0;
+ // A string, a template or a comment that the text opens where no element of the type's reading is open is a token in every reading of it, and a tag inside it is none to the type: `'a <b>' + \`</b>\` + '</T>…'` holds
+ // `<b>` and `</b>` in two literals, which the element reading takes for the tags of an element, and the type for strings. Such a tag — a ghost — opens and closes in the element reading (`open`), and in the other it is
+ // nothing: it adds nothing to `realDepth`, the number of elements of the type's reading that are open (a region that was opened at a greater depth than the one a closing tag brings the scan back to was opened inside the
+ // element that the tag closes: skipDepth). `certainUntil` is the end of the furthest such literal. Where the nested elements are read as code (`keep`), every region is such a literal: the tags in it are ghosts too.
+ const ghosts = [];
+ let realDepth = 0;
+ let certainUntil = 0;
+ // What the type that the text would be the members of can be, read as far as the text is plain prose (typeMembersFail): each thing that could hide the closing tag is asked whether that type can be valid up to
+ // it, until the answer is no (`typeDead`), which is the end of the question: no type holds the closing tag in anything, nothing that follows can hide it, and the text is an element.
+ const prose = closing !== null && closing.typeFrom >= 0 ? { at: closing.typeFrom, state: PROSE_SIGNATURE, last } : null;
+ let typeDead = false;
+ // The comments that the text opened, as a run: `//` to the end of its line and `/* */`, with nothing but white space and further comments between them, and the depth at which the run began. A comment is trivia to the
+ // type, so what follows the run is judged by what stands before it (slashFollowsAnOperand). Where the text of a nested element is the element's, the run that began in it is no comment, and ends with the element: the
+ // line comment ends at the closing tag, so a `/` after `x // y</b> +` and a line break follows the `+`, not `x`.
+ let comments = null;
let j = from;
while (j <= last) {
const c = src[j];
@@ -1608,7 +2160,7 @@ function readChildren(src, from, last, arrow, closing) {
continue;
}
if (c !== '<') {
- if (closing !== null && j >= hiddenUntil && !typeDead) {
+ if (closing !== null && j >= skipUntil && !typeDead && jsxText === 0) {
// What the text opens that a type reads as a token: a string, a template, a comment (a regex, where one may start) — the closing tag is hidden by one that is not closed before it. `hides`
// is 0 where this opens nothing that hides, -1 where it may, and the index just past it where it does.
let hides = 0;
@@ -1617,28 +2169,39 @@ function readChildren(src, from, last, arrow, closing) {
hides = end === -1 ? -1 : end;
} else if (c === '/') {
const end = commentEnd(src, j, last);
- if (end !== -1) hides = end;
- else if (!slashFollowsAnOperand(src, j)) hides = -1;
+ if (end !== -1) {
+ hides = end;
+ const run = commentRun(src, comments, j, end);
+ run.depth = realDepth;
+ comments = run;
+ } else if (!slashFollowsAnOperand(src, j, comments, true)) {
+ hides = -1;
+ }
} else if ((c === '"' || c === "'") && !quoteEndsAWord(src, j)) {
const end = stringScan(src, j, last);
hides = end === -2 ? -1 : Math.max(end, 0);
}
if (hides !== 0) {
- // The first thing that could hide the closing tag is asked whether the type that this text would be the members of can be valid up to it: where it cannot, no type holds the closing tag
- // in anything, nothing that follows can hide it, and the text is an element.
- if (!typeChecked) {
- typeChecked = true;
- typeDead = closing.typeFrom >= 0 && typeMembersFail(src, closing.typeFrom, j, c);
- }
+ if (prose !== null && typeMembersFail(src, prose, j, c)) typeDead = true;
if (!typeDead) {
- if (hides === -1) hideable = true;
- else hiddenUntil = Math.max(hiddenUntil, hides);
+ if (hides === -1) {
+ hideable = true;
+ } else {
+ hiddenUntil = Math.max(hiddenUntil, hides);
+ if (realDepth === 0) certainUntil = Math.max(certainUntil, hides);
+ if (hides > skipUntil) {
+ skipUntil = hides;
+ skipDepth = realDepth;
+ skipFrom = j;
+ }
+ }
}
}
}
j += 1;
continue;
}
+ const opensAt = j; // the `<` of a tag: it is a ghost where a literal that no reading of the type can end covers it
j += 1;
// `</` is one token to TypeScript's scanner in JSX text, with nothing between the two characters (scanner.ts, scanJsxToken); `< /b>` is no closing tag. What follows it is scanned as ordinary tokens, so
// a comment may stand before the name (`</ /* c */ b>`), but `</*` has none in it: the `/` is the token's, and the `*` is TS1003. (A type reads `</*` as a `<` and a comment.)
@@ -1649,8 +2212,28 @@ function readChildren(src, from, last, arrow, closing) {
const expected = open.length > 0 ? open[open.length - 1] : closing.name;
if (expected === null) return null;
if (tag.name !== expected) return { fails: j };
- if (open.length === 0) return { closes: tag.end, hideable: hideable || j - 1 < hiddenUntil };
+ if (open.length === 0) return { closes: tag.end, hideable: hideable || j - 1 < hiddenUntil, crossed, tagged };
open.pop();
+ const mayBeCode = codeable.pop();
+ if (elements.pop()) jsxText -= 1;
+ if (!ghosts.pop()) {
+ realDepth -= 1;
+ // A region that the text of this element opened and that is still open at its closing tag (a comment to the end of a line that holds the tag, a string or a template that ends after it): see skipUntil. A
+ // ghost's closing tag is inside the literal that holds its opening tag, so the regions that are open at it were opened outside the element. One that was kept at an element's closing tag holds the closing tags of the
+ // elements around it too, which are no more places to choose (`crossedFrom`: a region is told by where it starts, since two regions can end at one place — two `//` comments on one line). An element whose tag is no code has no region of its own to keep: its text opens none (jsxText), and a region that was open where it
+ // started holds its tags as text, which makes them ghosts in the reading that keeps it.
+ if (skipUntil > j - 1 && skipDepth > realDepth && skipFrom !== crossedFrom) {
+ if (mayBeCode) {
+ crossed += 1;
+ crossedFrom = skipFrom;
+ if (crossed > 1) hideable = true;
+ }
+ if (!mayBeCode || !keep) {
+ skipUntil = tag.end + 1;
+ if (comments !== null && comments.depth > realDepth) comments = null;
+ }
+ }
+ }
j = tag.end + 1;
continue;
}
@@ -1661,12 +2244,34 @@ function readChildren(src, from, last, arrow, closing) {
if (tag === null) return null;
if (tag.fails !== undefined) return { fails: tag.fails };
// A tag that is not self-closing opens an element, which a closing tag with its name closes.
- if (closing !== null && !tag.selfClosing) open.push(src.slice(j, tagNameEnd(src, j)));
+ if (closing !== null && !tag.selfClosing) {
+ open.push(src.slice(j, tagNameEnd(src, j)));
+ // A tag that stands inside a region is a ghost in the reading where the region is code (`keep`): the region holds it as text.
+ const ghost = opensAt < certainUntil || (keep && opensAt < skipUntil);
+ if (!keep && !ghost && opensAt < skipUntil) tagged = true;
+ ghosts.push(ghost);
+ const mayBeCode = tagMayBeCode(src, j, tag.resume - 1);
+ codeable.push(mayBeCode);
+ // An element whose tag is no code and that no region of the text covers is an element to every reading, and its text is JSX text, which opens nothing (jsxText).
+ const certain = !ghost && !mayBeCode && opensAt >= skipUntil;
+ elements.push(certain);
+ if (certain) jsxText += 1;
+ if (!ghost) realDepth += 1;
+ }
j = tag.resume;
continue;
}
if (closing !== null && next === '>') {
open.push(''); // a fragment, `<>`, which `</>` closes
+ const ghost = opensAt < certainUntil || (keep && opensAt < skipUntil);
+ if (!keep && !ghost && opensAt < skipUntil) tagged = true;
+ ghosts.push(ghost);
+ const fragmentMayBeCode = fragmentMayBeList(src, opensAt, j + 1);
+ codeable.push(fragmentMayBeCode);
+ const certain = !ghost && !fragmentMayBeCode && opensAt >= skipUntil;
+ elements.push(certain);
+ if (certain) jsxText += 1;
+ if (!ghost) realDepth += 1;
j += 1;
continue;
}
@@ -1712,12 +2317,18 @@ function elementChildren(src, from, name, budget = null, typeFrom = -1) {
// same. The parentheses are matched with comments and strings skipped, which is JavaScript's reading and not JSX's — the reason an arrow can be found where there is none.
// In a type the list is read exactly that way until something in it may start an expression (expressionMayStart: an initializer's `=`, a computed name's `[`, a decorator's `@`, an import
// type's attributes, an accessor's body, a type parameter's constraint). A type holds no regex, no JSX and no statement, so before one the `)` the scan finds is the type's, and a `/` that
-// starts no comment is in no type at all: the text is the element's. After one, the scan is still exact while it reads no `/`, `<` or back-tick — with no regex, no JSX and no template, every
-// quote opens a string and every parenthesis is code — and once it reads one, the expression may hold what the scan misreads (a regex with a `)` in it, JSX text, a template in a template),
-// so the `)` it finds is not trusted, and a list with no arrow after it is the guess (`interface I { <T>(a = /[)]/); m: '</T>…' }` ended the list at the `)` in the regex's class, and the
-// `]` after it read as the text of an element). A list whose parameters fail before any of that has no type reading either (parameterSyntaxFails).
+// starts no comment is in no type at all: the text is the element's. After one, the scan is still exact while it reads no `/`, `<` or back-tick that may start a regex, JSX or a template — with no regex, no JSX
+// and no template, every quote opens a string and every parenthesis is code — and once it reads one, the expression may hold what the scan misreads (a regex with a `)` in it, JSX text, a template in a
+// template), so the `)` it finds is not trusted, and a list with no arrow after it is the guess (`interface I { <T>(a = /[)]/); m: '</T>…' }` ended the list at the `)` in the regex's class, and the
+// `]` after it read as the text of an element). Three of those are read exactly instead, which is what keeps the guess for the rest (initializerReading, and the loop below):
+// - the default value's first token, where it is a regex or an element: `(a = /x/)`, `(a = <b>c</b>)` — a `/` right after the `=` begins a regex, which ends at its own `/` on the line, and a `<` there
+// an element, which the element reading follows to its closing tag (the `=` must be an initializer's, not a type parameter's default: no `<` was read before it);
+// - a `/` after a name or a number: it divides, in an expression (`(a = b/(c))`), so it opens no regex — unless a `{` has been read, which may open a function body where a statement starts, or a line
+// comment stands behind the name (`1 + // c` and a line break, then `/[)]/`: the comment is trivia, and the `/` begins a regex — slashFollowsAnOperand);
+// - a template with no `${`, which holds nothing but its own text, wherever it stands.
+// A list whose parameters fail before any of that has no type reading either (parameterSyntaxFails), and neither does one whose first default is `</`: no expression and no type starts with it.
// Parentheses followed by neither `=>` nor `:` are JSX text (`<b>(optional)</b>`) or a call signature with no return type: callSignatureOrElement says which, where it can.
-function genericFunctionTypeFollows(src, after, head, budget = null) {
+function genericFunctionTypeFollows(src, after, head, budget = null, noMember = false) {
const open = skipSpaceAndComments(src, after);
if (src[open] !== '(') return { generic: false, ambiguity: null };
// A list that can hold no parameters, or whose parameters fail before a type, a default, a pattern or a decorator, belongs to no signature and no function type: the text is an element,
@@ -1728,13 +2339,15 @@ function genericFunctionTypeFollows(src, after, head, budget = null) {
let k = open;
let expression = false; // something that may start an expression was read (expressionMayStart)
let unsafe = false; // ... and after it a `/`, a `<` or a back-tick: a regex, JSX or a template, which may hold what the scan misreads
+ let angle = false; // a `<` was read before it: type arguments or the type parameters of a function type, where an `=` is a default
+ let braces = false; // a `{` was read after it: it may open a function body, where a statement starts and a `/` after a `)` may begin a regex
for (; k < end; k += 1) {
const skipped = skipTrivia(src, k);
if (skipped !== k) {
if (src[k] === '`') {
// skipTrivia ends a template at its first back-tick, which may be the start of one nested in a substitution: ``(a: `${`)`}`)``.
if (!templateSkipIsWhole(src, k, skipped - 1)) return { generic: false, ambiguity: 'generic' };
- if (expression) unsafe = true;
+ if (expression && src.slice(k, skipped).includes('${')) unsafe = true;
}
k = skipped - 1;
continue;
@@ -1743,19 +2356,85 @@ function genericFunctionTypeFollows(src, after, head, budget = null) {
if (c === '(') depth += 1;
else if (c === ')' && --depth === 0) break;
else if (expression) {
- if (c === '/' || c === '<') unsafe = true;
+ if (c === '{') braces = true;
+ else if (c === '<' || (c === '/' && (braces || !slashFollowsAnOperand(src, k)))) unsafe = true;
} else if (expressionMayStart(src, k)) {
expression = true;
+ if (c === '=') {
+ const first = skipSpaceAndComments(src, k + 1);
+ // `</` is one token in a .tsx file, and no expression starts with it (TS1109, "Expression expected", for an initializer) and no type does (TS1110, for a type parameter's default): a list that
+ // holds an `=` and then a closing tag is no signature's, `(Tip: use <code>=</code>)`. `</*` is a `<` and a comment, and starts what a `<` does.
+ if (src[first] === '<' && src[first + 1] === '/' && src[first + 2] !== '*') return { generic: false, ambiguity: null };
+ const read = angle ? null : initializerReading(src, first, budget);
+ if (read !== null && read.fails) return { generic: false, ambiguity: null };
+ if (read !== null) k = read.resume - 1;
+ }
} else if (c === '/') {
// No type holds a `/` that starts no comment: only the element compiles (`<p>(see: /docs)</p>`, `<span>({done}/{total})</span>`).
return { generic: false, ambiguity: null };
+ } else if (c === '<') {
+ angle = true;
}
}
if (k >= end) return { generic: false, ambiguity: k >= src.length && !unsafe ? null : 'generic' };
const next = skipSpaceAndComments(src, k + 1);
if (src[next] === '=' && src[next + 1] === '>') return { generic: true, ambiguity: elementFailsAt(src, after, next) === -1 ? 'generic' : null };
if (src[next] === ':' || unsafe) return { generic: false, ambiguity: 'generic' };
- return callSignatureOrElement(src, after, head, k, next, budget);
+ return callSignatureOrElement(src, after, head, k, next, budget, noMember);
+}
+
+// The index of the `/` that closes the regex literal whose opening `/` is at `i`, as TypeScript's scanner finds it (scanner.ts, reScanSlashToken, https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/scanner.ts):
+// a `/` that no backslash escapes and no character class holds. A line break ends the line before one, and the literal is unterminated (TS1161) — and so does the end of the source: -1. -2 is where the window
+// ends first, which says nothing. (regexCloses asks the weaker question, whether one COULD close: it reads a backslash and a line break as an escape.)
+function regexEnd(src, i) {
+ const last = Math.min(src.length, i + LOOKAHEAD);
+ let escaped = false;
+ let inClass = false;
+ for (let j = i + 1; j < last; j += 1) {
+ const c = src[j];
+ if (isLineTerminator(c)) return -1;
+ if (escaped) escaped = false;
+ else if (c === '/' && !inClass) return j;
+ else if (c === '[') inClass = true;
+ else if (c === '\\') escaped = true;
+ else if (c === ']') inClass = false;
+ }
+ return last >= src.length ? -1 : -2;
+}
+
+// What the default value that starts at `first` — the token after an initializer's `=`, where an expression starts — is, where it can be read exactly: { fails } where no program that parses has it
+// (a regex that its line does not close, TS1161, which is the end of the text for TypeScript), { resume } — the index just past it — for a regex or an element, and null where the scan reads on:
+// a name, a number, a string, a bracket, and anything else it reads as it always has.
+// (a = /x/) a `/` right after the `=` has no operand to divide, so it begins a regex (a comment was passed over, and `/=` is a regex that starts with `=`): read to its closing `/`; its flags are name
+// characters, which the scan passes over
+// (a = <b>c</b>) a `<` there is an element (startsElement), read as the element reading follows one, to its closing tag: what it holds is text and expression containers, never the parenthesis that ends the list
+function initializerReading(src, first, budget) {
+ if (src[first] === '/') {
+ const closing = regexEnd(src, first);
+ if (closing === -2) return null;
+ return closing === -1 ? { fails: true } : { resume: closing + 1 };
+ }
+ if (src[first] !== '<') return null;
+ const end = nestedElementEnd(src, first, budget);
+ return end === -1 ? null : { resume: end };
+}
+
+// Whether the `<` at `at`, where an assignment expression starts, begins an element in every program that parses: it does where TypeScript's rule for a `<` there (parser.ts,
+// isParenthesizedArrowFunctionExpressionWorker, the JSX branch, which opensTypeParameters reads) says so with no guess.
+function startsElement(src, at) {
+ const rule = opensTypeParameters(src, at, null, true);
+ return !rule.generic && rule.ambiguity === null;
+}
+
+// The index just past the element that starts at the `<` at `at`, read as TypeScript reads one — the tag, its attributes and the children up to the closing tag that ends it (readTag, readChildren) — or -1 where
+// the `<` is not known to begin one (startsElement) or the element cannot be read to its end. A `<` that no tag name follows at once (`<>`, `< b>`) has no closing tag to look for (headTagName), and is never read to one.
+function nestedElementEnd(src, at, budget) {
+ if (!startsElement(src, at)) return -1;
+ const tag = readTag(src, at + 1, Math.min(src.length, at + LOOKAHEAD), true);
+ if (tag === null || tag.fails !== undefined) return -1;
+ if (tag.selfClosing) return tag.resume;
+ const read = elementChildren(src, tag.resume, headTagName(src, at), budget);
+ return read !== null && read.closes !== undefined ? read.closes + 1 : -1;
}
// Whether the parameter list whose `(` is at `open` can hold what TypeScript parses as parameters (parseParameters, parseParameterWorker,
@@ -1768,6 +2447,19 @@ function parameterListMayStart(src, open) {
return c === undefined || c.charCodeAt(0) > 0x7f || /^[A-Za-z_$\\{[.@)]$/.test(c);
}
+// Whether the `[` at `open`, where a member of a type begins, is an index signature that a `/` follows: a `[`, a name and a `,` or a `:` are one for certain (isUnambiguouslyIndexSignature,
+// https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts), whose next token is a parameter (after the `,`) or a type (after the `:`), and neither starts with a `/` that no comment makes
+// (TS1138, TS1110). So `[ a, // note` and a line break, then `/path`, is no type's, where `[ // note` and a `/` is a computed name that a regex may follow. A word that is a keyword is not read: it may not be a
+// name there (`[this, /x/]` is a computed name with a comma), and neither may a character beyond ASCII.
+function indexSignatureThenSlash(src, open) {
+ let k = skipSpaceAndComments(src, open + 1);
+ const end = asciiNameEnd(src, k);
+ if (end === -1 || TS_KEYWORDS.has(src.slice(k, end))) return false;
+ k = skipSpaceAndComments(src, end);
+ if (src[k] !== ',' && src[k] !== ':') return false;
+ return src[skipSpaceAndComments(src, k + 1)] === '/';
+}
+
// The words TypeScript's parser takes before a parameter's name (parseParameterWorker reads modifiers there, and only the checker rejects a misplaced one), measured over every keyword
// TypeScript 5.8 has, each in a call signature, a construct signature and a function type, followed by a name: all three parse. A parameter that starts with one is not read.
const PARAMETER_MODIFIERS = new Set(['abstract', 'accessor', 'async', 'declare', 'export', 'in', 'out', 'override', 'private', 'protected', 'public', 'readonly', 'static']);
@@ -1844,6 +2536,10 @@ function defaultMayModify(src, end) {
// The words a type may start with that take a type after them: `keyof T`, `typeof x`, `readonly T[]`, `unique symbol`, `infer U`, `asserts x`, measured over every keyword
// TypeScript has; `new`, `abstract`, `function` and `import`, which start a type that a name does not follow, are kept as well. (`this is T` is read in typeStartFails.)
const TYPE_OPERATOR_WORDS = new Set(['keyof', 'typeof', 'readonly', 'unique', 'infer', 'asserts', 'new', 'abstract', 'function', 'import']);
+// The ones of those that are no type without an operand (`a: keyof` is TS1110, where `a: abstract` and `a: function` are types named so): the reader of a type's members goes on from a `:` after one of them (typeMembersFail).
+// `keyof`, `readonly` and `unique` are operators of parseTypeOperatorOrHigher, whose operand may be an operator of its own and is otherwise a name (`keyof new`, `keyof import`: a reference to a type of that name);
+// `typeof` takes an entity name and `infer` an identifier, which any word is (`typeof new`, `infer keyof`); `new` and `import`, where a type starts, are a constructor type and an import type, which `(` or `<` must follow.
+const TYPE_PREFIX_WORDS = new Set(['keyof', 'readonly', 'unique']);
// Whether the type that starts at `t`, a parameter's, fails at the second name it holds. A name there that follows a type reference is TS1005 (the list wants a `,`, a `)`, an
// `=`, a `?` or an operator), unless the first word takes a type after it (TYPE_OPERATOR_WORDS) or the second is a conditional type's `extends`. `this` and `is` on one line are
@@ -1852,15 +2548,30 @@ const TYPE_OPERATOR_WORDS = new Set(['keyof', 'typeof', 'readonly', 'unique', 'i
// (parseTypeParameter), unless the first word is a modifier — TypeScript parses every one there, and only the checker objects (`<private x>`). A `<` after a type reference opens
// its type arguments, whose first is a type and is read the same way (`see<a href` fails at `href`). A name that a character beyond ASCII or a backslash goes on with ends the
// reading, as anything else does: false. All of it is measured against TypeScript over every pair of keywords, with the endings that could complete a type.
+// Four more types are read where they fail at their own second token (each measured the same way, over every keyword after it):
+// a number `10 MB max` a number literal is a type, and a name after it is TS1005 unless it is a conditional type's `extends` (numberTypeFails)
+// an object `{user.name}` a type literal's member is a name and then `?`, `:`, `(`, `<`, `,`, `;`, the `}` or a line's end — anything else after the name is TS1131 (objectTypeFails)
+// `new` `new <a href=` a constructor type is `new`, type parameters if a `<` follows, and a `(`: a `new` that a `(` or a `<` does not follow is TS1005, and the type parameters are read as above
+// `import` `import <a href=` an import type is `import` and a `(` (parseImportType): anything else after it is TS1005
function typeStartFails(src, t) {
// Each step reads one type: the parameter's, the type after `this is`, or the first type argument of a type reference that a `<` follows. Every step consumes text, so the
// loop ends.
for (let start = t; ;) {
const parameters = src[start] === '<';
const first = parameters ? skipSpaceAndComments(src, start + 1) : start;
+ if (!parameters && src[first] === '{') return objectTypeFails(src, first);
+ if (!parameters && (src[first] === '-' || isDigit(src[first]))) return numberTypeFails(src, first);
const firstEnd = asciiNameEnd(src, first);
if (firstEnd === -1) return false;
const word = src.slice(first, firstEnd);
+ if (!parameters && (word === 'new' || word === 'import')) {
+ const next = skipSpaceAndComments(src, firstEnd);
+ if (word === 'new' && src[next] === '<') {
+ start = next;
+ continue;
+ }
+ return src[next] !== '(';
+ }
if (parameters ? word === 'const' || PARAMETER_MODIFIERS.has(word) : TYPE_OPERATOR_WORDS.has(word)) return false;
const second = skipSpaceAndComments(src, firstEnd);
if (!parameters && word === 'this' && asciiNameEnd(src, second) === second + 2 && src.startsWith('is', second) && !/[\n\r\u2028\u2029]/.test(src.slice(firstEnd, second))) {
@@ -1876,6 +2587,52 @@ function typeStartFails(src, t) {
}
}
+const isDigit = (c) => typeof c === 'string' && c >= '0' && c <= '9';
+
+// The end of the decimal number literal that is a type at `at`, or -1: an optional `-` (the type is a negative number; TypeScript allows trivia between the two tokens, parseNonArrayType and
+// nextTokenIsNumericOrBigIntLiteral), digits and an optional fraction, with white space or a comment right after it. A number that a name is glued to is its own error (TS1351), one with an
+// exponent, a radix, a separator, a `n` or a `.` and no digit after it is another token to read, and neither is read here.
+function decimalLiteralEnd(src, at) {
+ let k = at;
+ if (src[k] === '-') k = skipSpaceAndComments(src, k + 1);
+ const digits = k;
+ while (isDigit(src[k])) k += 1;
+ if (k === digits) return -1;
+ if (src[k] === '.' && isDigit(src[k + 1])) {
+ k += 1;
+ while (isDigit(src[k])) k += 1;
+ }
+ return isTrivia(src[k]) || (src[k] === '/' && (src[k + 1] === '/' || src[k + 1] === '*')) ? k : -1;
+}
+
+// Whether the number literal type at `at` is followed by a name that no type has there: after a literal type the type ends, and only `[`, `|`, `&`, `?`, `!` and a conditional type's `extends` go on with
+// it — every other word is TS1005 (`',' expected`), in a call signature, a construct signature and a function type alike:
+// (Size: 10 MB max, <a href="/x">upgrade</a>)
+function numberTypeFails(src, at) {
+ const end = decimalLiteralEnd(src, at);
+ if (end === -1) return false;
+ const word = skipSpaceAndComments(src, end);
+ const wordEnd = asciiNameEnd(src, word);
+ return wordEnd !== -1 && src.slice(word, wordEnd) !== 'extends';
+}
+
+// What can follow the name that starts a type literal's first member and make it no member: `.`, an operator that no member has, or a `/` that starts no comment (a comment is trivia, and skipped). A member
+// is a name that `?`, `:`, `(`, `<`, `,`, `;`, the `}` or the end of a line follows (isTypeMemberStart, parseTypeMemberSemicolon); anything else — here every one of these, whatever the name is, a modifier and
+// `get` and `set` included, and a line break before it as well — is TS1131, "Property or signature expected". The exception is a `.` and a digit, `.5`, which is a number and so a property's name: after a modifier
+// (`{ readonly .5: T }`), or as the next member after a line break (`{ a` LF `.5 }`). Names, strings and numbers, `[`, `{` and `#`, which a modifier goes on with, are not in the list, and neither are `=`, `>`,
+// `<`, `(` and the other brackets, which a member may hold or which begin one.
+const OBJECT_MEMBER_JUNK = new Set([...'.+-*%&|^!~/']);
+
+// Whether the object type that opens at `open`, a parameter's type, is none: its first member is a name and then one of OBJECT_MEMBER_JUNK, as in the text of an element that starts with a parenthesis and
+// holds an expression container, `(Name: {user.name}, <a href={profile}>edit</a>)`.
+function objectTypeFails(src, open) {
+ const name = skipSpaceAndComments(src, open + 1);
+ const nameEnd = asciiNameEnd(src, name);
+ if (nameEnd === -1) return false;
+ const junk = skipSpaceAndComments(src, nameEnd);
+ return OBJECT_MEMBER_JUNK.has(src[junk]) && !(src[junk] === '.' && isDigit(src[junk + 1]));
+}
+
// Whether the character at `k`, in a parameter list read as a type, may start an expression or a statement there. TypeScript's parser does so from a type only at these places (parser.ts,
// https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts): an initializer's `=` (any `=` that is not the `=>` of a function type — `a: A<B>= /re/` is an initializer
// after type arguments), a computed name's `[` (any `[` but the `[]` of an array type, which this does not tell from a tuple, an index signature or an indexed access), a decorator's `@`,
@@ -1958,7 +2715,9 @@ function headTagName(src, head) {
// const e = <b>(optional)</b>; interface I { <T>(x) } type L = { <T>(x); m: { a: string } }; interface C { new <T>(x) }
// An element read for a signature reads the rest of the type as JSX text up to a closing tag found in a string or a comment that comes after it — `const s = '</T>;navigateTo({ … });//'` — where the
// call is a real one in no reading, and its token was rewritten. A signature read for an element is the failure; an element read for a signature reads JSX text as code, which is the same failure
-// the other way (a call inside the text of an element is no call). Two things settle it:
+// the other way (a call inside the text of an element is no call). Three things settle it:
+// 0. Where no member of a type begins at the head — right after an `=`, a `(`, a `[`, a `:` or an `=>`, `noMember` (NO_MEMBER_BEFORE) — there is no call signature for the text to be the start of, whatever it holds
+// after the `)`: an element, for certain. (After a `,`, a `;`, a `{` or a line break a member may begin, and the next two decide.)
// 1. A signature ends its member where TypeScript wants it to: after the `)` comes `,`, `;`, `}` or the end of the source, or the next token is on a later line (parseTypeMemberSemicolon, and
// canParseSemicolon for the line break, https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts). Anything else on the line — a name, a `<`, a `(`, a `{`, a comment that holds no
// line break — is TS1005, so no signature stands there and the text is an element, for certain: `<b>(optional)</b>`, `<p>({t("label")})</p>`, `<span>(total: {count})</span>`. So is a closing tag
@@ -1972,10 +2731,11 @@ function headTagName(src, head) {
// closed before it is open at it (a string, a template, a comment), or may be (a `/` that a regex may start after, a template with a `${`), or the reading cannot say, both programs compile and the text up to
// the decision is the same: the guess
// (`generic`), the element read.
-function callSignatureOrElement(src, after, head, close, next, budget) {
+function callSignatureOrElement(src, after, head, close, next, budget, noMember = false) {
const token = src[next];
// Text that ends here is a page that was cut off; no reading of it is complete.
if (token === undefined) return { generic: false, ambiguity: null };
+ if (noMember) return { generic: false, ambiguity: null };
let lineBreak = false;
for (let k = close + 1; k < next && !lineBreak; k += 1) lineBreak = isLineTerminator(src[k]);
const closingTag = token === '<' && src[next + 1] === '/' && src[next + 2] !== '*';
@@ -3088,4 +3848,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, RESERVED_WORDS };
+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 };
diff --git a/plugins/model-apps/scripts/lib/spec-lint.js b/plugins/model-apps/scripts/lib/spec-lint.js
index c286ec9ca..df1de98e5 100644
--- a/plugins/model-apps/scripts/lib/spec-lint.js
+++ b/plugins/model-apps/scripts/lib/spec-lint.js
@@ -2,12 +2,13 @@
// 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 } = require('./app-spec.js');
+const { relationshipSchemaName, relationshipFor, invalidChoiceSampleTokens, isPlatformIconRef, labelText, 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');
const { nearestName } = require('./nearest-name.js');
const { isAppSourcePath } = require('./app-source-path.js');
+const { labelLintWarnings } = require('./view-filter-labels.js');
const CHOICE_OPTION_WARN = 12;
const SEQNUM_RE = /\{SEQNUM(:\d+)?\}/i;
@@ -265,6 +266,7 @@ function lintAppSpec(spec) {
}
}
for (const sg of f.subgrids || []) {
+ for (const message of subgridUnknownKeys(sg)) W(`Form ${f.entity} ${message}`);
const has1N = (spec.relationships || []).some(
(r) => r.type === 'OneToMany' && lc(r.referenced) === lc(f.entity) && lc(r.referencing) === lc(sg.childEntity)
);
@@ -272,6 +274,16 @@ function lintAppSpec(spec) {
(r) => r.type === 'ManyToMany' && ((lc(r.entity1) === lc(f.entity) && lc(r.entity2) === lc(sg.childEntity)) || (lc(r.entity1) === lc(sg.childEntity) && lc(r.entity2) === lc(f.entity)))
);
if (!has1N && !hasNN) E(`Form ${f.entity} sub-grid for ${sg.childEntity} has no matching OneToMany or ManyToMany relationship`);
+ // Where the grid goes — the SAME judgement validateAppSpec makes, from the one function, so a spec that
+ // lints clean is not refused by the build's gate for a placement the lint never looked at.
+ if (formType === 'Main') for (const message of subgridPlacementProblems(f, sg)) E(`Form ${f.entity} ${message}`);
+ }
+ // A relationship listed more than once — likewise the one judgement of the spec gate: an error when an entry says
+ // where the grid goes, a warning when none does.
+ if (formType === 'Main') {
+ const duplicates = subgridDuplicateProblems(spec, f);
+ for (const message of duplicates.errors) E(`Form ${f.entity} ${message}`);
+ for (const message of duplicates.warnings) W(`Form ${f.entity} ${message}`);
}
for (const ev of f.events || []) {
if (!FORM_EVENTS.has(lc(ev.event))) { E(`Form ${f.entity} has an event with unknown type '${ev.event}' (use onload/onsave/onchange)`); continue; }
@@ -447,6 +459,9 @@ function lintAppSpec(spec) {
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.`);
}
}
+ // ADO 6691114: offline, a label can only be checked against what the spec declares. Say when one will
+ // be checked against the environment at build time instead, so the author is not surprised by the halt.
+ for (const w of labelLintWarnings(spec, v)) W(w);
for (const f of v.filters || []) {
if (!f.attr) { E(`View '${v.name}' has a filter without an attr`); continue; }
const op = f.op || 'eq';
diff --git a/plugins/model-apps/scripts/lib/unsynced-edits.js b/plugins/model-apps/scripts/lib/unsynced-edits.js
new file mode 100644
index 000000000..3cfe63ee9
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/unsynced-edits.js
@@ -0,0 +1,42 @@
+'use strict';
+// Does the SDK's workspace copy of an artifact hold edits the server has not seen?
+//
+// A push of a copy that equals its last-synced snapshot sends the server the document it already holds — a
+// write that costs a few requests (version reads, the PATCH, a read-back) and changes nothing. The reconcile
+// paths of the build (an existing view, an existing form) therefore push only when this says there is
+// something to send.
+//
+// Why the SDK's own dirty tracking is the right proof, and a hand-rolled compare is not:
+// * The workspace copy is the SDK's ONE canonical projection of the artifact (no side-channel), and the
+// snapshot is the projection of what the server returned at the last fetch or push. Every edit made
+// through the generic surface (updateElement / addElement / moveElement / removeElement) changes the
+// copy, so "copy equals snapshot" means no edit has been made since the server last held that document.
+// * An edit an interrupted earlier run left in the workspace survives a plain `fetchArtifact` while the
+// server has not moved (the SDK keeps unpushed work rather than silently reverting it). It is in the
+// copy but not in the snapshot, so it is reported here and still gets pushed — a comparison of "what this
+// run computed" against "what was fetched" would miss it.
+// * A copy that was never synced (no snapshot) is a pending creation and reads as changed.
+//
+// What this does NOT prove: that the server's PUBLISHED layer matches. The snapshot is the unpublished
+// layer's document (the SDK reads it with RetrieveUnpublished), so an earlier run that pushed and then
+// stopped before publishing leaves a clean copy over an unpublished change. A caller must never skip a
+// publish on the strength of this alone.
+//
+// `diffArtifact` is the SDK's structural diff between the copy and its snapshot — the same deepEqual that
+// `isDirty` uses, but addressable for one artifact (`listArtifacts` flags every workspace artifact of a
+// type, which a per-artifact decision should not pay for).
+//
+// FAILS OPEN: an SDK without the method, or a diff that throws (a workspace file that cannot be read), says
+// "changed", so the caller writes exactly as it did before this check existed. A skipped write has to be
+// proven unnecessary; a doubtful one is made.
+async function hasUnsyncedEdits(sdk, type, id) {
+ if (!sdk || typeof sdk.diffArtifact !== 'function') return true;
+ try {
+ const diff = await sdk.diffArtifact(type, id);
+ return !(diff && Array.isArray(diff.changes) && diff.changes.length === 0);
+ } catch {
+ return true;
+ }
+}
+
+module.exports = { hasUnsyncedEdits };
diff --git a/plugins/model-apps/scripts/lib/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.js
index a6e7a810d..3a55e4c95 100644
--- a/plugins/model-apps/scripts/lib/verify-spec.js
+++ b/plugins/model-apps/scripts/lib/verify-spec.js
@@ -11,21 +11,134 @@ const { sitemapEntityTables } = require('./app-spec.js');
// XML_TAG / XML_ATTR are the one tag and attribute grammar for FormXML and SiteMap XML; they live with
// 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 } = require('./app-spec.js');
+const { normalizePageSource, relationshipSchemaName, manyToManySchemaName, SDK_ROLE_MARKER, canonicalPersonaName, bpfUniqueName, BPF_ROLE_ACCESS, generatedTabName, generatedSectionName, formColumnsOf, formLayoutNames, subgridRelationshipName } = require('./app-spec.js');
const { sameRelationship, describeRelationship } = 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).
const KEPT_BY_DESIGNER = 'kept as the environment has it: changed in the designer since the spec\u2019s baseline, which the spec still matches';
const { extractNavTargets, strayPageRefs, describePageRefLocations } = require('./pageref-resolver.js');
-const { AI_APP_SETTING, resolveAiFlags, specOptsIntoAi, featureWantValue, sameSettingValue, resolveAppModuleId, proveAppOverride } = require('./ai-app-settings.js');
+const { AI_APP_SETTING, resolveAiFlags, specOptsIntoAi, featureWantValue, sameSettingValue, resolveAppModuleId, proveAppOverride, proofBudget } = require('./ai-app-settings.js');
const { declaredPrivileges, compareRolePrivileges } = require('./role-privileges.js');
const { resolveSurfaces } = require('./surface-resolver.js');
const { selectSummaryTables } = require('./ai-candidates.js');
-const { isVisualizationUnsupported } = require('./entity-provision.js');
-const { sectionGridWidth, mergeFieldOptions, fieldOptionsMap, normalizeFieldEntry, compileFormIntent, isNonFieldControl } = require('./artifact-intent.js');
+const { isVisualizationUnsupported, mapLimit } = require('./entity-provision.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');
const { rowOccupancy } = require('./form-occupancy.js');
+const { wantsTimeline, timelineVerifyProblem, FULL_BUILD } = require('./form-timeline.js');
+const { placementOf, resolvePlacement, columnSequence, neighbourOf, tokenLabel, findGridSection, AUTO_TAB_NAME } = require('./form-subgrid-placement.js');
const { isMainForm, selectDefaultForm, plannedMainFormSequence, displayConditionsOrder, compareServedOrder } = require('./form-order.js');
+const { hasLabelUses, resolveViewFilterLabels, memoizeChoiceReader, describeProblem } = require('./view-filter-labels.js');
+
+// How many verification reads may be in flight at once. A verify pass is nothing but reads, but each is a
+// Dataverse request that already retries on its own 429s (lib/sdk-http-client.js), so the bound is small:
+// enough to hide the per-request latency that made a pass cost the SUM of its reads, not so many that a
+// large spec turns into a burst. `opts.concurrency` overrides it; 1 runs the checks one after another, in the
+// order they are reported, which is the oracle the verify-parallel-checks tests compare the overlapped report with.
+const VERIFY_CONCURRENCY = 4;
+
+// The pass as an ordered list of tasks. Every check of a verify pass is a task that reads and then reports
+// into ITS OWN buffer; the report is the buffers joined in task order, which is the order the checks have
+// always been reported in, whatever order the reads answered in. The pool is entity-provision's mapLimit,
+// the limiter every other bounded fan-out of this plugin uses, with its `firstInOrder` rule: tasks START in
+// list order, nothing starts once one has failed, and the failure that is thrown is the one of the
+// lowest-numbered task — the error a pass that ran them one after another would have met first.
+//
+// A task may wait for an EARLIER one (a promise `section`/`each` returned). That cannot deadlock: tasks start
+// in order, so everything a task waits for has already started.
+function makeCheckPlan(concurrency) {
+ const tasks = [];
+ // A section's promise -> its task, to find where in the report the section sits (`unlessFailed`).
+ const taskOf = new Map();
+ // Marks a promise as handled: its failure is the POOL's to report (as the failed task's error); only a
+ // dependent task reads it, and one that never starts must not leave an unhandled rejection behind.
+ const handled = (promise) => { promise.catch(() => {}); return promise; };
+ // One check section: `fn` is handed the three places a check reports into. Resolves when it has run.
+ const section = (fn) => {
+ let settle;
+ const done = handled(new Promise((resolve, reject) => { settle = { resolve, reject }; }));
+ const task = async (buffers) => {
+ try {
+ await fn(buffers);
+ settle.resolve();
+ } catch (error) {
+ settle.reject(error);
+ throw error;
+ }
+ };
+ tasks.push(task);
+ taskOf.set(done, task);
+ return done;
+ };
+ // A section whose items read independently of each other: one task per item, each handed `[item]` and the
+ // item's index in the list, so the loop a section already has runs unchanged over its one item.
+ const each = (items, fn) => handled(Promise.all(Array.from(items, (item, index) => section((buffers) => fn(buffers, [item], index)))));
+ // A slow read that depends on no check's answer can be started WITH the pass instead of after the checks
+ // listed before it. It is a task of its own, listed first, that reports nothing — so the report is
+ // unchanged and it is one of the `concurrency` reads in flight like any other. `fn` must not throw: the
+ // check that consumes its answer (`consumer`, the promise its `section` returned) throws it, in that check's own
+ // place in the report. One read at a time there is nothing to overlap, so `fn` runs where its consumer first
+ // asks — the original read order.
+ //
+ // It is also a read the pass stops waiting for once a check LISTED BEFORE ITS CONSUMER has failed (`unlessFailed`).
+ // The pass throws the failure of the lowest-numbered task, so after that the consumer cannot change what is thrown
+ // whatever it reports — and the read can be slow without bound as far as this pass is concerned (it is a `pac`
+ // run, which the pass cannot time out), so draining it would turn a failure that used to be immediate into a
+ // hang. A check listed AFTER the consumer is another matter: the consumer's own failure outranks it, and the
+ // pass must still throw that one, as it did when the checks ran one after another — so a failure there does not
+ // end the wait. A read the pass gave up on is left to finish, or hang, on its own; `abandonedReads()` says there
+ // was one, so that whoever started it can end it.
+ let lowestFailure = Infinity;
+ const watchers = new Set();
+ let gaveUp = false;
+ const abandoned = Symbol('abandoned');
+ const positionOf = (consumer) => tasks.indexOf(taskOf.get(consumer));
+ const notifyFailed = (position) => {
+ if (position >= lowestFailure) return;
+ lowestFailure = position;
+ for (const check of [...watchers]) check();
+ };
+ // Answers `read`'s answer, or `abandoned` once a task listed before `consumer` has failed. A consumer that cannot
+ // be found in the list is never given up on.
+ const unlessFailed = (read, consumer) => new Promise((resolve, reject) => {
+ const check = () => {
+ const position = positionOf(consumer);
+ if (position < 0 || lowestFailure >= position) return;
+ watchers.delete(check);
+ gaveUp = true;
+ resolve(abandoned);
+ };
+ watchers.add(check);
+ read.then((answer) => { watchers.delete(check); resolve(answer); }, (error) => { watchers.delete(check); reject(error); });
+ check();
+ });
+ const early = (fn, consumer) => { if (concurrency > 1) tasks.unshift(async () => { await unlessFailed(fn(), consumer); }); };
+ const run = async () => {
+ const buffers = await mapLimit(tasks, concurrency, async (task, position) => {
+ const b = { checks: [], environmentSkipped: [], phaseSkipped: [] };
+ b.add = (kind, name, present, detail) => b.checks.push({ kind, name, present: !!present, detail: detail || '' });
+ try {
+ await task(b);
+ } catch (error) {
+ notifyFailed(position);
+ throw error;
+ }
+ return b;
+ }, { firstInOrder: true });
+ return {
+ checks: buffers.flatMap((b) => b.checks),
+ environmentSkipped: buffers.flatMap((b) => b.environmentSkipped),
+ phaseSkipped: buffers.flatMap((b) => b.phaseSkipped),
+ };
+ };
+ return { section, each, early, unlessFailed, abandoned, abandonedReads: () => gaveUp, run };
+}
+
+// Memoizes an async read for ONE pass: every consumer, however many sections ask at once, awaits the single
+// read in flight. (A Map of these is the same thing keyed.) The read starts on first use, never earlier.
+const once = (read) => { let started; return () => (started || (started = Promise.resolve().then(read))); };
// The PER-APP setting each AI feature writes now lives in ./ai-app-settings.js, together with the
// flag-resolution and override-proof helpers the BUILD uses — see that module for why one source of
@@ -33,11 +146,17 @@ const { isMainForm, selectDefaultForm, plannedMainFormSequence, displayCondition
// `opts.proofAttempts` / `opts.proofDelayMs` tune the app-scope override retry (see the ai-feature
// block below). They exist so tests can drive the absent path without paying real backoff; the
-// defaults are what the CLIs use.
+// defaults are the budget the build's own proof after a publish shares (AI_PROOF_BUDGET).
async function verifySpec(spec, read, opts = {}) {
if (read && typeof read.beginVerificationPass === 'function') read.beginVerificationPass();
- const checks = [];
- const add = (kind, name, present, detail) => checks.push({ kind, name, present: !!present, detail: detail || '' });
+ // Every check below is a task of this plan and reports into its own buffers (see makeCheckPlan), which
+ // are joined at the end in the order the tasks are listed — the order the checks were always reported in.
+ // The section bodies keep the indentation they had when they ran one after another, so this reads as
+ // additions around unchanged code.
+ if (opts.concurrency !== undefined && (!Number.isInteger(opts.concurrency) || opts.concurrency < 1)) {
+ throw new Error(`verify concurrency must be a positive integer (got ${JSON.stringify(opts.concurrency)})`);
+ }
+ const plan = makeCheckPlan(opts.concurrency === undefined ? VERIFY_CONCURRENCY : opts.concurrency);
// Artifacts the BUILD reported as impossible on this environment, keyed `entity|name`. Supplied by
// the caller because verify is also runnable standalone, where no build result exists — in that
// case the set is empty and every declared rule is checked, which is the right default: absent a
@@ -60,9 +179,8 @@ async function verifySpec(spec, read, opts = {}) {
// Two DIFFERENT reasons a check was not performed, kept apart because they warrant opposite
// messages. Reporting a phase that simply did not run as "this environment cannot host it" tells
// an operator on a perfectly healthy environment that their environment is broken — and on the
- // normal `--changed-only` fast-apply path that would be wrong every single time.
- const environmentSkipped = [];
- const phaseSkipped = [];
+ // normal `--changed-only` fast-apply path that would be wrong every single time. (Each task collects
+ // its own `environmentSkipped` / `phaseSkipped`; the plan joins them in report order.)
const selectedDefaultForms = new Map();
const declaredMainFormsByEntity = new Map();
@@ -84,7 +202,8 @@ async function verifySpec(spec, read, opts = {}) {
}
// Entities + their declared columns.
- for (const e of spec.entities || []) {
+ plan.each(spec.entities || [], async ({ add }, entities) => {
+ for (const e of entities) {
const logical = e.schemaName.toLowerCase();
const tbl = await read.findTable(logical);
add('entity', e.schemaName, tbl);
@@ -120,9 +239,20 @@ async function verifySpec(spec, read, opts = {}) {
}
}
}
+ });
// Views / charts / forms — by (entity, name) identity.
- for (const v of spec.views || []) {
+ //
+ // ADO 6691114: a filter's option LABEL is written as the value the ENVIRONMENT holds for it, so the value
+ // verify expects has to come from there too — against the spec's own 100000000+n numbering, a value the
+ // build resolved live (a global choice that already existed, a column of an existing table) would fail
+ // here although it is exactly right. Reader-gated, as the other content checks are: a reader without
+ // `choiceAttributes` keeps the spec-only expectation. One read per table for the whole pass.
+ const readChoices = typeof read.choiceAttributes === 'function'
+ ? memoizeChoiceReader((entity) => read.choiceAttributes(entity, { languageCode: spec.languageCode }))
+ : null;
+ plan.each(spec.views || [], async ({ add }, views) => {
+ for (const v of views) {
const viewName = `${String(v.entity).toLowerCase()}.${v.name}`;
// Also select layoutxml so a CONTENT check can catch a spec column the view does not carry (an
// added or renamed column that never landed would otherwise pass an existence-only verify). It
@@ -148,21 +278,45 @@ async function verifySpec(spec, read, opts = {}) {
add('view-columns', viewName, missingCols.length === 0, missingCols.length ? `missing column(s): ${missingCols.join(', ')}` : '');
}
if (row && Object.prototype.hasOwnProperty.call(row, 'fetchxml')) {
- const expected = expectedViewFetchParts(spec, v);
+ const labels = readChoices && hasLabelUses(spec, v) ? await resolveViewFilterLabels(spec, [v], { read: readChoices }) : null;
+ // A label no option answers to cannot be proven deployed — and a deployed value equal to the label's own
+ // text is the very defect — so it is reported by name, with the labels that are valid, instead.
+ const unresolved = labels ? labels.problems : [];
+ // A label whose option metadata could not be READ is not resolved either: what the expectation below holds
+ // for it is only the build's fallback (the spec's numbering, or the label as written), which a deployed
+ // value from the environment may rightly differ from. Where a different value is deployed, that is reported
+ // as UNRESOLVED, with the reason — never as a missing filter, which would call a correct view wrong because
+ // a read failed. Where the fallback IS deployed, it was right, and it verifies; and where the view carries
+ // no condition on the attribute at all, the filter is missing, and is reported as missing.
+ // Keyed `<attribute>|<value>` — the identity a deployed condition is compared by.
+ const guesses = new Map((labels ? labels.inconclusive : []).map((p) => [`${p.attr}|${p.assumed}`, p]));
+ const expected = expectedViewFetchParts(spec, v, labels);
// Dataverse stores savedquery.fetchxml as the authoritative query content for a system view, so
// the verifier proves the DEPLOYED predicates/orders rather than trusting the build's intended
// view definition. Subset semantics are deliberate: Dataverse may add platform-owned predicates
// that the App Spec never authored, and those must not block a good app.
// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/savedquery
- if (!row.fetchxml && (expected.conditions.length || expected.orders.length)) {
- if (expected.conditions.length) add('view-filters', viewName, false, 'could not read deployed savedquery.fetchxml to prove authored filters');
+ if (!row.fetchxml && (expected.conditions.length || expected.orders.length || unresolved.length)) {
+ if (expected.conditions.length || unresolved.length) add('view-filters', viewName, false, [...unresolved.map(describeProblem), ...(expected.conditions.length ? ['could not read deployed savedquery.fetchxml to prove authored filters'] : [])].join(' | '));
if (expected.orders.length) add('view-sort', viewName, false, 'could not read deployed savedquery.fetchxml to prove authored sort');
continue;
}
const actual = parseFetchXml(row.fetchxml);
- if (expected.conditions.length) {
- const missing = expected.conditions.filter((want) => !actual.conditions.some((got) => conditionMatches(want, got)));
- add('view-filters', viewName, missing.length === 0, missing.length ? `missing filter(s): ${missing.map(formatCondition).join('; ')}` : '');
+ if (expected.conditions.length || unresolved.length) {
+ const absent = expected.conditions.filter((want) => !actual.conditions.some((got) => conditionMatches(want, got)));
+ // An absent condition is only UNRESOLVED where the view carries SOME condition on that attribute with that
+ // operator — a value that may be the one the failed read would have named. A view with no such condition
+ // at all is missing the filter, whatever the options are, and says so.
+ const unresolvable = (c) => guesses.has(`${c.attribute}|${c.value}`)
+ && actual.conditions.some((got) => got.attribute === c.attribute && got.operator === c.operator);
+ const guessed = absent.filter(unresolvable);
+ const missing = absent.filter((c) => !unresolvable(c));
+ const notes = [
+ ...unresolved.map(describeProblem),
+ ...[...new Set(guessed.map((c) => guesses.get(`${c.attribute}|${c.value}`)))].map(describeProblem),
+ ...(missing.length ? [`missing filter(s): ${missing.map(formatCondition).join('; ')}`] : []),
+ ];
+ add('view-filters', viewName, notes.length === 0, notes.join(' | '));
}
if (expected.orders.length) {
// Sort PRECEDENCE is the whole point of a sort, so membership is not enough: a deployed
@@ -185,10 +339,13 @@ async function verifySpec(spec, read, opts = {}) {
}
}
}
- for (const ch of spec.charts || []) {
+ });
+ plan.each(spec.charts || [], async ({ add }, charts) => {
+ for (const ch of charts) {
const rows = await read.queryRecords('savedqueryvisualization', { select: ['savedqueryvisualizationid'], filter: `primaryentitytypecode eq '${String(ch.entity).toLowerCase()}' and name eq '${odataLit(ch.name)}'`, top: 1 });
add('chart', ch.name, rows && rows[0]);
}
+ });
// DASHBOARDS — existence, then that every deployed chart tile is internally consistent (#586 item 3).
// A chart tile names a table (`TargetEntityType`), a view and a chart. The platform accepts and
// publishes a tile whose chart belongs to ANOTHER table, and two same-named charts on different
@@ -254,7 +411,8 @@ async function verifySpec(spec, read, opts = {}) {
if (!ownDashboards.has(name)) ownDashboards.set(name, identifyDashboard(name));
return ownDashboards.get(name);
};
- for (const d of spec.dashboards || []) {
+ plan.each(spec.dashboards || [], async ({ add }, dashboards) => {
+ for (const d of dashboards) {
if (!d || !d.name) continue;
const own = await ownDashboard(d.name);
if (!own.id) { add('dashboard', d.name, false, own.detail); continue; }
@@ -283,6 +441,7 @@ async function verifySpec(spec, read, opts = {}) {
}
add('dashboard', d.name, problems.length === 0, problems.join('; '));
}
+ });
// One published systemform row feeds the default flag, the layout proof and the stored order.
// formRow selects all of them. Memoized for THIS verify only: the reader is reused, and a later
// verify must observe a row that changed in between (a recorded FormXML can be rewritten).
@@ -308,8 +467,9 @@ async function verifySpec(spec, read, opts = {}) {
return read.formTopology(entity, formId);
};
const canReadDefault = useCombinedFormRead || typeof read.formDefaultState === 'function';
- const resolvedMainFormsByEntity = new Map();
- for (const f of spec.forms || []) {
+ const resolvedMainFormsByIndex = [];
+ const formsResolved = plan.each(spec.forms || [], async ({ add }, forms, formIndex) => {
+ for (const f of forms) {
const name = f.name || `${f.entity} form`;
// Resolve with the SAME identity the build reconcile uses — (entity, name, TYPE) or a validated pinned
// formId (which checks the row's table/type/name) — so verify can't be fooled by a same-named sibling
@@ -323,8 +483,7 @@ async function verifySpec(spec, read, opts = {}) {
add('form', name, id);
const entityLogical = String(f.entity || '').toLowerCase();
if (id && declaredMainFormsByEntity.has(entityLogical) && (f.formType || 'Main') === 'Main') {
- if (!resolvedMainFormsByEntity.has(entityLogical)) resolvedMainFormsByEntity.set(entityLogical, []);
- resolvedMainFormsByEntity.get(entityLogical).push({ form: f, name, id });
+ resolvedMainFormsByIndex[formIndex] = { entityLogical, form: f, name, id };
}
if (id && selectedDefaultForms.get(entityLogical) === f && canReadDefault) {
let state = null;
@@ -341,8 +500,24 @@ async function verifySpec(spec, read, opts = {}) {
: `expected this Main form to be the table default, but deployed systemform.isdefault is ${state && state.isDefault === false ? 'false' : 'unreadable'}`);
}
}
+ });
+ // The forms that resolved as a declared Main form, per table, in the order the spec lists them — the
+ // order the checks below report in — however the resolutions finished. They wait for every form's
+ // resolution (`formsResolved`); tasks start in order, so those have all started by the time they ask.
+ const resolvedMainForms = once(async () => {
+ await formsResolved;
+ const byEntity = new Map();
+ for (const r of resolvedMainFormsByIndex) {
+ if (!r) continue;
+ if (!byEntity.has(r.entityLogical)) byEntity.set(r.entityLogical, []);
+ byEntity.get(r.entityLogical).push({ form: r.form, name: r.name, id: r.id });
+ }
+ return byEntity;
+ });
if (canReadDefault) {
- for (const [entityLogical, selected] of selectedDefaultForms) {
+ plan.each([...selectedDefaultForms], async ({ add }, defaults) => {
+ for (const [entityLogical, selected] of defaults) {
+ const resolvedMainFormsByEntity = await resolvedMainForms();
const selectedName = selected.name || `${selected.entity} form`;
for (const sibling of resolvedMainFormsByEntity.get(entityLogical) || []) {
if (sibling.form === selected) continue;
@@ -358,6 +533,7 @@ async function verifySpec(spec, read, opts = {}) {
: 'could not prove this spec-declared Main form is not also default');
}
}
+ });
}
// AB#6736948 — the Main Form Set order, for every table the build orders (lib/form-order.js). Two
@@ -372,8 +548,10 @@ async function verifySpec(spec, read, opts = {}) {
// Neither sees a user's remembered form (the one they last switched to), which opens first for them
// while they may open it; it is per user and not configuration (references/app-spec-schema.md).
if (useCombinedFormRead || typeof read.formTopology === 'function') {
- for (const [entityLogical, declared] of declaredMainFormsByEntity) {
+ plan.each([...declaredMainFormsByEntity], async ({ add, environmentSkipped }, declaredMain) => {
+ for (const [entityLogical, declared] of declaredMain) {
if (!plannedMainFormSequence(spec, entityLogical)) continue;
+ const resolvedMainFormsByEntity = await resolvedMainForms();
const resolved = resolvedMainFormsByEntity.get(entityLogical) || [];
const idOf = new Map(resolved.map((r) => [r.form, r.id]));
const nameOf = new Map(resolved.map((r) => [r.form, r.name]));
@@ -426,12 +604,14 @@ async function verifySpec(spec, read, opts = {}) {
add('form-order-served', `${entityLogical} opens with '${first}'`, true);
}
}
+ });
}
// Relationships. A name on the child is not proof: a 1:N and an N:N between the same pair derive
// the same schema name, and the second create used to be skipped. Match the endpoints the build
// sends. Plain-string rows (older test doubles) stay name-only. A read failure stays an empty
// list, which fails closed, same as before.
+ plan.section(async ({ add }) => {
if (typeof read.entityRelationships === 'function') {
const prefix = spec.solution && spec.solution.publisherPrefix;
const relCache = new Map();
@@ -490,6 +670,7 @@ async function verifySpec(spec, read, opts = {}) {
add('relationship', schema, false);
}
}
+ });
// Form TOPOLOGY. Existence is not proof of shape: every wrong-layout defect this plugin has hit —
// fields flattened into the first section, a duplicate tab appended on each rebuild, a relocated
@@ -511,7 +692,8 @@ async function verifySpec(spec, read, opts = {}) {
// explicit form passed verify on identity and default checks alone with no layout proof at all.
const canReadTopology = useCombinedFormRead || typeof read.formTopology === 'function';
{
- for (const f of spec.forms || []) {
+ plan.each(spec.forms || [], async ({ add }, forms) => {
+ for (const f of forms) {
const explicit = Array.isArray(f.tabs) && f.tabs.length > 0;
const entity = String(f.entity || '').toLowerCase();
const name = f.name || `${f.entity} form`;
@@ -571,9 +753,33 @@ async function verifySpec(spec, read, opts = {}) {
// the whole form, including header/footer and unbound controls, even for an unshaped auto form.
const identityProblems = formIdentityProblems(xml);
add('form-identities', `${entity}.${name}`, identityProblems.length === 0, identityProblems.join('; '));
+ const deployed = parseFormTopology(xml);
+ // The Notes timeline, on any layout: Dynamics renders it only under the control id `notescontrol` in a
+ // tall cell (lib/form-timeline.js), so a form that carries it in the shape an older build wrote — or not at
+ // all — has not got the timeline the spec asks for, however many other checks pass. The form need only
+ // carry ONE timeline that renders: a maker may have moved it, or added their own, and the build never edits
+ // a timeline it does not own. The engine's own host is judged by its rows as well (the build converges
+ // them, so rows still missing are a fix not applied); a timeline a maker added, by its id and span alone.
+ // What the detail tells the maker to do follows what a build will do about THIS form, which is not always
+ // "build again" (timelineVerifyProblem) — and what it does to the fields in the host first is predicted from the
+ // spec and this published form (notesHostInspector).
+ if (wantsTimeline(spec, f)) {
+ const problem = timelineVerifyProblem(deployed, isEngineHostSection, { inspect: notesHostInspector(spec, f, deployed) });
+ add('form-timeline', `${entity}.${name}`, !problem, problem);
+ }
+ // Sub-grids that declare where they go (`tab` / `column` / `after` / `before`) are checked against the
+ // deployed form on every layout; the others have no place to hold the form to. An explicit layout's tabs
+ // and sections are matched the way the build matched them (further down, where the matches are made); an
+ // auto layout's one tab and section are looked up by the names the compiler gives them.
+ const placedGridChecks = (match) => {
+ for (const c of subgridPlacementChecks(spec, f, deployed, match)) add('form-subgrid', `${entity}.${name}: ${c.name}`, c.ok, c.detail);
+ };
+ if (!explicit) {
+ const autoTab = layoutAutoMatch(deployed);
+ placedGridChecks(autoTab);
+ }
if (!explicit && !autoFlagged.length) continue;
- const deployed = parseFormTopology(xml);
const problems = [];
// A declared flag against the deployed attribute, where an absent attribute is what the form
// renders without one: shown, expanded, labelled, editable. Reported in the spec's own terms
@@ -654,6 +860,10 @@ async function verifySpec(spec, read, opts = {}) {
// failed a build that had done exactly what was asked. Live-reproduced.
const claimedTabs = new Set();
const tabOrder = [];
+ // Where each authored tab / section was matched on the deployed form — what a sub-grid's placement is
+ // judged against (subgridPlacementChecks), since a matched container keeps its deployed name.
+ const matchedTabs = [];
+ const matchedSections = new Map();
// The section names the author declared — the same set the build's compiler records — so the
// label and position passes skip a section another want owns by name, exactly as the build does.
// Tabs follow the same rule, from the same kind of set.
@@ -670,6 +880,7 @@ async function verifySpec(spec, read, opts = {}) {
if (!tabHit) { problems.push(`tab '${tabName}' is absent`); return; }
claimedTabs.add(tabHit.index);
tabOrder.push({ name: tabName, index: tabHit.index });
+ matchedTabs[ti] = tabHit.index;
const got = tabHit.item;
const compiledTab = compiledTabs[ti] || {};
stateFlag(`tab '${tabName}'`, 'expanded', 'expanded', got.expanded, compiledTab.expanded !== false);
@@ -704,6 +915,7 @@ async function verifySpec(spec, read, opts = {}) {
}
claimedSections.add(secHit.index);
sectionOrder.push({ name: secName, index: secHit.index });
+ matchedSections.set(secName, { ti: tabHit.index, ci, si: secHit.index });
const compiledSection = (compiledColumn.sections || [])[si] || {};
stateFlag(`section '${secName}'`, 'visible', 'visible', secHit.item.visible, compiledSection.visible !== false);
stateFlag(`section '${secName}'`, 'showLabel', 'showlabel', secHit.item.showLabel, compiledSection.showLabel !== false);
@@ -803,7 +1015,12 @@ async function verifySpec(spec, read, opts = {}) {
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` : ''}` : '');
+ placedGridChecks({
+ tab: (i) => matchedTabs[i],
+ section: (secName) => matchedSections.get(secName),
+ });
}
+ });
}
// Commands (existence) — a spec can declare a command bar that didn't build and still pass verify
@@ -811,11 +1028,13 @@ async function verifySpec(spec, read, opts = {}) {
// effort: only when the reader can resolve a command bar (`commandBar(entity)` -> truthy when present).
if (typeof read.commandBar === 'function') {
const cmdEntities = new Set((spec.commands || []).map((c) => String(c.entity).toLowerCase()));
- for (const entity of cmdEntities) {
+ plan.each([...cmdEntities], async ({ add }, entities) => {
+ for (const entity of entities) {
let present = false;
try { present = !!(await read.commandBar(entity)); } catch { present = false; }
add('command', `${entity} command bar`, present);
}
+ });
}
// Business rules. A rule that EXISTS is not a rule that RUNS: a Draft (statecode 0) rule is inert,
@@ -828,7 +1047,8 @@ async function verifySpec(spec, read, opts = {}) {
// existence — the rule never built at all
// cardinality — more than one row for the same (entity, name) fires the logic repeatedly
// state — deployed Draft when the spec asked for Active (or the reverse)
- for (const rule of spec.businessRules || []) {
+ plan.each(spec.businessRules || [], async ({ add, environmentSkipped, phaseSkipped }, rules) => {
+ for (const rule of rules) {
const entityLogical = String(rule.entity).toLowerCase();
const name = `${entityLogical}.${rule.name}`;
// A rule the BUILD skipped because this environment cannot host business rules at all is not a
@@ -900,12 +1120,14 @@ async function verifySpec(spec, read, opts = {}) {
add('business-rule', name, wantActive === isActive,
wantActive === isActive ? '' : (wantActive ? 'deployed but DRAFT — the rule does not run' : 'deployed ACTIVE but the spec asks for Draft — the rule is running'));
}
+ });
// Business process flows. Reconciled on the same three axes as business rules, because a BPF fails
// the same three silent ways: it never built, it built twice (users are offered the same process
// more than once), or it is deployed Draft and therefore invisible on the form. Activation is
// best-effort in the build, so verify is what makes the outcome loud.
- for (const flow of spec.businessProcessFlows || []) {
+ plan.each(spec.businessProcessFlows || [], async ({ add }, flows) => {
+ for (const flow of flows) {
const entityLogical = String(flow.entity).toLowerCase();
const name = `${entityLogical}.${flow.name}`;
let rows;
@@ -934,11 +1156,17 @@ async function verifySpec(spec, read, opts = {}) {
add('business-process-flow', name, wantActive === isActive,
wantActive === isActive ? '' : (wantActive ? 'deployed but DRAFT — the process does not appear on the form' : 'deployed ACTIVE but the spec asks for Draft — the process is running'));
}
+ });
// Sitemap subareas (+ icons). Scope every check to the specific element type (and, for a subarea
// icon, the owning entity) so an icon/entity value reused elsewhere in the XML can't satisfy an
// unrelated check (e.g. an Area icon must not make a missing SubArea icon look present).
- const xml = (await read.sitemapXml()) || '';
+ //
+ // The sitemap is read once for the pass, by whichever check needs it first: this section always reads it
+ // (as it always has), and the page checks read the same promise.
+ const sitemapXml = once(async () => (await read.sitemapXml()) || '');
+ plan.section(async ({ add }) => {
+ const xml = await sitemapXml();
// AB#6726727: a rebuild KEEPS a nav entry's icon that changed in the designer since the spec's
// baseline while the spec did not (sitemap-merge.js), and its own --verify must not fail on that.
// Such a failing icon check is accepted only when the build's rule (keepsLiveValue) holds for the
@@ -1022,6 +1250,7 @@ async function verifySpec(spec, read, opts = {}) {
}
}
}
+ });
// App-module TABLE membership (appmodulecomponent componenttype 1).
//
@@ -1037,6 +1266,7 @@ async function verifySpec(spec, read, opts = {}) {
// Optional capability: verify-spec is also driven by minimal readers, and an optional reader must
// never become a TypeError for them (same rule as `columnVisualization`).
const hiddenTables = Array.isArray(spec.app && spec.app.tables) ? spec.app.tables : [];
+ plan.section(async ({ add }) => {
if (typeof read.appEntityComponents === 'function' || hiddenTables.length) {
const sitemapEntities = [...new Set([...sitemapEntityTables(spec), ...hiddenTables.map((name) => String(name).toLowerCase())])];
if (sitemapEntities.length) {
@@ -1066,8 +1296,10 @@ async function verifySpec(spec, read, opts = {}) {
}
}
}
+ });
const mainForms = spec.app && spec.app.mainForms;
+ plan.section(async ({ add }) => {
if (mainForms && Object.keys(mainForms).length) {
let membership;
try {
@@ -1096,6 +1328,7 @@ async function verifySpec(spec, read, opts = {}) {
add('app-main-forms', table, problems.length === 0, problems.join('; '));
}
}
+ });
// Pages (design §13.1). Match BY ID against three authorities — IDENTITY (manifest), EXISTENCE
// (env-wide id set), MEMBERSHIP (app sitemap ids). Reader must supply sitemapPageIds(),
@@ -1110,6 +1343,55 @@ async function verifySpec(spec, read, opts = {}) {
typeof read.existenceIds !== 'function' ||
typeof read.manifest !== 'function'
)) || !!(hasNavPages && typeof read.pageCode !== 'function');
+ // Build key→id from the manifest (IDENTITY authority). A spec page's own pageId (edit-snapshot,
+ // C3) OUTRANKS the manifest entry for the same key — use idOf() consistently.
+ const pageIdOf = (man) => {
+ const idByKey = new Map(
+ ((man && man.pages) || [])
+ .filter((p) => p && p.key && p.pageId)
+ .map((p) => [p.key, p.pageId]),
+ );
+ // idOf: spec pageId first (highest authority), then manifest key→id (C3 outranks C1).
+ return (p) => p.pageId || idByKey.get(p.key || p.name);
+ };
+ // The page checks' slow reads, made in the order the checks have always made them: the three authorities
+ // (one is a pac listing, about five seconds) and then the code of the pages whose navigation is checked,
+ // which a reader that can (`pageCodes`) downloads in one pac run instead of one run per page. One memo, so
+ // the early start below and the check share the same reads. It never throws: a failed read is handed to the
+ // pages check, which throws it in its own place in the report — the read is no longer made at that point,
+ // and the error that ends the pass must not depend on when it was.
+ const pageReads = once(async () => {
+ try {
+ const sitemapIds = new Set((await read.sitemapPageIds()).map((id) => String(id).toLowerCase()));
+ const existenceIds = new Set((await read.existenceIds()).map((id) => String(id).toLowerCase()));
+ const man = await read.manifest();
+ let codes = null;
+ if (typeof read.pageCodes === 'function') {
+ // Only pages the checks below will read: deployed, in this app, with navigation to check — once
+ // each, in spec order. A page that ends up unresolved here is simply asked for by itself later.
+ const idOf = pageIdOf(man);
+ const wanted = [];
+ const seen = new Set();
+ for (const p of implementedPages) {
+ const id = idOf(p);
+ const key = id ? String(id).toLowerCase() : '';
+ if (!key || !(p.navigatesTo || []).length || seen.has(key)) continue;
+ if (!existenceIds.has(key) || !sitemapIds.has(key)) continue;
+ seen.add(key);
+ wanted.push(id);
+ }
+ // One page is the one-page download, which pageCode already is.
+ if (wanted.length > 1) {
+ try { codes = await read.pageCodes(wanted); } catch { codes = null; }
+ }
+ }
+ return { sitemapIds, existenceIds, man, codes };
+ } catch (error) {
+ return { error };
+ }
+ });
+ const pagesCheck = plan.section(async ({ add }) => {
+ const xml = await sitemapXml();
if (implementedPages.length) {
if (unableToRun) {
// Reader is missing required page-authority methods — add a sentinel check and skip the loop.
@@ -1118,18 +1400,21 @@ async function verifySpec(spec, read, opts = {}) {
// ONE cached snapshot of each authority (Imp7 — never re-query per page). Throws from
// sitemapPageIds/existenceIds propagate out of verifySpec; the build gate's try/catch converts them
// to a non-zero exit (design §13.1). The caller that constructed the reader bears fail-closed responsibility.
- const sitemapIds = new Set((await read.sitemapPageIds()).map((id) => String(id).toLowerCase()));
- const existenceIds = new Set((await read.existenceIds()).map((id) => String(id).toLowerCase()));
- const man = await read.manifest();
- // Build key→id from the manifest (IDENTITY authority). A spec page's own pageId (edit-snapshot,
- // C3) OUTRANKS the manifest entry for the same key — use idOf() consistently.
- const idByKey = new Map(
- ((man && man.pages) || [])
- .filter((p) => p && p.key && p.pageId)
- .map((p) => [p.key, p.pageId]),
- );
- // idOf: spec pageId first (highest authority), then manifest key→id (C3 outranks C1).
- const idOf = (p) => p.pageId || idByKey.get(p.key || p.name);
+ // The pass stops waiting for these reads once a check listed before this one has failed (see makeCheckPlan's
+ // unlessFailed): whatever this check would go on to report cannot change what the pass throws then. A failure
+ // in a check listed after this one does not end the wait — this check's own failure outranks it.
+ const reads = await plan.unlessFailed(pageReads(), pagesCheck);
+ if (reads === plan.abandoned) return;
+ if (reads.error) throw reads.error;
+ const { sitemapIds, existenceIds, man, codes } = reads;
+ const idOf = pageIdOf(man);
+ // The code `pageCodes` already fetched, else that one page's own download.
+ const pageCodeOf = async (id) => {
+ const got = codes && codes.get(String(id).toLowerCase());
+ if (!got) return read.pageCode(id);
+ if ('error' in got) throw got.error;
+ return got.code;
+ };
// Imp7: if NO implemented page can be given an id (manifest empty/absent AND no spec pageIds),
// the verifier cannot correlate spec pages to live ids → unableToRun (page-identity), NOT N misses.
const resolvable = implementedPages.filter((p) => !!idOf(p));
@@ -1161,7 +1446,7 @@ async function verifySpec(spec, read, opts = {}) {
let code;
try {
// Download THAT page's code by id (not all pages) — the real reader caches per id.
- code = (await read.pageCode(id)) || '';
+ code = (await pageCodeOf(id)) || '';
} catch (e) {
// A single page's download blip is a specific verifiable miss, not reader-incapacity.
add('page-code', p.name, false, String((e && e.message) || e));
@@ -1192,6 +1477,8 @@ async function verifySpec(spec, read, opts = {}) {
}
}
}
+ });
+ if (implementedPages.length && !unableToRun) plan.early(pageReads, pagesCheck);
// Persona security roles. Existence + SDK-ownership is a sufficient content oracle here (unlike the
// additive view/form checks): the SDK applies a role's privileges with ReplacePrivilegesRole, so an
@@ -1205,7 +1492,21 @@ async function verifySpec(spec, read, opts = {}) {
if (!appRoleIdsP) appRoleIdsP = read.appRoleIds();
return appRoleIdsP;
};
- for (const p of spec.personas || []) {
+ // The same table's privilege set, and the same role's privileges, are asked for by several personas,
+ // grants and flows. Each is read once per pass (a failed read is remembered with it, which is how every
+ // caller already treats a failure: a finding, never a pass).
+ const readPerKey = (fn) => {
+ const answers = new Map();
+ return (key) => {
+ const k = String(key).trim().toLowerCase();
+ if (!answers.has(k)) answers.set(k, Promise.resolve().then(() => fn(key)));
+ return answers.get(k);
+ };
+ };
+ const entityPrivilegesOf = readPerKey((entity) => read.entityPrivileges(entity));
+ const rolePrivilegesOf = readPerKey((roleId) => read.rolePrivileges(roleId));
+ plan.each(spec.personas || [], async ({ add }, personas) => {
+ for (const p of personas) {
const roleName = canonicalPersonaName(p); // trimmed — matches the SDK's created name
if (!roleName) continue;
let row;
@@ -1244,7 +1545,7 @@ async function verifySpec(spec, read, opts = {}) {
const declared = declaredPrivileges(p);
let actual = null;
try {
- actual = await read.rolePrivileges(row.roleid);
+ actual = await rolePrivilegesOf(row.roleid);
} catch { actual = null; }
if (!Array.isArray(actual)) {
// Fail CLOSED: an unreadable role is not a role we can call correct.
@@ -1254,7 +1555,7 @@ async function verifySpec(spec, read, opts = {}) {
const entityPrivileges = new Map();
for (const entity of new Set(declared.map((d) => d.entity))) {
try {
- const privs = await read.entityPrivileges(entity);
+ const privs = await entityPrivilegesOf(entity);
if (Array.isArray(privs)) entityPrivileges.set(entity, privs);
} catch { /* left absent → reported as a finding by compareRolePrivileges */ }
}
@@ -1266,6 +1567,7 @@ async function verifySpec(spec, read, opts = {}) {
}
}
}
+ });
// Role grants (`roleGrants[]`) — privileges ADDED to a pre-existing role. AB#6686429.
//
@@ -1276,7 +1578,8 @@ async function verifySpec(spec, read, opts = {}) {
// role holds beyond the declared set is somebody else's and must never be a finding.
//
// Deliberately NOT checked: the SDK ownership marker. The role belongs to someone else by definition.
- for (const g of spec.roleGrants || []) {
+ plan.each(spec.roleGrants || [], async ({ add }, grants) => {
+ for (const g of grants) {
const declaredName = typeof g.role === 'string' ? g.role.trim() : '';
const label = declaredName || String(g.roleId || '?');
let row;
@@ -1304,7 +1607,7 @@ async function verifySpec(spec, read, opts = {}) {
}
let actual = null;
try {
- actual = await read.rolePrivileges(row.roleid);
+ actual = await rolePrivilegesOf(row.roleid);
} catch { actual = null; }
if (!Array.isArray(actual)) {
add('role-grant-privileges', label, false, 'could not read the role\'s privileges');
@@ -1314,7 +1617,7 @@ async function verifySpec(spec, read, opts = {}) {
const entityPrivileges = new Map();
for (const entity of new Set(declared.map((d) => d.entity))) {
try {
- const privs = await read.entityPrivileges(entity);
+ const privs = await entityPrivilegesOf(entity);
if (Array.isArray(privs)) entityPrivileges.set(entity, privs);
} catch { /* left absent → reported as a finding by compareRolePrivileges */ }
}
@@ -1323,6 +1626,7 @@ async function verifySpec(spec, read, opts = {}) {
? `${declared.length} granted privilege(s) held`
: cmp.missing.map((m) => `${m.entity}.${m.access}: ${m.reason}`).join('; '));
}
+ });
// Business process flow role grants (`businessProcessFlows[].securityRoles`). #513.
//
@@ -1330,7 +1634,8 @@ async function verifySpec(spec, read, opts = {}) {
// named `bpfUniqueName(flow.name)` (live-measured), and holding privileges on it is what lets a
// persona run the process. Subset semantics as everywhere else — a persona legitimately holds far
// more than this one grant.
- for (const f of spec.businessProcessFlows || []) {
+ plan.each(spec.businessProcessFlows || [], async ({ add }, flows) => {
+ for (const f of flows) {
if (!f || !f.securityRoles || !Array.isArray(f.securityRoles.personas)) continue;
if (typeof read.rolePrivileges !== 'function' || typeof read.entityPrivileges !== 'function') continue;
// READ the deployed unique name, do not derive it. A flow authored in Maker, or one renamed
@@ -1369,7 +1674,7 @@ async function verifySpec(spec, read, opts = {}) {
}
let privs = null;
try {
- privs = await read.entityPrivileges(backingTable);
+ privs = await entityPrivilegesOf(backingTable);
} catch { privs = null; }
if (!Array.isArray(privs)) {
// Fail CLOSED: an unreadable backing table is not proof the grant landed. It also catches the
@@ -1393,7 +1698,7 @@ async function verifySpec(spec, read, opts = {}) {
} catch { row = undefined; }
if (!row) { add('bpf-roles', `${f.name} / ${roleName}`, false, 'persona role not found'); continue; }
let actual = null;
- try { actual = await read.rolePrivileges(row.roleid); } catch { actual = null; }
+ try { actual = await rolePrivilegesOf(row.roleid); } catch { actual = null; }
if (!Array.isArray(actual)) { add('bpf-roles', `${f.name} / ${roleName}`, false, "could not read the role's privileges"); continue; }
const actualByPrivilegeId = new Map(actual.map((a) => [String((a && a.privilegeId) || '').trim().toLowerCase(), a && a.depth]));
const declared = BPF_ROLE_ACCESS.map((access) => ({ entity: backingTable, access, scope: 'organization' }));
@@ -1403,6 +1708,7 @@ async function verifySpec(spec, read, opts = {}) {
: cmp.missing.map((m) => `${m.access}: ${m.reason}`).join('; '));
}
}
+ });
// AI app features. The verifier previously had NO awareness of `spec.ai` at all, so a build whose
// every requested AI feature was skipped (admin gate off) or silently not persisted still reported a
@@ -1431,6 +1737,7 @@ async function verifySpec(spec, read, opts = {}) {
// Reader-gated like the other content checks: this needs BOTH `retrieveSetting` (context) and
// `queryRecords` (the proof), so an existence-only reader skips it entirely rather than falling
// back to the unsound effective-value compare. The shipped CLI reader has both.
+ plan.section(async ({ add }) => {
const requestedFeatures = resolveAiFlags(spec);
if (requestedFeatures && typeof read.retrieveSetting === 'function' && typeof read.queryRecords === 'function') {
// MUST be the same identity the build wrote under — `appUniqueName(spec)`, which falls back to
@@ -1452,7 +1759,7 @@ async function verifySpec(spec, read, opts = {}) {
// A small retry on the ABSENT case only: an override row can lag briefly behind the write
// that created it, and a single read turns that lag into a false FAIL on the build's exit
// code (`--verify` gates it). A read ERROR is not retried — see proveAppOverride.
- const proof = app.error ? { error: app.error } : await proveAppOverride(read, app.appModuleId, setting, { attempts: opts.proofAttempts === undefined ? 3 : opts.proofAttempts, delayMs: opts.proofDelayMs === undefined ? 500 : opts.proofDelayMs });
+ const proof = app.error ? { error: app.error } : await proveAppOverride(read, app.appModuleId, setting, proofBudget(opts));
// (2) Context only: what is currently in force (may be the ENVIRONMENT fallback). This read is
// genuinely non-load-bearing — it never participates in the comparison, so a transport
@@ -1475,12 +1782,14 @@ async function verifySpec(spec, read, opts = {}) {
: `requested '${want}' but the app-scope override for '${setting}' holds '${proof.value === '' || proof.value === undefined ? '(empty)' : proof.value}'`);
}
}
+ });
// App routing description (`app.aiDescription`, #583). Asserted only when the spec sets one: absent
// means the build left the deployed value alone, so there is nothing to compare. The oracle is the
// row's own `appmodule.aiappdescription`, found by the SAME identity the build wrote under
// (`appUniqueName(spec)`). Reader-gated on `queryRecords`; a failed read FAILS the check, because a
// routing description nobody can read back is not proven applied.
+ plan.section(async ({ add }) => {
const wantAiDescription = spec.app && typeof spec.app.aiDescription === 'string' && spec.app.aiDescription.trim()
? spec.app.aiDescription : null;
if (wantAiDescription && typeof read.queryRecords === 'function') {
@@ -1500,6 +1809,7 @@ async function verifySpec(spec, read, opts = {}) {
: got ? `the deployed routing description ${shown(got)} differs from the spec's`
: 'the app has no routing description (appmodule.aiappdescription is empty)');
}
+ });
// AI row summaries (`ai.summaries`). AB#6689110.
//
@@ -1529,7 +1839,8 @@ async function verifySpec(spec, read, opts = {}) {
// `--verify` exit code, and it hits most specs, since almost every table has a text column.
const summaryTables = specOptsIntoAi(spec) ? selectSummaryTables(spec) : [];
if (summaryTables.length && typeof read.queryRecords === 'function') {
- for (const logical of summaryTables) {
+ plan.each(summaryTables, async ({ add }, tables) => {
+ for (const logical of tables) {
const modelName = `${String(logical).toLowerCase()} row summary`;
let rows = null;
let readError = null;
@@ -1570,7 +1881,27 @@ async function verifySpec(spec, read, opts = {}) {
+ 'The build reports this as a skip when the environment does not license the row-summary (AI Builder) capability — '
+ 'run against a licensed environment, or set the table to enabled:false so the spec stops requesting it.');
}
+ });
+ }
+
+ // Every check above is registered and none has run yet: run them. The reads overlap (at most
+ // `concurrency` at a time); the report below does not depend on which answered first.
+ //
+ // A page read the pass gave up on (see makeCheckPlan) can still be running when the pass ends: a `pac` run outlives
+ // whoever stopped waiting for it, a batch shim keeps running after the process that started it is ended, and the
+ // temporary folder a download writes to is removed only when that download ends. So the reader is asked to end what it
+ // started, and to say when it has — before the pass returns, or throws, whichever it is, because a verify CLI exits
+ // the moment it does. Best-effort: nothing it throws may replace the outcome of the pass.
+ let ran;
+ try {
+ ran = await plan.run();
+ } finally {
+ if (plan.abandonedReads() && read && typeof read.endPageReads === 'function') {
+ try { await read.endPageReads(); } catch { /* the pass's own outcome stands */ }
+ }
}
+ const { checks, environmentSkipped, phaseSkipped } = ran;
+ const add = (kind, name, present, detail) => checks.push({ kind, name, present: !!present, detail: detail || '' });
// JTBD rollup — translates a technical failure into the business impact it caused. Every other
// check answers "is this artifact deployed?"; this one answers "can this persona still do this
@@ -1621,8 +1952,8 @@ function escapeRe(s) {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
-function expectedViewFetchParts(spec, view) {
- const def = viewDef(spec, view);
+function expectedViewFetchParts(spec, view, resolution) {
+ const def = viewDef(spec, view, resolution);
const conditions = [];
const walk = (group) => {
for (const c of (group && group.conditions) || []) {
@@ -1639,7 +1970,10 @@ function expectedViewFetchParts(spec, view) {
attribute: String(s.attribute || '').toLowerCase(),
descending: s.descending === true,
}));
- return { conditions: conditions.filter((c) => c.attribute && c.operator), orders };
+ // A label the environment could not resolve stays in `def` as the text it was written with; it is no
+ // expectation of what is deployed, and the caller reports it as a problem of its own.
+ const unresolved = new Set(((resolution && resolution.problems) || []).map((p) => `${p.attr}|${p.label}`));
+ return { conditions: conditions.filter((c) => c.attribute && c.operator && !unresolved.has(`${c.attribute}|${c.value}`)), orders };
}
function xmlDecode(value) {
@@ -1780,6 +2114,128 @@ function autoLayoutFieldFlags(spec, formSpec) {
return out;
}
+// What a build does with each OTHER cell of a Notes host before it judges the section — the answer
+// `timelineVerifyProblem` (form-timeline.js) asks for one cell at a time:
+//
+// (cell) → {} not a bound field (a maker's web resource, a quick view, a sub-grid, a spacer): a build
+// never touches it, so it stays
+// { name } a field the build leaves where it is
+// { name, goes } a field the build takes out of the host first — `destructive` when it removes it, which
+// takes --allow-destructive
+// { name, unsure, destructive? } a field verify cannot tell the build's treatment of; `unsure` says why
+//
+// The build repairs the host LAST (repairTimelineHost) and declines a host that still holds another control, but by then
+// its field passes have run, and they take out of the host the fields the spec says belong elsewhere. `--verify` reads the
+// published form BEFORE any of that, so judging the form as published would send the maker to move by hand a field the
+// build moves or removes itself. A bound field leaves the host by:
+// · placement an explicit layout that declares it in another section moves its cell there (placeFieldInSection);
+// · an anchor `fieldOptions[field].after` moves it beside the anchor (applyFieldPositions) — on any layout, whatever
+// `prune` says — unless the anchor is not on the form or sits in a section the build owns, where no field
+// is placed (planFieldAdjacent). The build places anchored fields in DEPENDENCY order, so an anchor that
+// sits in the host but has an anchor of its own is moved out first, and the field follows it (canAnchor);
+// · the prune an explicit layout with prune on removes a field it does not list. That is `formRemovals`, the function
+// behind the destructive gate, so the two cannot disagree about which fields go; the removal needs
+// --allow-destructive.
+//
+// What a pass does is predicted only for a field the published form has ONE cell of. Each of those passes acts on a single cell
+// of a field — the first it finds in the form's order AT THAT MOMENT, and the prune removes one cell of a field per run — and that
+// is not the published order: the topology pass has reordered tabs and sections and moved named sections between tabs by then
+// (planOrderMoves), and a pass can move the very cell a later pass looks for. With two cells in different sections nothing
+// short of replaying the build says which one it acts on, so for a field the form has more than once that a pass WOULD act on
+// verify does not predict either way: it says it cannot tell (`unsure`), rather than promise a repair the build then declines or
+// send the maker to move by hand what the build moves itself. A field that no pass touches stays whichever cell is acted on, so
+// that stays a plain "the build leaves it", one cell of it or several. The same uncertainty reaches a field anchored to an ANCHOR
+// the form has more than once, one of whose cells is in a section the build owns — its own anchor, or the end of a chain of
+// anchors (canAnchor) — and the reason names the field the form has more than once, not an anchor of one cell on the way to it.
+//
+// This is a prediction from the spec and the published form. It cannot see what only happens as the build runs: a removal
+// the maker declines at the preflight, or one the build holds back because the form changed since, or a move it skips
+// because the rows it would split carry a row-span. Where it is wrong the build says so (`skipped.layout`) and the form
+// still fails `--verify` afterwards: the build's own report is the authority, and this spares the maker only the advice
+// that is wrong for the common case.
+//
+// Returns nothing for a layout the compiler cannot read (only a spec that was never validated): nothing can be predicted
+// for it, and `timelineVerifyProblem` then counts every other cell as in the way, as it does for a form it knows nothing about.
+function notesHostInspector(spec, formSpec, deployed) {
+ let def;
+ try { def = compileFormIntent(spec, formSpec); } catch (e) { return undefined; }
+ const want = new Set(formFieldLogicals(def));
+ // An auto layout declares no section for a field and relocates nothing; only an explicit one places.
+ const declaredIn = def.__explicitLayout ? declaredSectionByField(def.tabs) : {};
+ // formRemovals takes a form, and `deployed` is the tabs array verify parsed from its FormXML.
+ const removals = new Set(formRemovals({ tabs: deployed }, def));
+ const anchors = def.__fieldPositions || {};
+ // Every cell that binds a field, per field, in the published form's order, with the section it is in. A quick view carries
+ // its lookup's name in `datafieldname` and is not that field — the build skips it when it looks for a field's cell
+ // (findFieldCellLocation), so it must not count as one here.
+ const cellsOf = new Map();
+ for (const tab of deployed || []) for (const column of (tab && tab.columns) || []) for (const section of (column && column.sections) || []) {
+ for (const row of (section && section.rows) || []) for (const cell of (row && row.cells) || []) {
+ const control = cell && cell.control;
+ if (!control || !control.fieldName || isNonFieldControl(control)) continue;
+ const logical = String(control.fieldName).toLowerCase();
+ if (!cellsOf.has(logical)) cellsOf.set(logical, []);
+ cellsOf.get(logical).push({ section, cell });
+ }
+ }
+ // Whether the build, positioning a field beside `field`, finds it in a section it does not own: `true` — it moves the field
+ // there; `false` — it declines (planFieldAdjacent: the anchor is on the form in a section the build owns, or not on it at
+ // all); `{ chain }` — that depends on which of several cells of a field the build finds first. `chain` runs from `field`
+ // through the anchors it is itself placed after, down to that field: a field placed after one that hangs on such a field is
+ // as uncertain as it is.
+ const canAnchor = (field, seen = new Set()) => {
+ const cells = cellsOf.get(field);
+ // Not on the form: the build adds it, to a section of the form's own, when the layout places it.
+ if (!cells) return want.has(field);
+ if (cells.every((c) => !isEngineHostSection(c.section))) return true;
+ if (cells.length > 1) return { chain: [field] };
+ // One cell, in a section the build owns. It is taken out before anything is positioned beside it when the layout declares
+ // it elsewhere, and when it is anchored itself its own move is made first (dependency order) — a field anchored to it
+ // follows it out. `seen` ends a cycle, which the build refuses to place at all.
+ if (declaredIn[field] !== undefined) return true;
+ const next = anchors[field];
+ if (!next || seen.has(field)) return false;
+ seen.add(field);
+ const below = canAnchor(next, seen);
+ return below && below.chain ? { chain: [field, ...below.chain] } : below;
+ };
+ // Why a field cannot be predicted when its anchors lead to a field the form has more than once, in the chain's own terms: the
+ // anchors on the way have one cell each and are not called otherwise. ['new_other', 'new_area'] reads "its anchor 'new_other'
+ // follows 'new_area', which is on the form more than once"; a chain of one is the anchor itself.
+ const moreThanOnce = (chain) => (chain.length === 1
+ ? `its anchor '${chain[0]}' is on the form more than once`
+ : `its anchor '${chain[0]}' follows ${chain.slice(1).map((f) => `'${f}'`).join(', which follows ')}, which is on the form more than once`);
+ // What the build does with the cell of `logical` it acts on — the same three rules, in the order the passes run them — or
+ // nothing when no pass touches the field.
+ const ruleFor = (logical) => {
+ if (declaredIn[logical] !== undefined) return { goes: `your layout places it in section '${declaredIn[logical]}', so it is moved there` };
+ if (removals.has(logical)) return { goes: 'your layout does not list it, so it is removed', destructive: true };
+ const anchor = anchors[logical];
+ if (!anchor) return undefined;
+ const usable = canAnchor(anchor);
+ if (usable && usable.chain) return { unsure: moreThanOnce(usable.chain) };
+ return usable ? { goes: `fieldOptions places it after '${anchor}', so it is moved there` } : undefined;
+ };
+ return (cell) => {
+ const control = cell && cell.control;
+ if (!control || !control.fieldName || isNonFieldControl(control)) return {};
+ const logical = String(control.fieldName).toLowerCase();
+ const name = `the field '${logical}'`;
+ const cells = cellsOf.get(logical) || [];
+ const mine = cells.find((c) => c.cell === cell);
+ if (!mine) return { name };
+ const rule = ruleFor(logical);
+ if (!rule) {
+ // No pass touches the field, so every cell of it stays. A further cell of it in the same section is named as one, so the
+ // advice never names one field twice.
+ const nth = cells.filter((c) => c.section === mine.section).indexOf(mine);
+ return { name: nth === 0 ? name : `${nth === 1 ? 'a second' : 'another'} cell of ${name}` };
+ }
+ if (cells.length === 1) return Object.assign({ name }, rule);
+ return Object.assign({ name, unsure: 'it is on the form more than once' }, rule.destructive ? { destructive: true } : {});
+ };
+}
+
// Repeated field bindings are valid (body/header), but duplicated cell/control identities are not.
// Collect definitions across the whole form, not only the sections an explicit layout declares.
function formIdentityProblems(xml) {
@@ -1823,6 +2279,124 @@ function formIdentityProblems(xml) {
return problems;
}
+// How an AUTO layout's compiler-named containers are found on a deployed form: by name, because nothing there is
+// matched by label or position (an explicit layout's matches are made where the layout is walked).
+function layoutAutoMatch(deployed) {
+ const lower = (v) => String(v == null ? '' : v).toLowerCase();
+ return {
+ tab: (i) => {
+ const at = deployed.findIndex((t) => lower(t.name) === AUTO_TAB_NAME);
+ return i === 0 && at >= 0 ? at : undefined;
+ },
+ section: (name) => {
+ for (let ti = 0; ti < deployed.length; ti += 1) {
+ for (let ci = 0; ci < (deployed[ti].columns || []).length; ci += 1) {
+ const sections = deployed[ti].columns[ci].sections || [];
+ for (let si = 0; si < sections.length; si += 1) {
+ if (lower(sections[si].name) === name && !isEngineHostSection(sections[si])) return { ti, ci, si };
+ }
+ }
+ }
+ return undefined;
+ },
+ };
+}
+
+// Whether each sub-grid that declares where it goes (`tab` / `column` / `after` / `before`) is where the spec
+// puts it on the DEPLOYED form: in the form-column of its anchor and DIRECTLY beside it (or beside the grid
+// anchored there ahead of it — see neighbourOf), or in the tab (and column) it names. The build converges these,
+// so a grid still elsewhere means the fix was not applied — the same reason every other placement is verified,
+// and the reason this is judged against what the form really holds rather than against the build's report.
+// `match` says where the layout's tabs and sections are on the deployed form: { tab(specIndex) → deployed index,
+// section(name) → { ti, ci, si } }, each undefined when absent. A grid with no placement is not checked.
+function subgridPlacementChecks(spec, f, deployed, match) {
+ const placed = [];
+ for (const sg of f.subgrids || []) {
+ const raw = placementOf(sg);
+ if (!raw || !sg.childEntity) continue;
+ const rel = subgridRelationshipName(spec, f.entity, sg.childEntity);
+ if (rel) placed.push({ raw, rel, key: rel.toLowerCase(), child: String(sg.childEntity).toLowerCase() });
+ }
+ if (!placed.length) return [];
+ const layout = formLayoutNames(f);
+ // The anchored grids of each layout form-column, in declared order: what the build's sequence is made of.
+ const groups = new Map();
+ const resolvedOf = new Map();
+ for (const p of placed) {
+ const resolved = resolvePlacement(layout, p.raw);
+ resolvedOf.set(p, resolved);
+ if (!resolved.ok || !resolved.anchor) continue;
+ const key = `${resolved.tabIndex}:${resolved.columnIndex}`;
+ if (!groups.has(key)) groups.set(key, []);
+ groups.get(key).push({ key: p.key, [resolved.anchor.side]: resolved.anchor.name });
+ }
+ const tabName = (ti) => String((deployed[ti] || {}).name || `#${ti + 1}`);
+ const out = [];
+ const judged = new Set();
+ for (const p of placed) {
+ const resolved = resolvedOf.get(p);
+ const name = `sub-grid ${p.child}`;
+ const fail = (detail) => out.push({ name, ok: false, detail });
+ // A form holds one grid per relationship, and the spec gate refuses an entry that places a grid a second time. A
+ // spec that reaches verify without the gate must not PASS such an entry: the grid sits where the first one puts it,
+ // so the later entry's placement was never what the build honoured.
+ if (judged.has(p.key)) { fail(`the sub-grid for ${p.rel} is listed more than once, and a form holds one grid per relationship — only the first entry's placement is checked`); continue; }
+ judged.add(p.key);
+ if (!resolved.ok) { fail('its placement does not resolve against the layout this spec declares'); continue; }
+ const at = findGridSection(deployed, p.rel);
+ if (!at) { fail(`the grid for relationship ${p.rel} is not on the deployed form`); continue; }
+ const problems = [];
+ if (resolved.anchor) {
+ const anchor = match.section(resolved.anchor.name);
+ if (!anchor) { fail(`its anchor section '${resolved.anchor.name}' is not on the deployed form, so where the grid sits cannot be proven`); continue; }
+ if (at.ti !== anchor.ti || at.ci !== anchor.ci) {
+ problems.push(`the grid is in tab '${tabName(at.ti)}' form-column ${at.ci + 1}, but the spec places it ${resolved.anchor.side} section '${resolved.anchor.name}', in tab '${tabName(anchor.ti)}' form-column ${anchor.ci + 1}`);
+ } else {
+ const key = `${resolved.tabIndex}:${resolved.columnIndex}`;
+ const seq = columnSequence(layout[resolved.tabIndex].columns[resolved.columnIndex].sections, groups.get(key) || []);
+ // Where a token of the sequence sits on the deployed form-column of the anchor. A grid counts only in the
+ // section the build owns: one a maker put in a section of their own is nothing the build places by.
+ const siOf = (token) => {
+ if (token.section !== undefined) {
+ const hit = match.section(token.section);
+ return hit && hit.ti === anchor.ti && hit.ci === anchor.ci ? hit.si : undefined;
+ }
+ const hit = findGridSection(deployed, token.grid);
+ return hit && hit.engine && hit.ti === anchor.ti && hit.ci === anchor.ci ? hit.si : undefined;
+ };
+ const near = neighbourOf(seq, p.key, (token) => siOf(token) !== undefined);
+ if (!near) { fail(`its anchor section '${resolved.anchor.name}' is not on the deployed form, so where the grid sits cannot be proven`); continue; }
+ const refSi = siOf(near.token);
+ const wantSi = near.side === 'after' ? refSi + 1 : refSi - 1;
+ if (at.si !== wantSi) {
+ const sections = deployed[anchor.ti].columns[anchor.ci].sections || [];
+ const ref = tokenLabel(near.token, (gridKey) => (placed.find((q) => q.key === gridKey) || {}).child);
+ const from = near.side === 'after' ? refSi + 1 : at.si + 1;
+ const between = near.side === 'after' ? sections.slice(refSi + 1, at.si) : sections.slice(at.si + 1, refSi);
+ const names = between.map((s, i) => `'${s.name || `#${from + i + 1}`}'`).join(', ');
+ const wrongSide = near.side === 'after' ? at.si < refSi : at.si > refSi;
+ problems.push(wrongSide
+ ? `the grid is ${near.side === 'after' ? 'above' : 'below'} ${ref} in tab '${tabName(anchor.ti)}' form-column ${anchor.ci + 1}, but the spec places it directly ${near.side} it`
+ : `the grid is not directly ${near.side} ${ref} in tab '${tabName(anchor.ti)}' form-column ${anchor.ci + 1}: ${names} ${between.length === 1 ? 'sits' : 'sit'} between them`);
+ }
+ }
+ } else {
+ const ti = match.tab(resolved.tabIndex);
+ if (ti === undefined) { fail(`tab '${layout[resolved.tabIndex].name}' is not on the deployed form, so where the grid sits cannot be proven`); continue; }
+ if (at.ti !== ti) problems.push(`the grid is in tab '${tabName(at.ti)}', but the spec places it in tab '${tabName(ti)}'`);
+ else if (resolved.columnIndex !== undefined && at.ci !== resolved.columnIndex) problems.push(`the grid is in form-column ${at.ci + 1} of tab '${tabName(ti)}', but the spec places it in form-column ${resolved.columnIndex + 1}`);
+ }
+ // What to do about a grid that is not where the spec puts it depends on whether a build will move it: it moves the
+ // section it owns (a `section_grid_*` host) and leaves a grid a maker put in a section of their own. A full build —
+ // `--changed-only` skips a spec that has not changed, which a form an older build left never reaches the fix by.
+ const advice = at.engine
+ ? `run ${FULL_BUILD} to move it`
+ : 'it sits in a section a build did not create, so a build leaves it there — move that section in the maker, or delete it to let a build place a grid of its own';
+ out.push({ name, ok: problems.length === 0, detail: problems.length ? `deployed where the spec does not place it — ${problems.join('; ')} — ${advice}` : '' });
+ }
+ return out;
+}
+
// Parse a deployed form's FormXml into the container tree `--verify` needs to prove a layout.
//
// Why this exists: form verification used to prove only that a form row EXISTS with the right
@@ -1849,7 +2423,7 @@ function parseFormTopology(xml) {
let tab = null, column = null, section = null, row = null, cell = null;
// A <cell> carries its own <labels>, so a cell's label must not be attributed to its section.
let inCell = false;
- const re = /<(\/?)(tab|column|section|row|cell|control|label)\b([^>]*?)(\/?)>/gi;
+ const re = /<(\/?)(tab|column|section|row|cell|control|label|relationshipname)\b([^>]*?)(\/?)>/gi;
const attr = (raw, name) => {
const m = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, 'i').exec(raw || '');
return m ? (m[1] != null ? m[1] : m[2]) : undefined;
@@ -1892,8 +2466,10 @@ function parseFormTopology(xml) {
else if (tag === 'cell') {
inCell = !selfClosing;
// A cell with no <control> child stays control-less, which is what keeps a SPACER from
- // reading as engine-owned.
+ // reading as engine-owned. `auto` is the cell's own attribute (the timeline's cell carries
+ // auto="false"); it is read only so the timeline helpers see the same cell either tree shape gives.
cell = { colspan: Number(attr(raw, 'colspan')) || 1, rowspan: Number(attr(raw, 'rowspan')) || 1, visible: flag(raw, 'visible') };
+ if (attr(raw, 'auto') !== undefined) cell.auto = attr(raw, 'auto');
if (row) row.cells.push(cell);
if (selfClosing) cell = null;
}
@@ -1916,12 +2492,24 @@ function parseFormTopology(xml) {
// marks a timeline or sub-grid host a maker added a field to (isEngineHostSection).
const f = attr(raw, 'datafieldname');
const classId = attr(raw, 'classid');
+ const controlId = attr(raw, 'id');
const disabled = flag(raw, 'disabled');
// A quick view binds a LOOKUP's datafieldname too, but it is not that field: counted as one, it placed
// the lookup wherever the quick view sat and lent the field its visibility and state. The build skips it
// the same way (isNonFieldControl) when it picks the cell to place or patch.
if (f && !isNonFieldControl({ classId })) section.fields.push(String(f).toLowerCase());
- if (cell) cell.control = Object.assign(f ? { fieldName: String(f).toLowerCase() } : {}, classId ? { classId } : {}, disabled === undefined ? {} : { disabled });
+ // `id` is what tells a timeline Dynamics renders (`notescontrol`) from one it does not (a generated id).
+ if (cell) cell.control = Object.assign(f ? { fieldName: String(f).toLowerCase() } : {}, classId ? { classId } : {}, controlId === undefined ? {} : { id: controlId }, disabled === undefined ? {} : { disabled });
+ }
+ // A sub-grid names the relationship it shows as ELEMENT text, not as an attribute:
+ // <control id="…" classid="{E7A81278-8635-4D9E-8D4D-59480B391C5B}"><parameters>
+ // <RelationshipName>new_customer_new_ticket</RelationshipName><TargetEntityType>new_ticket</TargetEntityType>…
+ // It is the only parameter verify reads — it is what says WHICH grid a section holds — so it is read up to the
+ // next tag and kept on the control for findGridSection (lib/form-subgrid-placement.js).
+ else if (tag === 'relationshipname' && !selfClosing && cell && cell.control) {
+ const end = s.indexOf('<', re.lastIndex);
+ const text = (end < 0 ? s.slice(re.lastIndex) : s.slice(re.lastIndex, end)).trim();
+ if (text) cell.control.relationshipName = decodeXmlEntities(text);
}
}
return tabs;
@@ -2024,4 +2612,4 @@ function appShellReferencesPage(spec, key) {
return false;
}
-module.exports = { verifySpec, hasElement, subareaHasDashboard, subareaDashboardHasLauncher, liveNavEntries, subareaHasGenPage, appShellReferencesPage, layoutColumnNames, parseFetchXml };
+module.exports = { verifySpec, hasElement, subareaHasDashboard, subareaDashboardHasLauncher, liveNavEntries, subareaHasGenPage, appShellReferencesPage, layoutColumnNames, parseFetchXml, notesHostInspector };
diff --git a/plugins/model-apps/scripts/lib/view-filter-labels.js b/plugins/model-apps/scripts/lib/view-filter-labels.js
new file mode 100644
index 000000000..5bb19bad7
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/view-filter-labels.js
@@ -0,0 +1,634 @@
+'use strict';
+// Resolve the option LABELS a view filter names to the option VALUES the platform stores (ADO 6691114).
+//
+// A view filter may write a Choice option as its label — `{ "attr": "new_tier", "op": "eq", "value": "Gold" }`
+// — and the FetchXML condition needs the option's integer. The build used to derive that from the spec
+// alone (`choiceValueMap`, app-spec.js): the options a spec column declares inline, or those of a global
+// choice the spec declares, numbered 100000000 + index. That is only the right answer when THIS build
+// created the option set. It silently was not when
+// 1. the filter is on a choice column of an EXISTING table the spec declares no column of — a LOCAL
+// option set (account.industrycode) or one bound to a SYSTEM global choice. The label then reached the
+// FetchXML as the condition's value, passed lint, and Dataverse rejected the saved view mid-build, after
+// the tables and columns had been written;
+// 2. a declared global choice already existed with other values — the SDK's createGlobalOptionSet REUSES
+// an existing set unchanged (a re-run with different options returns the existing set), and a maker
+// may have added or renumbered options in the portal since.
+// (A column bound to a global choice the spec does NOT declare is a lint error — the build would create it
+// with no options — so it never reaches here.)
+//
+// So a label is resolved against the option metadata the ENVIRONMENT holds whenever it can be read, and
+// against the spec only where the environment cannot say. A label that matches nothing is a PROBLEM, never a
+// value, and it is found as early as it can be known (one exception, `specNumberStands`: where the spec numbers
+// the options and the environment has an option on the number the spec gives the label but calls it something
+// else — a maker renamed it — the spec's number is kept, with a warning, unless the environment shows another
+// numbering):
+// - `checkViewFilterLabelsBeforeBuild`, before the build writes anything (and in the dry run): only what the
+// environment ALREADY shows, or what the spec alone decides because the build is about to create it. The
+// build skips it when the spec carries a localized label (`preflightViewLabels`, sdk-build.js): these reads
+// carry labels, and a label-bearing read ahead of a create can cost a multi-language label its other languages;
+// - `resolveViewFilterLabels`, in the views phase once the data model exists: the final answer, with values.
+
+const { choiceValueMap, labelText, labelAliases, lookupColumnsFor } = require('./app-spec.js');
+const { odataLit } = require('./odata.js');
+const { labelsByLcid, readMetadata } = require('./lookup-labels.js');
+
+// A value that is already an option VALUE (or any other number) is not a label, so an integer string — or a
+// comma-separated list of them, the form a multi-select's value takes — is never resolved and never read for.
+// A numeric option label the SPEC declares ("2024") still resolves as a label, as it always did: that is the
+// spec-only rule `viewDef` applies after this, and it asks for nothing from here.
+const INTEGER = /^-?\d+(?:\s*,\s*-?\d+)*$/;
+
+// An id or a date is never an option label, so on an attribute the spec does not declare — where it could be
+// anything — it is not worth a read of the table's option sets to find that out. (On a declared Choice column
+// it is still a label that names no option, and is reported as one.)
+const GUID = /^\{?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}\}?$/i;
+const ISO_DATE = /^\d{4}-\d{2}-\d{2}(?:[T ].*)?$/;
+
+// The operators whose value is compared with an option. `lt`/`ge`… on a choice compare option numbers, which
+// no one writes as labels, and `like`/`on`/`this-week`… belong to other column types — so they are left to
+// the spec-only rule `viewDef` has always applied to a declared Choice column.
+const OPTION_OPS = new Set(['eq', 'ne', 'neq', 'in', 'not-in', 'contain-values', 'not-contain-values']);
+
+// How many valid labels an error lists before it says how many it left out — an option set such as
+// industrycode has dozens, and a message that long hides the one line that matters.
+const LABELS_SHOWN = 25;
+
+const lc = (s) => String(s == null ? '' : s).toLowerCase();
+const keyOf = (entity, attr, label) => `${lc(entity)}|${lc(attr)}|${label}`;
+
+// The spec's table by logical name. Not `_graph.entityByLogical`: lint runs this on a half-typed spec, where
+// an entry with no schemaName is a finding for validation to report, and that helper would throw on it.
+const entityOf = (spec, logical) => ((spec && spec.entities) || []).find((e) => e && lc(e.schemaName) === logical);
+
+// The labels the spec itself gives a Choice column's options — inline, or those of a global choice it
+// declares — in the authoring language. Empty for a column bound to a global choice the spec does not declare
+// (a lint error, so not a case a build meets).
+function declaredLabels(spec, column) {
+ const inline = column && Array.isArray(column.options) && column.options.length ? column.options : null;
+ const shared = !inline && column && column.globalChoice
+ ? (((spec.globalChoices || []).find((g) => g && lc(g.name) === lc(column.globalChoice)) || {}).options || [])
+ : [];
+ return (inline || shared).map((o) => labelText(o, spec && spec.languageCode)).filter(Boolean);
+}
+
+// What the spec says about an attribute of the view's table: a declared column (its App Spec type), the
+// primary name column, or a relationship's lookup — or nothing, which is every system column (statuscode,
+// createdon…) and every column of an existing table the spec does not list.
+function declaredAttribute(spec, entity, attr) {
+ if (!entity) return null;
+ const column = (entity.columns || []).find((c) => c && typeof c.schemaName === 'string' && lc(c.schemaName) === attr);
+ if (column) return { type: column.type || 'Text', column };
+ if (entity.primaryAttribute && lc(entity.primaryAttribute.schemaName) === attr) return { type: 'Text' };
+ if (lookupColumnsFor(spec, lc(entity.schemaName)).some((l) => l.logical === attr)) return { type: 'Lookup' };
+ return null;
+}
+
+// Every place a view filter writes a LABEL: [{ view, viewName, entity, attr, label }].
+//
+// A label is a string that is not an integer, in the value of an option-comparing operator, on an
+// attribute that is not a declared non-choice column. An undeclared attribute is included because the spec
+// cannot say it is not a choice — resolving it is what tells (a text column's string is then used as written)
+// — unless the value is an id or a date, which no option is labelled with.
+function labelUses(spec, view) {
+ const out = [];
+ const entityLogical = lc(view && view.entity);
+ const entity = entityOf(spec, entityLogical);
+ for (const f of (view && Array.isArray(view.filters) ? view.filters : [])) {
+ if (!f || typeof f.attr !== 'string') continue;
+ const op = f.op || 'eq';
+ if (!OPTION_OPS.has(op)) continue;
+ const attr = lc(f.attr);
+ const declared = declaredAttribute(spec || {}, entity, attr);
+ if (declared && declared.type !== 'Choice' && declared.type !== 'MultiChoice') continue;
+ // in / not-in read values[] and everything else reads value — exactly what viewDef sends.
+ const tokens = op === 'in' || op === 'not-in' ? (Array.isArray(f.values) ? f.values : []) : (f.value === undefined ? [] : [f.value]);
+ for (const token of tokens) {
+ if (typeof token !== 'string' || INTEGER.test(token)) continue;
+ if (!declared && (GUID.test(token) || ISO_DATE.test(token))) continue;
+ out.push({ view, viewName: view.name, entity: entityLogical, attr, label: token });
+ }
+ }
+ return out;
+}
+
+const hasLabelUses = (spec, view) => labelUses(spec, view).length > 0;
+
+// Dataverse sends an option set as:
+// { "value": [ { "LogicalName": "new_tier",
+// "OptionSet": { "Options": [ { "Value": 227350001,
+// "Label": { "LocalizedLabels": [ { "Label": "Gold", "LanguageCode": 1033 },
+// { "Label": "Oro", "LanguageCode": 3082 } ],
+// "UserLocalizedLabel": { "Label": "Gold", "LanguageCode": 1033 } } } ] } } ] }
+// A column bound to a global choice carries the shared set in `OptionSet`, exactly as an inline one does —
+// measured live by the download's option-set read (download-model-app.js `readOptionSets`), where a
+// global-bound column returned all of its options through `OptionSet`. `GlobalOptionSet` is deliberately not
+// read: it is populated for a LOCAL set too, and then carries only the set's name. `Label` is read by
+// language code rather than through `UserLocalizedLabel`, which is only the calling user's language — a
+// filter may name a label in any.
+function parseOptions(rawOptions, languageCode) {
+ const options = [];
+ for (const raw of Array.isArray(rawOptions) ? rawOptions : []) {
+ if (!raw || !Number.isFinite(Number(raw.Value))) continue;
+ const byLcid = labelsByLcid(raw.Label);
+ const labels = Object.values(byLcid);
+ const user = raw.Label && raw.Label.UserLocalizedLabel && raw.Label.UserLocalizedLabel.Label;
+ if (typeof user === 'string' && user.trim() && !labels.includes(user)) labels.push(user);
+ options.push({ value: Number(raw.Value), labels, shown: labelText(byLcid, languageCode) || labels[0] || String(raw.Value) });
+ }
+ return options;
+}
+
+// The four attribute kinds a filter can name an option of, each read by its OWN cast: `Attributes` is a
+// heterogeneous collection, so `OptionSet` can only be expanded through a cast segment, and one request per
+// kind is the narrowest read there is. Boolean is left out on purpose — its two options are true/false, and
+// `value="true"` is already what a Two Options filter writes.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query-metadata-web-api
+// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/enumattributemetadata
+const OPTION_CASTS = ['Picklist', 'MultiSelectPicklist', 'State', 'Status'];
+
+// The choice attributes of one table, with every option and every language of its label:
+// { state: 'ok', attributes: Map(logicalName -> { kind, options: [{ value, labels, shown }] }), complete, why? }
+// { state: 'absent' } — the table is not in the environment (every cast answered 404)
+// { state: 'error', why } — nothing could be read
+// `complete` is false when a cast failed: what the others returned is usable, but an attribute missing from
+// an incomplete read is UNKNOWN, not "not a choice".
+//
+// Deliberately NOT `sdk.fetchEntityMetadata`: it is the SDK's whole-table read (about eleven requests), it
+// WRITES the table into the build's workspace — which a read-only dry run must not do — and its `choices`
+// carry only the calling user's language, so a label written in another provisioned language could not match.
+// This is the same cast reads it makes for options, kept to the four kinds a filter can name. The download's
+// `readOptionSets` reads two of these casts for another purpose — declaring option sets, throwing on a failed
+// read — whereas a filter also needs State and Status, and needs `absent` and `complete` told apart from
+// "nothing there". Remove this when the SDK offers a read of a column's options that neither writes the
+// workspace nor drops languages.
+async function readChoiceAttributes(client, entityLogical, { languageCode } = {}) {
+ const base = `/EntityDefinitions(LogicalName='${odataLit(lc(entityLogical))}')/Attributes/Microsoft.Dynamics.CRM.`;
+ const reads = await Promise.all(OPTION_CASTS.map(async (cast) => {
+ try {
+ const res = await client.get(`${base}${cast}AttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)`);
+ return { cast, res };
+ } catch (err) {
+ return { cast, why: (err && err.message) || String(err) };
+ }
+ }));
+ const rows = [];
+ const failures = [];
+ let absent = 0;
+ for (const read of reads) {
+ if (read.why) { failures.push(read.why); continue; }
+ const { res } = read;
+ if (res && res.status === 404) { absent += 1; continue; }
+ if (res && res.status >= 200 && res.status < 300 && res.body && Array.isArray(res.body.value)) { rows.push(read); continue; }
+ const message = res && res.body && res.body.error && res.body.error.message;
+ failures.push(`HTTP ${res && res.status}${message ? `: ${message}` : ''}`);
+ }
+ if (absent === reads.length) return { state: 'absent' };
+ if (!rows.length) return { state: 'error', why: failures[0] || 'no choice metadata was returned' };
+ const attributes = new Map();
+ for (const { cast, res } of rows) {
+ for (const row of res.body.value) {
+ if (!row || typeof row.LogicalName !== 'string') continue;
+ attributes.set(lc(row.LogicalName), { kind: cast, options: parseOptions(row.OptionSet && row.OptionSet.Options, languageCode) });
+ }
+ }
+ const complete = failures.length === 0 && absent === 0;
+ return { state: 'ok', attributes, complete, ...(failures.length ? { why: failures[0] } : {}) };
+}
+
+// One read per table, whoever asks and however often: the answer is memoized as a promise, so concurrent
+// callers share the read. A reader that throws becomes an `error` answer — a label that cannot be resolved is
+// the caller's to report, and must not abort the build or the verify around it.
+function memoizeChoiceReader(read) {
+ const cache = new Map();
+ return (entityLogical) => {
+ const key = lc(entityLogical);
+ if (!cache.has(key)) cache.set(key, Promise.resolve().then(() => read(key)).catch((err) => ({ state: 'error', why: (err && err.message) || String(err) })));
+ return cache.get(key);
+ };
+}
+
+// A reader that asks for each table ONCE per build. Null when there is no client to read with — a test double
+// — so a caller resolves from the spec alone, exactly as before, without pretending to have asked.
+function makeChoiceReader({ client, languageCode } = {}) {
+ if (!client || typeof client.get !== 'function') return null;
+ return memoizeChoiceReader((key) => readChoiceAttributes(client, key, { languageCode }));
+}
+
+// The options of a GLOBAL option set, by name:
+// GET /GlobalOptionSetDefinitions(Name='new_tierset')
+// -> 200 { "MetadataId": "…", "Name": "new_tierset", "IsGlobal": true, "Options": [ { "Value": 227350001, "Label": <Label> }, … ] }
+// Returns { state: 'ok', options } | { state: 'absent' } | { state: 'error', why }, `options` as readChoiceAttributes
+// gives them. The name is lower-cased, as the SDK does when it probes and creates the set.
+//
+// Needed only before the build runs: a declared global choice that already exists is REUSED unchanged
+// (createGlobalOptionSet), so a column the build is about to create against it will hold the environment's
+// options, not the spec's — which cannot be read from a column that does not exist yet. Once the column exists
+// its own `OptionSet` says it, and readChoiceAttributes is enough.
+// Not `$select`ed: `Options` belongs to the derived OptionSetMetadata, which a keyed read of the abstract set
+// type can only project through a cast, and the set is read whole by its documented URL.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query-metadata-web-api
+async function readGlobalChoiceOptions(client, name, { languageCode } = {}) {
+ const got = await readMetadata(client, `/GlobalOptionSetDefinitions(Name='${odataLit(lc(name))}')`);
+ if (got.state !== 'ok') return got;
+ if (!Array.isArray(got.body.Options)) return { state: 'error', why: 'the response carried no Options array' };
+ return { state: 'ok', options: parseOptions(got.body.Options, languageCode) };
+}
+
+// One read per set per build. Null when there is no client, as makeChoiceReader.
+function makeGlobalChoiceReader({ client, languageCode } = {}) {
+ if (!client || typeof client.get !== 'function') return null;
+ return memoizeChoiceReader((key) => readGlobalChoiceOptions(client, key, { languageCode }));
+}
+
+// The labels an error offers, in the authoring language, cut off at LABELS_SHOWN.
+function showLabels(shownLabels) {
+ const head = shownLabels.slice(0, LABELS_SHOWN).join(', ');
+ return shownLabels.length > LABELS_SHOWN ? `${head} … and ${shownLabels.length - LABELS_SHOWN} more` : head;
+}
+
+// Match one label against live options. Exact text, any language: 0 hits is unknown, 1 value resolves, and
+// two DIFFERENT values is refused — one string cannot select two options, and a tie-break would be a coin
+// flip dressed up as an answer.
+function matchOptions(options, label) {
+ const hits = [...new Set(options.filter((o) => o.labels.includes(label)).map((o) => o.value))];
+ if (hits.length === 1) return { value: hits[0] };
+ if (hits.length > 1) return { ambiguous: hits };
+ return {};
+}
+
+const problemOf = (use, reason, extra = {}) => ({ view: use.viewName, entity: use.entity, attr: use.attr, label: use.label, reason, ...extra });
+
+// Judge one label against the options a SOURCE holds — the environment's, or the spec's — as a problem, or null
+// when it names exactly one of them.
+function problemAgainst(use, options) {
+ const m = matchOptions(options, use.label);
+ if (m.value !== undefined) return null;
+ return m.ambiguous ? problemOf(use, 'ambiguous', { values: m.ambiguous }) : problemOf(use, 'unknown', { valid: options.map((o) => o.shown) });
+}
+
+// The spec's own number for a label stands in where the environment does not carry the label by name. Builds used it
+// always before labels were resolved against the environment (2.13.0), so a spec such a build handled must not start
+// to stop where it did not — but the number stands only while nothing in the environment says it is ANOTHER option's.
+//
+// It applies to a column whose options THE SPEC numbers: inline `options[]`, or a global choice `globalChoices[]`
+// declares (`choiceValueMap` holds exactly those, 100000000 + index — what a build writes when it creates them). A
+// maker's edit changes a label and leaves the number, so the spec's number still names the option where
+// - a maker renamed it ("Gold" -> "Gold Tier"): the value did not change, only its label;
+// - a localized option's label is in a language the environment never stored (a label-bearing read ahead of its
+// create can cost it every language but the base one): the option is there, the translation is not;
+// - a maker added a second option with the same label: the spec's number says which one it meant.
+//
+// What it must never do is bind a number the environment shows belongs to a DIFFERENT option. A rebuild never changes
+// an existing column's options and does not create a column or a set it finds, so the spec's numbering is the
+// environment's only where the column or set was built from this very list. Options inserted, removed or reordered in
+// the spec since, a column made elsewhere, or a set another app created in another order leave the two apart, and the
+// spec's number then names something else. The environment shows it in one of these ways, and each refuses the number:
+// - it has no option on the spec's number at all;
+// - the option on the spec's number goes by the name of ANOTHER option of the spec;
+// - a label of THIS spec sits only on other numbers, and that says the numbering moved: the label is one of the labels of the
+// filter's own option (any alias, in any language — its option is elsewhere), or it sits on a number the spec gives ANOTHER
+// option (the options shifted). Where two options carry the label, the spec's number must be one of them.
+//
+// A label that sits on a number the spec does not use proves nothing of the kind: it is an option a maker added or made
+// again — one added in the Default solution takes another publisher's range, one deleted and re-created takes the next
+// free number — and every number the spec has is where it was. Holding that against the spec would stop a build the
+// numbers still serve (2.13.0 built it right) whenever a maker both added an option and renamed another. The price is a
+// column made elsewhere, in another order and with options the spec lacks, whose rename of the filtered option hides the
+// mismatch: nothing contradicts the number, so it is used as 2.13.0 used it, and the warning — which names the option
+// the number landed on — is the trace.
+//
+// Labels are compared without regard to case HERE and nowhere else (a label still resolves by its exact text): an
+// environment whose labels differ from the spec's only in case must not hide that its numbering differs, and refusing
+// more is the safe direction, since the option's integer value always works.
+//
+// Where nothing contradicts the spec's number and nothing confirms it either — a renamed option names nothing the spec
+// can compare — the number is the one earlier builds used, and the caller warns that it is an assumption.
+//
+// Returns { value, option } — `option` is what the environment calls the number — when it stands; { refusal } — the
+// sentence a problem carries to say why the spec's number was not used — when the spec numbers the label and the
+// environment says no; or null when the spec has no number to offer (a column it does not number, a label it does not
+// have: a typo). The label is then the problem `problemAgainst` found.
+function specNumberStands(spec, entity, declared, use, options) {
+ if (!declared || !declared.column) return null;
+ const map = choiceValueMap(entity, spec)[use.attr];
+ const value = map && map[use.label];
+ if (value === undefined) return null;
+ const refuse = (because) => ({ refusal: `The spec numbers "${use.label}" ${value}, but ${because}, so that number is not used.` });
+ const option = options.find((o) => o.value === value);
+ if (!option) return refuse(`the environment has no option numbered ${value}`);
+
+ // The spec's numbers by label, folded: a label that folds onto two numbers ("Open" and "open") keeps both.
+ const numbersOf = new Map();
+ for (const [label, number] of Object.entries(map)) {
+ if (!numbersOf.has(lc(label))) numbersOf.set(lc(label), new Set());
+ numbersOf.get(lc(label)).add(number);
+ }
+ const specNumbers = new Set(Object.values(map));
+ const listed = (numbers) => (numbers.length > 1 ? `${numbers.slice(0, -1).join(', ')} and ${numbers[numbers.length - 1]}` : String(numbers[0]));
+
+ // The option on the number goes by another option's name. Every language it has is read: the second-language label of
+ // another option gives it away even where every label of the spec is on its own number.
+ for (const label of option.labels) {
+ const elsewhere = [...(numbersOf.get(lc(label)) || [])].find((n) => n !== value);
+ if (elsewhere !== undefined) return refuse(`the environment shows another numbering (the option numbered ${value} there is labelled "${label}", which the spec numbers ${elsewhere})`);
+ }
+ // A label of the spec that sits only on numbers that are not its own. It counts when it is the filter's own option's
+ // (its number IS the one in question) or when it sits on a number the spec gives another option; a number the spec does
+ // not use at all is an option added or re-made, which moves nothing (see above).
+ for (const label of Object.keys(map)) {
+ const own = numbersOf.get(lc(label));
+ const carriers = options.filter((o) => o.labels.some((l) => lc(l) === lc(label)));
+ if (!carriers.length || carriers.some((o) => own.has(o.value))) continue;
+ if (!own.has(value) && !carriers.some((o) => specNumbers.has(o.value))) continue;
+ // The environment's own spelling, where it is not the spec's: the label was found through case folding, and the author is
+ // told what to look for there.
+ const spelled = [...new Set(carriers.flatMap((o) => o.labels.filter((l) => lc(l) === lc(label))))];
+ const as = spelled.some((l) => l !== label) ? ` (as ${spelled.map((l) => `"${l}"`).join(' and ')})` : '';
+ return refuse(`the environment shows another numbering ("${label}"${as} is numbered ${listed([...new Set(carriers.map((o) => o.value))])} there, ${map[label]} in the spec)`);
+ }
+ return { value, option };
+}
+
+// What the build tells the author when the spec's number stands in for a label the environment does not carry. A
+// shared label is one the environment DOES carry on that number; for a missing one the identity of the option is the
+// build's assumption, and the message says so and says how to take the choice out of the build's hands.
+function describeSpecNumber(use, stands, problem) {
+ const where = `'${use.entity}'.'${use.attr}'`;
+ if (problem.reason === 'ambiguous') {
+ return `the environment lists more than one option labelled "${use.label}" on ${where}; the spec numbers "${use.label}" ${stands.value}, which is one of them, so the filter uses ${stands.value}.`;
+ }
+ return `the environment lists no option labelled "${use.label}" on ${where}. The spec numbers "${use.label}" ${stands.value} and the environment has an option with that number, labelled "${stands.option.shown}", so the filter uses ${stands.value} on the assumption that it is the same option under another label; if it is not, use the integer value of the option you mean.`;
+}
+
+// One label against the options the environment holds for the column (or for the set it is bound to): the label names
+// exactly one of them, or — where it names none — the spec's own number stands in for it, or it is a problem. Returns
+// { value } the environment names it;
+// { value, note } the spec's number stands in: `note` is what the build says about the assumption;
+// { problem } the label is a problem — and where the spec had a number for it that the environment refuses, the
+// problem carries the `refusal` that says why that number was not used.
+function judgeLabel(spec, entity, declared, use, options) {
+ const problem = problemAgainst(use, options);
+ if (!problem) return { value: matchOptions(options, use.label).value };
+ const stands = specNumberStands(spec, entity, declared, use, options);
+ if (stands && stands.option) return { value: stands.value, note: describeSpecNumber(use, stands, problem) };
+ return { problem: stands ? { ...problem, refusal: stands.refusal } : problem };
+}
+
+// Resolve every label the views name. `read` is async (entityLogical) => the shape readChoiceAttributes
+// returns, or null to resolve from the spec alone. `readGlobalChoice` is async (set name) =>
+// readGlobalChoiceOptions' shape, or absent: with it, a column bound to a declared global choice whose own options
+// could not be read is resolved from the SET.
+//
+// Returns { value(entity, attr, label) -> number | undefined, problems, warnings, inconclusive }. `value` answers
+// only for a label this call resolved; for anything else `viewDef` keeps its spec-only rule. `inconclusive` lists,
+// as problem-shaped records (reason `unreadable`, with the read's `why`), every label whose answer a FAILED or
+// PARTIAL read left open — each with the value the build falls back to (`assumed`): the spec's own numbering for
+// a column the spec declares, the label as written for one it does not. The build does not halt on these (it must
+// write something, and warns); a caller that PROVES things against the environment — verify — must not take the
+// assumption for a fact.
+//
+// This is the FINAL answer, asked in the views phase once the data model exists, so what the build created is
+// there to read. `prior` is what the pre-flight already resolved (see checkViewFilterLabelsBeforeBuild): final,
+// so it is taken as it is and its tables are not read again.
+// Where each answer comes from, in order — the environment first, because it is what the platform holds:
+// 1. the environment's option set for the attribute, when it has one;
+// 1b. for a column whose options the spec numbers (inline, or a declared global choice) where the environment
+// does not carry the label by name: the spec's own number, when the environment has an option on it and
+// shows no other numbering (specNumberStands), with a warning — otherwise the label is a problem;
+// 2. for a column bound to a declared global choice whose own options could not be read: the global choice
+// itself, which the column is bound to — a set the build reuses unchanged — judged exactly as 1 and 1b are;
+// 3. the spec's own options (inline, or a declared global choice) for a column the spec declares as a
+// Choice, when the environment cannot say — the table is not there yet, or the read failed. This is a
+// FALLBACK, right only for an option set this build created (100000000 + index), so it is never used
+// silently: a warning names the label, the column and the number it was given;
+// 4. otherwise the value is not a label: an attribute the spec does not declare and the environment says
+// is not a choice keeps the string as written.
+async function resolveViewFilterLabels(spec, views, { read, prior, readGlobalChoice } = {}) {
+ const values = new Map();
+ const problems = [];
+ const inconclusive = [];
+ const warnings = [];
+ const warned = new Set();
+ const warnOnce = (message) => { if (!warned.has(message)) { warned.add(message); warnings.push(message); } };
+
+ for (const view of views || []) {
+ const decided = new Set(); // one problem per label per view, however often the view repeats it
+ for (const use of labelUses(spec, view)) {
+ const key = keyOf(use.entity, use.attr, use.label);
+ if (values.has(key) || decided.has(key)) continue;
+ decided.add(key);
+ if (prior && prior.has(key)) { values.set(key, prior.get(key)); continue; }
+
+ const entity = entityOf(spec, use.entity);
+ const declared = declaredAttribute(spec, entity, use.attr);
+ const specMap = declared ? choiceValueMap(entity, spec)[use.attr] : undefined;
+
+ const live = read ? await read(use.entity) : null;
+ const liveAttribute = live && live.state === 'ok' ? live.attributes.get(use.attr) : undefined;
+ const conclusive = !!live && (live.state === 'absent' || (live.state === 'ok' && live.complete));
+ // A read that failed or came back partial: what the environment holds is UNKNOWN, not absent.
+ const unread = !!live && !conclusive;
+
+ if (liveAttribute && liveAttribute.options.length) {
+ const judged = judgeLabel(spec, entity, declared, use, liveAttribute.options);
+ if (judged.problem) problems.push(judged.problem);
+ else { values.set(key, judged.value); if (judged.note) warnOnce(judged.note); }
+ continue;
+ }
+
+ if (declared) {
+ // A column bound to a declared global choice, whose own options the environment did not give: the SET
+ // holds them (the build reuses an existing one unchanged), so it is read itself instead of guessing at
+ // its numbering from the spec.
+ const column = declared.column;
+ const globalBound = !!column && !!column.globalChoice && !(Array.isArray(column.options) && column.options.length > 0);
+ if (globalBound && readGlobalChoice) {
+ const set = await readGlobalChoice(column.globalChoice);
+ if (set && set.state === 'ok') {
+ const judged = judgeLabel(spec, entity, declared, use, set.options);
+ if (judged.problem) problems.push(judged.problem);
+ else { values.set(key, judged.value); if (judged.note) warnOnce(judged.note); }
+ continue;
+ }
+ }
+ // A declared Choice column the environment cannot describe: the spec's own options, which are the
+ // values the build writes when it creates the column.
+ if (specMap && specMap[use.label] !== undefined) {
+ const assumed = specMap[use.label];
+ values.set(key, assumed);
+ if (live) {
+ const why = live.state === 'error' ? `could not be read (${live.why})`
+ : unread ? `could not be read completely (${live.why})`
+ : live.state === 'absent' ? 'is not there' : `lists no options for '${use.attr}'`;
+ warnOnce(`the option metadata of '${use.entity}' ${why}, so the filter value "${use.label}" on '${use.attr}' uses the spec's own numbering (${assumed}), which is right only for an option set this build created.`);
+ }
+ if (unread) inconclusive.push(problemOf(use, 'unreadable', { why: live.why, assumed }));
+ continue;
+ }
+ problems.push(problemOf(use, conclusive ? 'unknown' : 'unreadable', { valid: declaredLabels(spec, declared.column), ...(live && live.why ? { why: live.why } : {}) }));
+ continue;
+ }
+
+ // Not declared in the spec. Only the environment can say whether this is a choice.
+ if (live && live.state === 'error') warnOnce(`could not read the option metadata of '${use.entity}' (${live.why}), so the filter value "${use.label}" on '${use.attr}' is used as written; if '${use.attr}' is a Choice column its label was not resolved.`);
+ else if (live && live.state === 'ok' && !live.complete) warnOnce(`the option metadata of '${use.entity}' could not be read completely (${live.why}), so the filter value "${use.label}" on '${use.attr}' is used as written; if '${use.attr}' is a Choice column its label was not resolved.`);
+ if (unread) inconclusive.push(problemOf(use, 'unreadable', { why: live.why, assumed: use.label }));
+ }
+ }
+ return { value: (entity, attr, label) => values.get(keyOf(entity, attr, label)), problems, warnings, inconclusive };
+}
+
+// A label on a status reason THE BUILD inserts: statusReasons[] are added to the table's `statuscode` by the
+// data-model phase, so until it has run the environment cannot list them.
+const insertsStatusReason = (entity, attr, label) => attr === 'statuscode' && !!entity
+ && (Array.isArray(entity.statusReasons) ? entity.statusReasons : []).some((s) => s && labelAliases(s.label).includes(label));
+
+// The same question asked BEFORE the build writes anything — by the build's pre-flight (sdk-build.js) and by the
+// dry run — so a typo stops the build while nothing has been written, instead of after the data model has been.
+// A half-built app is what the old failure left: the tables and columns written, and then Dataverse rejecting
+// the view.
+//
+// Before the build runs, the environment cannot yet hold what the build is about to create, so each label is
+// judged by whichever side is AUTHORITATIVE for it, and only a DEFINITE answer is a problem:
+// - the environment already has the column: its options are final — a build leaves an existing column's
+// options alone — so a label it does not list is a problem (except a status reason the build inserts, and
+// a label of a column whose options the spec numbers that the environment carries only under another label,
+// when the spec's own number still names an option there and nothing shows another numbering: the views phase
+// uses that number, with a warning — see specNumberStands);
+// - the spec declares a column the environment lacks: the build creates it, from the spec's own options, or
+// bound to the declared global choice — whose options are the ENVIRONMENT's when that set already exists
+// (createGlobalOptionSet reuses it unchanged, so the same rule as for a column it has applies to it) and the
+// spec's when it does not;
+// - anything else — the table is not there yet, a read failed or was partial — cannot be known now. It is NOT
+// a problem here (a false halt would stop a good build); the views phase asks again after the build has
+// run, and that answer is final.
+//
+// `read` is async (table) => readChoiceAttributes' shape; `readGlobalChoice` is async (set name) =>
+// readGlobalChoiceOptions'. Returns { problems, resolved, notes }. `resolved` maps keyOf(table, column, label) to the
+// value of every label whose answer is FINAL: one read straight off a column the environment ALREADY has (the
+// build leaves such a column alone), or off the global choice a column the build is about to create will be bound
+// to, when that set already exists (the build reuses it unchanged). The views phase takes these as they are and
+// asks only about what the build creates. Everything else is the views phase's to compute. `notes` are the
+// warnings the views phase will give for the labels the spec's own number stands in for — said by the views
+// phase, not here, so a build says them once; a dry run has no views phase, and says them itself.
+async function checkViewFilterLabelsBeforeBuild(spec, views, { read, readGlobalChoice } = {}) {
+ const problems = [];
+ const resolved = new Map();
+ const notes = new Set();
+ if (!read) return { problems, resolved, notes: [] }; // no environment to ask: nothing to check ahead of the build
+
+ for (const view of views || []) {
+ const decided = new Set();
+ for (const use of labelUses(spec, view)) {
+ const key = keyOf(use.entity, use.attr, use.label);
+ if (decided.has(key)) continue;
+ decided.add(key);
+
+ const entity = entityOf(spec, use.entity);
+ const declared = declaredAttribute(spec, entity, use.attr);
+ const live = await read(use.entity);
+ const liveAttribute = live && live.state === 'ok' ? live.attributes.get(use.attr) : undefined;
+ const conclusive = !!live && (live.state === 'absent' || (live.state === 'ok' && live.complete));
+
+ if (liveAttribute && liveAttribute.options.length) {
+ const judged = judgeLabel(spec, entity, declared, use, liveAttribute.options);
+ if (judged.problem) {
+ // A status reason the build inserts is not a problem yet: the views phase finds it once it has.
+ if (!(judged.problem.reason === 'unknown' && insertsStatusReason(entity, use.attr, use.label))) problems.push(judged.problem);
+ } else if (judged.note) notes.add(judged.note); // the spec's own number is not handed on as final: its warning is the views phase's
+ else resolved.set(key, judged.value);
+ continue;
+ }
+ if (!conclusive || !declared) continue;
+
+ // A declared column the environment does not have, so the build creates it.
+ const column = declared.column;
+ const inline = !!column && Array.isArray(column.options) && column.options.length > 0;
+ if (column && column.globalChoice && !inline) {
+ const set = readGlobalChoice ? await readGlobalChoice(column.globalChoice) : null;
+ if (!set || set.state === 'error') continue; // cannot tell whether the set exists, so cannot tell whose options it gets
+ if (set.state === 'ok') {
+ const judged = judgeLabel(spec, entity, declared, use, set.options);
+ if (judged.problem) problems.push(judged.problem);
+ else if (judged.note) notes.add(judged.note);
+ // The set exists, so createGlobalOptionSet reuses it unchanged and the column the build creates
+ // holds ITS values. That is final, so it is handed on: were the views phase's own read to fail, it
+ // would otherwise fall back to the spec's 100000000 + index, a number this set never had.
+ else resolved.set(key, judged.value);
+ continue;
+ }
+ // 'absent': the build creates the set from the spec, so the spec's options decide, below.
+ }
+ const specMap = choiceValueMap(entity, spec)[use.attr];
+ if (specMap && specMap[use.label] === undefined) problems.push(problemOf(use, 'unknown', { valid: declaredLabels(spec, column) }));
+ }
+ }
+ return { problems, resolved, notes: [...notes] };
+}
+
+// One line per problem: which view, which column, which label, what is valid — and, where the spec numbers the label
+// and the environment refused that number, why it was not used (a label that names no option is a different thing to a
+// reader who knows a renamed option keeps its number).
+function describeProblem(p) {
+ const where = `view "${p.view}" (${p.entity}): filter on ${p.attr}`;
+ const refusal = p.refusal ? ` ${p.refusal}` : '';
+ if (p.reason === 'ambiguous') {
+ return `${where} — "${p.label}" names more than one option (${p.values.join(', ')}), so it cannot choose between them.${refusal} Use the integer value of the one you mean.`;
+ }
+ if (p.reason === 'unreadable') {
+ return `${where} — could not read the options of ${p.entity}.${p.attr} (${p.why || 'the environment did not answer'}), so "${p.label}" cannot be turned into an option value. Use the option's integer value, or try again once ${p.entity} answers metadata reads.`;
+ }
+ const valid = p.valid && p.valid.length ? ` Valid labels: ${showLabels(p.valid)}.` : '';
+ return `${where} — "${p.label}" is not an option of ${p.entity}.${p.attr}.${valid}${refusal} Use ${valid ? 'one of those labels, or ' : ''}the option's integer value.`;
+}
+
+const describeProblems = (problems) => problems.map((p) => ` - ${describeProblem(p)}`).join('\n');
+
+// What offline lint can say about the labels one view filters on. It can only check what the spec declares,
+// so it says nothing for a label the spec's own options prove, and says so — "checked against the environment
+// at build time" — for the two it cannot prove:
+// - a label not among the options the spec declares: the environment may hold more (a maker adds options,
+// or a declared global choice already existed with others);
+// - a column the spec does not declare: only the environment can say whether it is a Choice at all.
+// (A column bound to a global choice the spec does not declare is already a lint ERROR — reported once, by the
+// column check — so it gets no second word here.)
+// The build halts on a label the environment cannot resolve — before it writes anything where the environment
+// already shows it, otherwise before any view is written — which is what each message tells the author.
+function labelLintWarnings(spec, view) {
+ const entity = entityOf(spec, lc(view && view.entity));
+ if (!entity) return []; // an unknown table is validation's finding, not another warning here
+ const out = [];
+ const seen = new Set();
+ for (const use of labelUses(spec, view)) {
+ const key = `${use.attr}|${use.label}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ const declared = declaredAttribute(spec, entity, use.attr);
+ const head = `View '${view.name}' filters ${use.entity}.${use.attr} on the label "${use.label}"`;
+ if (declared) {
+ const map = choiceValueMap(entity, spec)[use.attr];
+ if (map && map[use.label] === undefined) {
+ out.push(`${head}, which is not among the options this spec declares for it (${showLabels(declaredLabels(spec, declared.column))}). Offline lint cannot see options added in the environment, so the label is checked against the environment at build time, and the build halts, before any view is written, if there is no such option.`);
+ }
+ continue; // a label the spec's own options prove needs no word, and an undeclared global choice is the column check's
+ }
+ out.push(`${head}, but this spec does not declare ${use.attr}. If it is a Choice column the label is checked against the environment at build time, and the build halts, before any view is written, when it names no option; otherwise the value is used as written.`);
+ }
+ return out;
+}
+
+module.exports = {
+ labelUses,
+ hasLabelUses,
+ labelLintWarnings,
+ readChoiceAttributes,
+ readGlobalChoiceOptions,
+ makeChoiceReader,
+ makeGlobalChoiceReader,
+ memoizeChoiceReader,
+ resolveViewFilterLabels,
+ checkViewFilterLabelsBeforeBuild,
+ describeProblem,
+ describeProblems,
+ OPTION_OPS,
+};
diff --git a/plugins/model-apps/scripts/lib/workspace-binding.js b/plugins/model-apps/scripts/lib/workspace-binding.js
new file mode 100644
index 000000000..4925ccb8c
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/workspace-binding.js
@@ -0,0 +1,363 @@
+'use strict';
+// What a persistent `.maker-workspace` does when it meets an environment other than its own.
+//
+// The vendored SDK records the environment a workspace was created for in the workspace manifest, and an SDK
+// for another environment is refused (`WORKSPACE_ORG_MISMATCH`) before anything is read from or written to the
+// workspace. The reason is the one the SDK gives: the workspace's saved copies, baselines and cached metadata
+// are the OTHER environment's, and out-of-box ids are equal across environments, so using it would read and
+// write the wrong rows.
+//
+// The plugin hits this when an app folder that was built against one environment is pointed at another
+// (`--env`, or `--workspace` naming another environment's folder). A build with --apply is the only entry point
+// that opens the app folder's workspace — a dry run, download, ai-preflight, the provision-* scripts, teardown and
+// verify work in throwaway ones, and read from the folder only its baseline file (a dry run also reads its manifest,
+// to warn) — so --apply turns the refusal into the halt below, and a dry run turns what it finds into a warning.
+//
+// A dry run does not open the folder because opening binds it: the SDK writes the environment into the manifest
+// the first time a workspace is opened. A preview builds nothing, so a folder it bound to the environment it only
+// previewed would later refuse the environment the operator meant — with advice that sends them back to, or offers
+// to tear down, an environment nothing was ever built in. A preview needs nothing from the folder either: the reads
+// its live plan makes all go to the server.
+//
+// For the same reason the halt tells a folder that was only ever OPENED (the SDK's manifest listing no artifact, and
+// its empty folders, with nothing else beside them) from one a build saved into. The first is what a preview of an
+// earlier release, or a build that stopped at its start, leaves: no saved copy, receipt or baseline to lose and
+// nothing built in that environment, so there is no environment to go back to and nothing to tear down. The check
+// is conservative — any other file, a link, or anything it cannot read counts as saved work.
+//
+// The SDK's own remedy, `cleanWorkspace()`, discards the SDK's saved copies, metadata and baselines (only its own
+// folders: the plugin's files beside them stay). The plugin never calls it, and the halt never offers to. Those
+// copies can hold edits that were never pushed, and the page-ownership receipts and the baseline
+// (last-applied.json) kept beside them belong to the other environment too, so whether to give them up is the
+// operator's decision — made through `teardown-model-app.js --clear-workspace`, which already refuses while a
+// receipt remains (see also RESET_WORKSPACE in entity-provision.js).
+//
+// Which spellings of ONE environment the halt has to tell apart from another environment. The SDK compares the
+// recorded URL as text, after trimming, lower-casing and dropping trailing slashes, so those never meet it. `--env`
+// takes `https://` + a Dataverse host and nothing else (createAzHttpClient refuses the rest), which leaves one way
+// for a run of this plugin to meet a workspace recorded under another spelling of its own environment: the host's
+// `.api.` form, `<org>.api.crm.dynamics.com` — the host the Web API documentation and the discovery service's
+// `ApiUrl` give — against `<org>.crm.dynamics.com`, the host the environment is opened at. The plugin does not fold
+// the two into one environment:
+// it keys the baseline, the page-ownership receipts, the token it asks for and the origin its HTTP client accepts
+// on the host it was given, so the SDK's refusal agrees with the rest of the plugin, and the way out is the host the
+// folder was opened with. A manifest written by another tool can also carry a path or a port; no `--env` can match
+// that, so only a fresh folder is offered for it.
+// See: https://learn.microsoft.com/power-apps/developer/data-platform/discovery-service (the `ApiUrl` of an environment)
+const fs = require('node:fs');
+const path = require('node:path');
+const { dataverseOrigin } = require('./dataverse-auth.js');
+const { WORKSPACE_MANIFEST } = require('./workspace-paths.js');
+
+// The code of the SDK's refusal (`WorkspaceOrgMismatchError`, which also carries `workspaceInstanceUrl` and
+// `instanceUrl`, the two URLs as they were written).
+const WORKSPACE_ORG_MISMATCH = 'WORKSPACE_ORG_MISMATCH';
+// The code of the SDK's answer to a folder with no manifest — a workspace that was never opened.
+const WORKSPACE_NOT_INITIALIZED = 'WORKSPACE_NOT_INITIALIZED';
+// The plugin's own: the halt for a manifest the SDK could not read at all (below). The SDK has no code for it.
+const WORKSPACE_MANIFEST_INVALID = 'WORKSPACE_MANIFEST_INVALID';
+
+function isWorkspaceOrgMismatch(err) {
+ return !!err && typeof err === 'object' && err.code === WORKSPACE_ORG_MISMATCH;
+}
+
+// A manifest.json the JSON parser rejected. The SDK parses it with `JSON.parse` and lets the SyntaxError out as it is: no
+// code, a position ("Unterminated string in JSON at position 36"), and on newer Node versions a quote of the file. Its
+// name is the only stable mark — the message differs between Node versions — and it is a safe one here because this is
+// only ever asked of what opening a workspace, or asking it for its manifest, threw; neither parses any other file.
+// Listing artifacts is not such a call: it also parses each listed artifact's saved copy and its metadata (to flag the
+// copies with unpushed edits), and a corrupt copy throws the very same SyntaxError. That is why the dry run asks for the
+// manifest rather than for a listing (`workspaceBindingNote`).
+function isManifestParseFailure(err) {
+ return !!err && typeof err === 'object' && err.name === 'SyntaxError';
+}
+
+// The origin a URL names, as printable text, or null when it names none.
+//
+// `dataverseOrigin` is the plugin's definition of an environment, and the only thing printed for one it
+// accepts. The workspace manifest is different: the SDK writes whatever URL its caller passed, so a workspace
+// from an older plugin or another tool can name something the plugin would not accept today, and the text may
+// carry more than an origin:
+// "instanceUrl": "https://user:[email protected]/main.aspx?token=abc"
+// `URL.origin` drops credentials, path, query and fragment, so even then only scheme://host[:port] is shown.
+function originOf(url) {
+ if (typeof url !== 'string') return null;
+ const strict = dataverseOrigin(url);
+ if (strict) return strict;
+ try {
+ const parsed = new URL(url.trim());
+ return /^https?:$/.test(parsed.protocol) ? parsed.origin.toLowerCase() : null;
+ } catch {
+ return null;
+ }
+}
+
+// The host a URL names (lower case, without credentials, port, path, query or fragment), or null for text that is
+// not an http(s) URL.
+function hostOf(url) {
+ if (typeof url !== 'string') return null;
+ try {
+ const parsed = new URL(url.trim());
+ return /^https?:$/.test(parsed.protocol) && parsed.hostname ? parsed.hostname.toLowerCase() : null;
+ } catch {
+ return null;
+ }
+}
+
+// `contoso.api.crm.dynamics.com` -> `contoso.crm.dynamics.com`: the label that makes a host the API host of the
+// environment the host without it names (see the header).
+function withoutApiLabel(host) {
+ return host.replace(/^([^.]+)\.api\./, '$1.');
+}
+
+// How the environment a manifest records relates to the one this run targets:
+// 'spelling' — the same host, recorded with more than its origin (a path, a port, credentials)
+// 'api-host' — the same environment under its other host (`.api.`)
+// 'other' — another environment
+// The `.api.` label is only read as "the API host of the same environment" on a Dataverse host: on any other it is
+// just a label, and two such hosts are two places.
+function relationOf(recordedUrl, runUrl) {
+ const recorded = hostOf(recordedUrl);
+ const run = hostOf(runUrl);
+ if (!recorded || !run) return 'other';
+ if (recorded === run) return 'spelling';
+ const dataverse = (host) => dataverseOrigin(`https://${host}`) !== null;
+ return dataverse(recorded) && dataverse(run) && withoutApiLabel(recorded) === withoutApiLabel(run) ? 'api-host' : 'other';
+}
+
+// The remedies as lines: one is a sentence, several are a list to choose from.
+function remedyLines(choices) {
+ return choices.length === 1
+ ? [`${choices[0][0].toUpperCase()}${choices[0].slice(1)}.`]
+ : ['Choose one:', ...choices.map((choice) => ` • ${choice}`)];
+}
+
+// Whether the manifest at `file` lists no artifact: the SDK writes `"artifacts": []` when it opens a workspace and
+// adds an entry for every artifact it saves. A manifest that does not say it lists none, or cannot be read as one, is
+// not "nothing".
+function listsNoArtifact(file) {
+ try {
+ const manifest = JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
+ return !!manifest && typeof manifest === 'object' && Array.isArray(manifest.artifacts) && manifest.artifacts.length === 0;
+ } catch {
+ return false;
+ }
+}
+
+// Whether `folder` holds nothing a build saved: the SDK's manifest listing no artifact, and otherwise only empty
+// folders — what opening a workspace lays down (`manifest.json`, `.metadata/<type>/` and `<type>/` per artifact type;
+// see the header). Conservative on purpose: "nothing" is only answered when every entry was seen and is one of those,
+// so a file of any other name (a baseline, a receipt, a journal, an operator's note), a link, a manifest that lists an
+// artifact, a tree deeper or larger than that scaffold, and anything that could not be read all count as something.
+// Read-only.
+function holdsNothing(folder) {
+ const MAX_DEPTH = 4; // `.metadata/<type>` is two deep; the rest is margin
+ const MAX_ENTRIES = 200; // the scaffold is about twenty folders
+ let seen = 0;
+ const onlyFolders = (dir, depth) => {
+ let entries;
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return false;
+ }
+ // `isDirectory()` is false for a link, so a link to a folder is not an empty folder.
+ return entries.every((entry) => (seen += 1) <= MAX_ENTRIES && depth < MAX_DEPTH && entry.isDirectory() && onlyFolders(path.join(dir, entry.name), depth + 1));
+ };
+ let entries;
+ try {
+ entries = fs.readdirSync(folder, { withFileTypes: true });
+ } catch {
+ return false;
+ }
+ let manifest = false;
+ for (const entry of entries) {
+ seen += 1;
+ if (entry.isFile() && entry.name === WORKSPACE_MANIFEST) {
+ if (!listsNoArtifact(path.join(folder, entry.name))) return false;
+ manifest = true;
+ } else if (!(entry.isDirectory() && onlyFolders(path.join(folder, entry.name), 1))) {
+ return false;
+ }
+ }
+ return manifest;
+}
+
+// What the halt, and the note a dry run prints, are written from: how the failure to open the folder relates to this
+// run. `err` is what opening the workspace (or asking it for its manifest) threw; null when it is neither the SDK's refusal
+// nor a manifest the JSON parser rejected — the caller handles that as it is.
+// relation 'other' — the folder belongs to another environment (`onlyOpened`: and nothing was ever saved in it)
+// relation 'api-host' — it belongs to this environment, under its other host name
+// relation 'spelling' — it belongs to this host, recorded with more than an origin
+// relation 'none' — its manifest names no usable environment
+// relation 'invalid' — its manifest is not JSON
+function bindingFacts(err, { env, workspaceDir }) {
+ const refused = isWorkspaceOrgMismatch(err);
+ if (!refused && !isManifestParseFailure(err)) return null;
+ const runOrigin = (refused && originOf(err.instanceUrl)) || originOf(env);
+ const workspaceOrigin = refused ? originOf(err.workspaceInstanceUrl) : null;
+ let relation = 'invalid';
+ if (refused) relation = workspaceOrigin ? relationOf(err.workspaceInstanceUrl, runOrigin) : 'none';
+ // Absolute: it is printed for the operator to find the folder and to hand to teardown, which is run from wherever they are.
+ const folder = path.resolve(workspaceDir);
+ return {
+ code: refused ? WORKSPACE_ORG_MISMATCH : WORKSPACE_MANIFEST_INVALID,
+ runOrigin,
+ workspaceOrigin,
+ relation,
+ folder,
+ target: runOrigin || '(unknown)',
+ // The `--env` that makes the SDK accept this folder again. The SDK matches the recorded text itself, so it is only
+ // available when that text IS an origin the plugin takes; a path or a port on it has no `--env` spelling.
+ goBackTo: refused ? dataverseOrigin(err.workspaceInstanceUrl) : null,
+ onlyOpened: relation === 'other' && holdsNothing(folder),
+ };
+}
+
+// The lines of the halt (`preview: false`: the build stopped) or of the dry run's note (`preview: true`: the preview
+// ran, and an --apply would stop). They differ in how they open, and in the one remedy that DELETES from an
+// environment — it belongs to the refusal an operator acts on, not to a preview.
+//
+// The folder is printed on a line of its own and never inside a command. It can be copied exactly from there, and no
+// quoting of it is right for every shell (see `quoting` below).
+function describeBinding(facts, { preview }) {
+ const { folder, target, workspaceOrigin, goBackTo } = facts;
+ const fresh = 'use a fresh app folder (copy app-spec.json and the files it names into it), or pass --workspace <a new folder>';
+ // Said once for every case whose recorded URL is not an https origin: `--env` cannot be given one.
+ const unspellable = 'recorded in a form --env cannot take (a path, a port, credentials or another scheme), so no --env value can match it';
+ const stopped = preview
+ ? 'this preview works in a temporary workspace, so it ran as normal; a build with --apply would stop before reading or writing anything in this app\'s workspace folder'
+ : 'the build stopped before reading or writing anything in its workspace folder';
+ const lead = (state) => `${stopped}, which ${state}:`;
+ // A folder with no environment to go back to is moved, not deleted: it can hold what a new workspace does not get back.
+ const noEnvironmentRemedies = [
+ ...remedyLines([
+ 'move the folder aside (rename it) and run again: the build then opens a new workspace for this environment',
+ fresh,
+ ]),
+ 'Do not delete it: it can hold page-ownership receipts (the proof a rebuild needs to update pages it created) and the baseline (last-applied.json), which a new workspace does not get back. The build never clears or re-binds a workspace for you.',
+ ];
+ const lines = [];
+ if (facts.relation === 'invalid') {
+ lines.push(
+ lead('has a manifest.json that is not valid JSON, so it names no environment'),
+ ` ${folder}`,
+ ` this run targets: ${target}`,
+ 'The SDK keeps the environment a workspace belongs to in that file, so it cannot tell whether this folder is this environment\u2019s. Nothing in it was read or changed.',
+ ...noEnvironmentRemedies,
+ );
+ } else if (facts.relation === 'none') {
+ lines.push(
+ lead('records no usable environment in its manifest.json'),
+ ` ${folder}`,
+ ` this run targets: ${target}`,
+ 'It names no environment, so there is none to go back to. Nothing in it was read or changed.',
+ ...noEnvironmentRemedies,
+ );
+ } else if (facts.relation === 'spelling') {
+ lines.push(
+ lead('records this environment\'s URL in a form --env cannot take (a path, a port, credentials or another scheme)'),
+ ` ${folder}`,
+ ` this run targets: ${target}`,
+ `It is the same environment, but the SDK compares the recorded URL as text (ignoring only case and trailing slashes), so no --env value can match it. Nothing was changed.`,
+ ...remedyLines([`${fresh} — the old folder is left as it is`]),
+ );
+ } else if (facts.relation === 'api-host') {
+ lines.push(
+ lead('was opened for this environment under its other host name'),
+ ` ${folder}`,
+ ` workspace was opened as: ${workspaceOrigin}`,
+ ` this run targets: ${target}`,
+ `These are two host names of one environment (the .api. host is its API URL), but the SDK binds a workspace to the URL it was opened with, compared as text, and this plugin keeps the folder's page-ownership receipts and baseline (last-applied.json) under the host it was given as well, so it does not treat them as one.${goBackTo ? '' : ` The folder's URL is also ${unspellable}.`} Nothing was changed.`,
+ ...remedyLines([
+ ...(goBackTo ? [`run again with the host the folder was opened with: --env ${goBackTo}`] : []),
+ `${fresh} — the old folder is left as it is`,
+ ]),
+ );
+ } else if (facts.onlyOpened) {
+ lines.push(
+ lead('was only ever opened for another environment'),
+ ` ${folder}`,
+ ` workspace belongs to: ${workspaceOrigin}`,
+ ` this run targets: ${target}`,
+ `It holds nothing a build saved — no saved copies, page-ownership receipts or baseline, only the manifest and the empty folders the SDK lays down when it opens a workspace — so it was only ever opened for ${workspaceOrigin} (an earlier preview, or a build that stopped at its start, leaves exactly this), and nothing was built there for a teardown to remove. The build never clears or re-binds a workspace for you, so the folder has to go by hand; nothing is lost by that.`,
+ ...remedyLines([
+ 'delete the folder (it holds nothing), or move it aside, and run again: the build then opens a new workspace for this environment',
+ fresh,
+ ]),
+ );
+ } else {
+ // Teardown clears `--workspace`, else the folder beside its spec — which need not be this one. The folder is the
+ // line above, not an argument: a path can hold `$`, a backtick or a quote, and quoting that is right for one shell is
+ // wrong for another. Inside double quotes PowerShell and POSIX shells still expand `$name`, so a command carrying the
+ // path in them could clear a different folder, or none; single quotes are not quotes in cmd.exe.
+ const teardown = `only if that environment's copy of the app is no longer wanted: node scripts/teardown-model-app.js --env ${goBackTo} --spec <app-spec.json> --workspace <the folder printed above> --apply --allow-destructive --clear-workspace — this DELETES what the spec declares from ${goBackTo}; the folder is removed only after a clean teardown, and kept while any page-ownership receipt remains`;
+ const quoting = 'Pass --workspace the folder exactly as printed above, quoted for your shell: in single quotes in PowerShell, bash and zsh (double quotes there still expand $, so a folder named $work would point the delete somewhere else), in double quotes in cmd.exe (it has no single quotes). Without --workspace, teardown clears the folder beside its spec instead, which may be another one.';
+ const withTeardown = !preview && !!goBackTo;
+ lines.push(
+ lead('belongs to a different environment'),
+ ` ${folder}`,
+ ` workspace belongs to: ${workspaceOrigin}`,
+ ` this run targets: ${target}`,
+ `The SDK's saved copies of this app's artifacts, their metadata and baselines in that folder are ${workspaceOrigin}'s, and the ids in them are only valid there (out-of-box ids are equal across environments), so using them for another environment would read and write the wrong rows. The build never clears or re-binds the folder for you: clearing it discards those saved copies, including any edit made in them that was never pushed, and the page-ownership receipts and the baseline (last-applied.json) kept beside them are ${workspaceOrigin}'s too.${goBackTo ? '' : ` The folder's URL is ${unspellable}.`}`,
+ ...remedyLines([
+ ...(goBackTo ? [`build against the environment it belongs to: --env ${goBackTo}`] : []),
+ fresh,
+ ...(withTeardown ? [teardown] : []),
+ ]),
+ ...(withTeardown ? [quoting] : []),
+ );
+ }
+ return lines;
+}
+
+// The halt as an Error (`code`, `environment` = this run's, `workspaceEnvironment` = the workspace's or null), or null
+// when `err` is neither the SDK's refusal of the folder nor a manifest the JSON parser rejected — the caller rethrows
+// that as it is. `err` is what opening the workspace threw, and nothing else.
+//
+// What it says depends on how the folder relates to this run (see `bindingFacts`): another environment (all three
+// remedies, unless nothing was ever saved there), the same environment under its other host or recorded with more than
+// an origin (never the teardown: the run's own environment is the one it would delete from), or no usable environment.
+function workspaceBindingError(err, ctx) {
+ const facts = bindingFacts(err, ctx);
+ if (!facts) return null;
+ return Object.assign(new Error(describeBinding(facts, { preview: false }).join('\n')), {
+ code: facts.code,
+ environment: facts.runOrigin,
+ workspaceEnvironment: facts.workspaceOrigin,
+ });
+}
+
+// What a DRY RUN says about the app folder's workspace, which it does not open: null when the folder is fine for this run
+// (it belongs to this environment, or holds no workspace yet), else the note — the halt an --apply would meet, worded for
+// a preview that ran as normal. `probeSdk` is an SDK over the folder, and it is asked for the workspace manifest and
+// nothing else: `getManifest()` checks the manifest's environment like every other workspace entry point, parses
+// manifest.json and no other file, and writes nothing. Advisory only: anything else that goes wrong in asking (a folder
+// that cannot be read, a probe that cannot answer) gives no note, because nothing here may stop a preview.
+//
+// It is not asked to list the app artifacts, which checks the environment just as well. A listing also parses what it
+// lists — each artifact's saved copy and the metadata kept beside it — to flag the copies that hold unpushed edits:
+// apps/<app id>.json {"name": "Support Desk <- a copy cut short, or
+// .metadata/apps/<app id>.meta.json {"etag": <- its metadata cut short
+// Either throws the same SyntaxError as a manifest.json that is not JSON, so a folder that belongs to THIS environment
+// would be reported as having an invalid manifest ("move the folder aside") when an --apply opens it without trouble.
+// A saved copy says nothing about which environment a folder belongs to, so the preview reads none and says nothing
+// about one.
+async function workspaceBindingNote(probeSdk, ctx) {
+ let failure;
+ try {
+ await probeSdk.getManifest();
+ return null;
+ } catch (err) {
+ failure = err;
+ }
+ try {
+ if (failure && failure.code === WORKSPACE_NOT_INITIALIZED) return null;
+ const facts = bindingFacts(failure, ctx);
+ return facts ? describeBinding(facts, { preview: true }).join('\n') : null;
+ } catch {
+ return null;
+ }
+}
+
+module.exports = { WORKSPACE_ORG_MISMATCH, WORKSPACE_MANIFEST_INVALID, isWorkspaceOrgMismatch, workspaceBindingError, workspaceBindingNote };
diff --git a/plugins/model-apps/scripts/list-connections.js b/plugins/model-apps/scripts/list-connections.js
index b9daabbf2..b11dd319b 100644
--- a/plugins/model-apps/scripts/list-connections.js
+++ b/plugins/model-apps/scripts/list-connections.js
@@ -59,18 +59,35 @@ function extractConnectorId(connectionId) {
return match ? match[1] : '';
}
+// `pac connection list` prints a GRID: after PAC's auth banner, a header row and one row per connection, every column as wide as its widest cell — the header
+// name included — plus one space (live capture, PAC CLI 2.12.2; every value here is synthetic):
+// Connected as [maker001]
+// Id Name API Id Status
+// 00000000000000000000000000000001 Weather /providers/Microsoft.PowerApps/apis/shared_msnweather Connected
+// 00000000000000000000000000000002 SharePoint /providers/Microsoft.PowerApps/apis/shared_sharepointonline Connected
+// So the gap between two header names is not fixed: it is wide while some cell is longer than the name, and ONE space when none is. A name of four characters or
+// fewer leaves "Name" the widest cell of its column, and an environment with no connections leaves every header name the widest cell of its column:
+// Id Name API Id Status
+// 00000000000000000000000000000001 mail /providers/Microsoft.PowerApps/apis/shared_office365 Connected (one connection, named "mail")
+// Id Name API Id Status (no connections: the header alone, and no message)
+// The last two are how PAC builds the grid — no capture of either exists. A header read by two-space gaps between its names missed both, and the empty one is the answer
+// that matters, so the grid's header is recognised by its WORDS: the four names, in this order, and nothing else on the line, whatever the padding between them.
+const PAC_GRID_HEADER = /^Id\s+Name\s+API\s+Id\s+Status$/i;
+
// Whether a row of column names is a connection table's header. A header proves the output is a table, and a table with no rows is an
// EMPTY listing — the answer that sends connection setup on to create a duplicate of a connection the maker already has — so a header is
// recognised only by a COMPLETE column set PAC prints, compared normalized (case and punctuation ignored), and never by one column that
// looks like an id column. A diagnostic that has such a column, or only mentions a connector, is prose:
// Connection Id could not be read.
// Warning: failed to retrieve connector metadata.
-// The column sets are the first from a live capture of `pac connection list` and the others from the layouts the fixtures in
-// tests/list-connections.test.js cover:
+// The first column set is the header of the grid above, which parseWhitespaceTable reads by its words (PAC_GRID_HEADER); here the same names are accepted
+// under a dashed separator, where the columns are cut by the dashes. The others come from the layouts the fixtures in tests/list-connections.test.js cover:
// Id Name API Id Status no dashed separator
// Connection Name Connector Id Connection Id the default fixed-width table, and the plain whitespace one
// Connection Id Connector Id the two-column fixed-width table
-// A build that prints another column set is refused as unreadable, which costs a re-run of `pac connection list`; a guess costs a duplicate.
+// A build that prints another column set is refused as unreadable, which costs a re-run of `pac connection list`; a guess costs a duplicate. PAC's resources hold a
+// `ConnectionListHeader` string too ("Connection ID,Connector ID,Created By"), but this command does not print it — its header is `ConnectionsListHeader`,
+// "Id,Name,API Id,Status", as the grid above shows — so a table with those columns is not accepted.
const CONNECTION_TABLE_COLUMNS = new Set(['id,name,apiid,status', 'connectionname,connectorid,connectionid', 'connectionid,connectorid']);
function isConnectionHeader(names) {
return CONNECTION_TABLE_COLUMNS.has(names.map(normalizeHeader).filter(Boolean).join(','));
@@ -100,21 +117,21 @@ function parseJsonConnections(raw) {
return usableConnectionRows(rows.map(mapConnectionRow), 'JSON');
}
-// PAC's auth banner, printed before any listing, and its one "nothing to list" message:
+// PAC's auth banner, printed before any listing:
// Connected as [email protected] (the form most PAC commands print)
// Connected as [maker001] (the form `pac connection list` printed in a live capture)
-// No connections found.
-// Each is recognised by its exact shape and nothing broader. The banner is a WHOLE line — `Connected as`, then one word or one bracketed
-// alias (a word that opens a bracket must close it), and nothing after it — because a prefix test swallowed a diagnostic joined to it:
+// It is recognised by its exact shape and nothing broader: a WHOLE line — `Connected as`, then one word or one bracketed alias (a word that opens a bracket must
+// close it), and nothing after it — because a prefix test swallowed a diagnostic joined to it:
// Connected as [maker001] Warning: failed to retrieve connections.
-// A failure worded like the empty-state message —
-// No connections could be found because the request failed.
-// — matched the earlier pattern ("no connections ... found") and read as an EMPTY environment, the answer that
-// sends connection setup on to create a duplicate of a connection the maker already has. The trailing period is
-// optional so a build that drops it is not refused, but no other wording is taken for emptiness: a build that
-// words its empty state differently is refused as unreadable, which costs a re-run, not a duplicate.
+//
+// There is NO "nothing to list" sentence in this parser, on purpose. `pac connection list` says an environment has no connections by printing the grid's header with
+// no rows under it (see PAC_GRID_HEADER), never a sentence. PAC's resources do hold one — `ConnectionNotFound`, "No connections were found in the passed
+// environment." — but the command does not print it (PAC CLI 2.12.2: nothing refers to that string), and an earlier version of this script took "No connections found."
+// for the same job, a wording that is in none of PAC's resources. A sentence taken for emptiness is how a failure becomes "no connections" — an earlier, broader pattern
+// read "No connections could be found because the request failed." that way — and that answer sends connection setup on to create a duplicate of a connection the
+// maker already has. A sentence PAC never prints cannot be one that is needed, so a build that does print one is refused as unreadable, which costs a re-run, until a
+// capture shows its exact wording.
const PAC_BANNER = /^connected as (?:[^\s[]\S*|\[[^\]\r\n]+\])$/i;
-const NO_CONNECTIONS_MESSAGE = /^no connections found\.?$/i;
// A line ends at CRLF, a bare CR or LF, and PAC's output is split on all three everywhere. Deleting the CRs instead joined the line a bare
// CR ended to the next one: `Connected as [maker001]\rWarning: …` became a single line that began like the banner.
const LINE_BREAK = /\r\n|\r|\n/;
@@ -158,27 +175,21 @@ function requireBannerPreamble(lines, layout) {
// there — a header followed by
// Warning: failed to retrieve connections.
// was read as an empty listing (the line has no API path) or as a connection (its words filled the id cells).
-// Blank lines and dashed separators are layout, and PAC's own empty-state message is the one non-row line
-// allowed — only when no row is listed, since it would contradict one. Anything else refuses the listing, the
+// Blank lines and dashed separators are layout. Anything else that is not a row refuses the listing, the
// wrapped tail of a long name that older builds print on a second line included: a refusal costs a re-run of
// `pac connection list`, where a guess costs a duplicate connection.
function readTableRows(lines, readRow, layout) {
const rows = [];
- let emptyMessage = null;
for (const line of lines) {
const text = line.trim();
// The auth banner is recognised wherever it falls; any other text is not.
if (!text || /^[\s-]+$/.test(text) || PAC_BANNER.test(text)) continue;
- if (NO_CONNECTIONS_MESSAGE.test(text)) { emptyMessage = text; continue; }
const row = readRow(line);
if (!row || !isConnectionRow(row)) {
throw new Error(unreadableListing(null, `unrecognized connection listing — a line under the ${layout} table header is not a connection row`, text));
}
rows.push(row);
}
- if (emptyMessage && rows.length) {
- throw new Error(unreadableListing(null, `unrecognized connection listing — the ${layout} table lists connections and also says there are none`, emptyMessage));
- }
return rows;
}
@@ -210,19 +221,21 @@ function parseFixedWidthTable(raw) {
function parseWhitespaceTable(raw) {
const lines = raw.split(LINE_BREAK).filter((line) => line.trim());
- const headerIndex = lines.findIndex((line) => /Connection Name|Connection Id|Connector|API Id/i.test(line)
- && isConnectionHeader(line.trim().split(/\s{2,}/)));
+ // The grid `pac connection list` prints is found by the words of its header, whatever the padding between them; the other layouts by two-space gaps.
+ const headerIndex = lines.findIndex((line) => PAC_GRID_HEADER.test(line.trim())
+ || (/Connection Name|Connection Id|Connector|API Id/i.test(line) && isConnectionHeader(line.trim().split(/\s{2,}/))));
if (headerIndex === -1) return null; // no table here — not the same as a table with no rows
const headers = lines[headerIndex].trim().split(/\s{2,}/);
const normalizedHeaders = headers.map(normalizeHeader);
- const isIdNameApi = normalizedHeaders.join(',') === 'id,name,apiid,status';
+ const isIdNameApi = PAC_GRID_HEADER.test(lines[headerIndex].trim()) || normalizedHeaders.join(',') === 'id,name,apiid,status';
requireBannerPreamble(lines.slice(0, headerIndex), isIdNameApi ? 'Id/Name/API Id' : 'whitespace');
- // Current PAC builds emit:
+ // Current PAC builds emit the grid described at PAC_GRID_HEADER:
// Id Name API Id Status
// with no dashed separator. Names may contain spaces, so splitting each row on
// whitespace loses the boundary. The connector API path is the stable delimiter.
if (isIdNameApi) {
- // A row is `<id> <name, which may hold spaces> <API path> [<status, which may be several words or none>]`:
+ // A row is `<id> <name, which may hold spaces> <API path> [<status, which may be several words or none>]`, however many spaces PAC left between the cells — one
+ // when a cell is the widest of its column, as in `00000000000000000000000000000001 mail /providers/Microsoft.PowerApps/apis/shared_office365 Connected`:
// 00000000000000000000000000000001 Contoso Dataverse /providers/Microsoft.PowerApps/apis/shared_commondataservice Not connected
// A line that does not match — a warning, JSON cut short, a connection row in a changed layout — is not a row,
// and readTableRows refuses the listing for it.
@@ -259,7 +272,7 @@ function unreadableListing(raw, why, line, label = line === undefined ? 'first l
// What PAC wrote to stderr on a zero exit. A real `pac connection list` that exits 0 writes nothing there, so text on it means the
// run had something to report that the table on stdout does not show — and a failed listing can still exit 0:
-// stdout Id Name API Id Status (a header and no rows)
+// stdout Id Name API Id Status (a header and no rows)
// stderr Warning: failed to retrieve connections.
// Read from stdout alone, that was an empty environment, the answer that sends connection setup on to create a duplicate. Blank lines are
// not text, so a stderr that is only a trailing newline is clean; the first line that is not blank refuses the listing, quoted.
@@ -301,10 +314,9 @@ function parsePacConnectionList(raw) {
if (fixed) return fixed;
const loose = parseWhitespaceTable(text);
if (loose) return loose;
- // No table and no JSON: only PAC's own message says there is nothing to list.
- const lines = text.split(LINE_BREAK).map((l) => l.trim()).filter((l) => l && !PAC_BANNER.test(l));
- if (lines.length && lines.every((l) => NO_CONNECTIONS_MESSAGE.test(l))) return [];
- throw new Error(unreadableListing(text, lines.length ? 'no connection table, JSON list or "no connections found" message' : 'it printed no listing at all'));
+ // No table and no JSON: nothing here says "no connections" (an empty environment is a header with no rows, read above), so whatever this is, it is refused.
+ const hasText = text.split(LINE_BREAK).some((l) => l.trim() && !PAC_BANNER.test(l.trim()));
+ throw new Error(unreadableListing(text, hasText ? 'no connection table or JSON list' : 'it printed no listing at all'));
}
function sameConnectionId(a, b) {
diff --git a/plugins/model-apps/scripts/list-languages.js b/plugins/model-apps/scripts/list-languages.js
new file mode 100644
index 000000000..f45f6cb52
--- /dev/null
+++ b/plugins/model-apps/scripts/list-languages.js
@@ -0,0 +1,127 @@
+#!/usr/bin/env node
+'use strict';
+// list-languages: the languages an environment has provisioned, each with its culture code and text direction, and
+// the environment's base language — what the generative-page planner decides localization from. It is the planner's
+// first choice, with `pac model list-languages` as its fallback.
+//
+// The SDK's `getEnvironmentLanguages()` answers LCIDs only: three read-only GETs through the org client, in the order
+// base, provisioned, available — nothing cached, nothing written, no workspace used. Culture codes and the
+// right-to-left flag are the host's to map (lib/lcid-cultures.js); an LCID that table does not name stays numeric,
+// has no code or direction, and is reported in `unmapped` — never guessed.
+//
+// The read is strict. An answer the SDK cannot read as a list of languages fails with `ENVIRONMENT_LANGUAGES_UNREADABLE`
+// and a failed read with its own error, so a caller never receives an English default in their place.
+//
+// The planner takes this script as the PREFERRED source of the languages, never the only one. When it exits non-zero —
+// whatever the reason, most often the Azure CLI (missing, signed out, slow, or signed in to another tenant), which
+// `/genpage` has never needed for a page over existing tables or mock data — the planner runs
+// `pac model list-languages --environment '<envUrl>'` instead, which signs in through `pac`. So a failure here must
+// stay a LOUD one (exit 1, `ok: false`, nothing on stdout that reads as an answer) and is never the end of a run:
+// agents/genpage-planner.md, "Detect Configured Languages".
+//
+// Like every script here it emits no telemetry of its own (the plugin's hooks do), and it never prints a token.
+//
+// Usage: node scripts/list-languages.js --env <envUrl>
+// --env the environment's https origin, e.g. https://contoso.crm.dynamics.com
+//
+// Output (stdout, one JSON line), exit 0:
+// { "ok": true,
+// "baseLanguage": { "lcid": 1033, "code": "en-US", "name": "English (United States)", "rtl": false },
+// "languages": [ { "lcid": 1033, "code": "en-US", "name": "English (United States)", "rtl": false },
+// { "lcid": 1025, "code": "ar-SA", "name": "Arabic (Saudi Arabia)", "rtl": true } ],
+// "unmapped": [],
+// "summary": [ "1033 en-US — RTL: No", "1025 ar-SA — RTL: Yes" ] }
+// `languages` are the PROVISIONED languages, in the server's order — the ones labels and pages can be written in.
+// `name` is the English name from this host's Intl and is null when it has none; `code` and `rtl` come from the table.
+// The line is pure ASCII: every other character (the dash in `summary`, an accented name) is a `\uXXXX` escape, which
+// any JSON parser reads back as itself. 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 the planner copies these lines into its plan.
+//
+// Exit codes: 0 read; 1 usage error (stderr names the flag, stdout stays empty) or a failure to read — stdout then holds
+// { "ok": false, "error": "<message>", "code": "<SDK error code, when it has one>" } and stderr the message.
+
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { parseArgs, validateFlags, emitResult, requireDataverseOrigin } = require('./lib/dataverse-auth.js');
+const { createAzHttpClient } = require('./lib/sdk-http-client.js');
+const { describeEnvironmentLanguages } = require('./lib/lcid-cultures.js');
+
+const USAGE = 'Usage: node scripts/list-languages.js --env <envUrl>';
+
+/**
+ * Reads the environment's languages through the vendored SDK and describes them in the planner's terms.
+ * @param {string} env - a Dataverse https origin
+ * @param {object} [httpClient] - the SDK's HttpClient; the az-token one for `env` when omitted (a test seam)
+ */
+async function readLanguages(env, httpClient) {
+ // `createMakerSdk` requires a workspace storage although this read never touches it (the SDK's design: "no
+ // workspace, no cache"). So the storage points at a throwaway directory that is removed whichever way the read
+ // ends — the same shape ai-preflight.js has, which the temp-workspace lifecycle scan in sdk-async-surface.test.js
+ // holds every such script to.
+ const workspaceDir = fs.mkdtempSync(path.join(os.tmpdir(), 'list-languages-'));
+ try {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require('./vendor/cds-maker-sdk.cjs');
+ const sdk = createMakerSdk({
+ workspaceStorage: createNodeWorkspaceStorage(workspaceDir),
+ instanceUrl: env,
+ httpClient: httpClient || createAzHttpClient(env),
+ });
+ return describeEnvironmentLanguages(await sdk.getEnvironmentLanguages());
+ } finally {
+ try {
+ fs.rmSync(workspaceDir, { recursive: true, force: true });
+ } catch {
+ // Cleanup of a directory nothing was written to must not turn a successful read into a failure.
+ }
+ }
+}
+
+async function main() {
+ const argv = process.argv.slice(2);
+ const { flags } = parseArgs(argv);
+ const flagError = validateFlags(argv, { known: ['env'], needValue: ['env'] });
+ if (flagError) {
+ process.stderr.write(`✗ ${flagError}\n${USAGE}\n`);
+ process.exit(1);
+ }
+ if (!flags.env) {
+ process.stderr.write(`${USAGE}\n`);
+ process.exit(1);
+ }
+ let env;
+ try {
+ env = requireDataverseOrigin(flags.env);
+ } catch (err) {
+ process.stderr.write(`✗ ${err.message}\n${USAGE}\n`);
+ process.exit(1);
+ }
+
+ // emitResult() ends the process, so the read's outcome is settled first and emitted outside the try: an exit inside
+ // it would be caught as a failure of the read.
+ let languages;
+ let failure;
+ try {
+ languages = await readLanguages(env);
+ } catch (err) {
+ failure = err;
+ }
+ if (failure) {
+ const code = failure && typeof failure.code === 'string' ? failure.code : undefined;
+ emitResult(false, { ok: false, error: String((failure && failure.message) || failure), ...(code ? { code } : {}) }, { ascii: true });
+ return;
+ }
+ 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`);
+ }
+ emitResult(true, { ok: true, ...languages }, { ascii: true });
+}
+
+module.exports = { readLanguages };
+
+if (require.main === module) {
+ main().catch((err) => {
+ process.stderr.write(`Error: ${err.message}\n`);
+ process.exit(1);
+ });
+}
diff --git a/plugins/model-apps/scripts/provision-entities.js b/plugins/model-apps/scripts/provision-entities.js
index e20f76ebe..7b845e7c4 100644
--- a/plugins/model-apps/scripts/provision-entities.js
+++ b/plugins/model-apps/scripts/provision-entities.js
@@ -9,8 +9,8 @@ const os = require('node:os');
const fs = require('node:fs');
const path = require('node:path');
const { validateProvisionInput } = require('./lib/provision-input.js');
-const { makeRunner, provisionSolution, provisionDataModel, provisionSampleData } = require('./lib/entity-provision.js');
-const { quickCreateEnabledFor, normalizeLanguageCode } = require('./lib/app-spec.js');
+const { makeRunner, provisionSolution, provisionDataModel, provisionSampleData, relationshipsInCreateOrder } = require('./lib/entity-provision.js');
+const { quickCreateEnabledFor, normalizeLanguageCode, askedPrimaryNameLength } = require('./lib/app-spec.js');
const { createAzHttpClient } = require('./lib/sdk-http-client.js');
const { parseArgs, validateFlags, readAliasedFlag, readJsonArg, emitResult, readProvisionedLanguages } = require('./lib/dataverse-auth.js');
@@ -63,6 +63,9 @@ function computeTotal(input, opts) {
// entities + columns + status reasons + alternate keys
for (const e of input.entities || []) {
total += 1; // table
+ // primary name column length step — MUST match provisionDataModel's condition (entity-provision.js) and buildPlan below:
+ // one narrated step (run, or skipped with the reason) whenever the input gives the name column a length.
+ if (askedPrimaryNameLength(e) !== undefined) total += 1;
// quick-create enable step — MUST match provisionDataModel's condition (entity-provision.js) and
// buildPlan below, or [n/total] drifts. This CLI's input has no forms[], so quickCreateEnabledFor
// fires only on an explicit entities[].quickCreate === true.
@@ -112,7 +115,9 @@ function buildPlan(input, opts) {
}
}
- for (const rel of input.relationships || []) {
+ // In the order the apply creates them — a lookup labelled in several languages goes first — so the plan lists
+ // the steps in the order the run takes them (lib/entity-provision.js relationshipsInCreateOrder).
+ for (const rel of relationshipsInCreateOrder(input)) {
if (rel.type === 'OneToMany') {
plan.push(`relationship 1:N ${rel.referenced}->${rel.referencing}`);
} else if (rel.type === 'ManyToMany') {
@@ -120,6 +125,11 @@ function buildPlan(input, opts) {
}
}
+ // After the relationships: where provisionDataModel sets the length of a table it creates (computeTotal counts the step too).
+ for (const e of input.entities || []) {
+ if (askedPrimaryNameLength(e) !== undefined) plan.push(`primary column length ${e.schemaName}.${e.primaryAttribute.schemaName}`);
+ }
+
if (opts.sampleData && input.sampleData) {
for (const [entityKey, records] of Object.entries(input.sampleData)) {
if (Array.isArray(records) && records.length > 0) {
diff --git a/plugins/model-apps/scripts/teardown-model-app.js b/plugins/model-apps/scripts/teardown-model-app.js
index 9288ee97b..cb000c1ce 100644
--- a/plugins/model-apps/scripts/teardown-model-app.js
+++ b/plugins/model-apps/scripts/teardown-model-app.js
@@ -88,6 +88,7 @@ async function teardownModelApp(spec, opts, deps) {
return { ok: false, errors: v.errors };
}
const log = deps.log || (() => undefined);
+ const warn = deps.warn || ((message) => log(`⚠ teardown warning: ${message}`));
const counts = { ok: 0, skip: 0, error: 0 };
const emit = deps.emit || cliEmit(log, { apply: opts.apply, counts });
// Fail-closed: a teardown --apply DELETES real artifacts (app, tables, solution), so it now requires
@@ -139,7 +140,7 @@ async function teardownModelApp(spec, opts, deps) {
}
let r;
try {
- r = await runTeardown(spec, { apply: opts.apply, workspaceDir: opts.workspaceDir, env: opts.env }, { sdk: deps.sdk, emit });
+ r = await runTeardown(spec, { apply: opts.apply, workspaceDir: opts.workspaceDir, env: opts.env }, { sdk: deps.sdk, emit, warn });
} finally {
if (heartbeat) clearInterval(heartbeat);
// Every teardown that FINISHES drops its entry from the tombstone's list of teardowns in flight — a
diff --git a/plugins/model-apps/scripts/tests/ai-app-features-real-bundle.test.js b/plugins/model-apps/scripts/tests/ai-app-features-real-bundle.test.js
index b0700e0b2..060b8ea81 100644
--- a/plugins/model-apps/scripts/tests/ai-app-features-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/ai-app-features-real-bundle.test.js
@@ -340,4 +340,68 @@ test('REAL BUNDLE: disabling is NOT gated — a false is written even when the o
const save = calls.find((c) => c.method === 'POST' && /SaveSettingValue/i.test(c.url));
assert.ok(save, 'a disable must be written even with the gate off');
assert.strictEqual(String(save.body.Value), '1', 'and 1 means DISABLED, not platform default');
+});
+
+// --- an override that is saved but not yet published ---------------------------------------------------
+// A write lands in the app's UNPUBLISHED layer (`componentstate` 1). The proof used to read only the published
+// `appsettings` projection, so a feature on a freshly created app came back `notPersisted` and the build wrote it
+// again after a publish. The bundle now reads the unpublished layer too and answers `applied` with
+// `pendingPublish: true` — which the build must NOT count as in force (rebucketPendingPublish), or a build without
+// `--publish` reports rows that no runtime serves and `--verify` (which reads the published layer) contradicts it.
+
+test('REAL BUNDLE: an override still in the unpublished layer is `applied` with pendingPublish — and the proof reads that layer', async () => {
+ const { sdk, calls } = await freshSdk({ gate: '2', effective: '2', overrideRows: [{ value: '2', componentstate: 1 }] });
+ const r = await sdk.setAppAiFeatures(APP, { formFill: true }, { ...FAST, appModuleId: APP_ID });
+ assert.deepStrictEqual(r.applied, ['formFill']);
+ assert.strictEqual(r.outcomes[0].status, 'applied');
+ assert.strictEqual(r.outcomes[0].pendingPublish, true, 'saved, taking effect when the app is published');
+ const proof = calls.find((c) => c.method === 'GET' && c.url.includes('/appsettings'));
+ assert.match(decodeURIComponent(proof.url), /appsettings\/Microsoft\.Dynamics\.CRM\.RetrieveUnpublishedMultiple\(\)/, 'the proof reads the unpublished-aware function, not the published collection');
+});
+
+test('REAL BUNDLE: a row already in force carries no pendingPublish', async () => {
+ for (const rows of [[{ value: '2', componentstate: 0 }], [{ value: '2' }]]) {
+ const { sdk } = await freshSdk({ gate: '2', effective: '2', overrideRows: rows });
+ const r = await sdk.setAppAiFeatures(APP, { formFill: true }, { ...FAST, appModuleId: APP_ID });
+ assert.deepStrictEqual(r.applied, ['formFill']);
+ assert.strictEqual(r.outcomes[0].pendingPublish, undefined, JSON.stringify(rows));
+ }
+});
+
+test('REAL BUNDLE: the build files a pendingPublish outcome outside `applied`, and a settled one stays where it is', async () => {
+ const { rebucketPendingPublish } = require('../lib/ai-app-settings.js');
+ const { sdk } = await freshSdk({ gate: '2', effective: '2', overrideRows: [{ value: '2', componentstate: 1 }] });
+ const pending = rebucketPendingPublish(await sdk.setAppAiFeatures(APP, { formFill: true }, { ...FAST, appModuleId: APP_ID }));
+ assert.deepStrictEqual([pending.applied, pending.pendingPublish], [[], ['formFill']]);
+ assert.strictEqual(pending.outcomes[0].status, 'pendingPublish');
+ assert.match(pending.outcomes[0].reason, /not in force until the app is published/);
+
+ const { sdk: settled } = await freshSdk({ gate: '2', effective: '2', overrideRows: [{ value: '2' }] });
+ const r = rebucketPendingPublish(await settled.setAppAiFeatures(APP, { formFill: true }, { ...FAST, appModuleId: APP_ID }));
+ assert.deepStrictEqual(r.applied, ['formFill']);
+ assert.strictEqual(r.pendingPublish, undefined, 'no bucket is invented for a result with nothing pending');
+});
+
+test('rebucketPendingPublish moves only the flagged features, once, and tolerates results with no detail', () => {
+ const { rebucketPendingPublish } = require('../lib/ai-app-settings.js');
+ const result = {
+ applied: ['formFill', 'nlSearch', 'm365'], skipped: [], notPersisted: [], unverified: [], failed: [],
+ outcomes: [
+ { feature: 'formFill', status: 'applied', appOverrideExists: true },
+ { feature: 'nlSearch', status: 'applied', appOverrideExists: true, pendingPublish: true },
+ { feature: 'm365', status: 'applied', appOverrideExists: true, pendingPublish: true },
+ ],
+ };
+ rebucketPendingPublish(result);
+ assert.deepStrictEqual(result.applied, ['formFill']);
+ assert.deepStrictEqual(result.pendingPublish, ['nlSearch', 'm365']);
+ assert.deepStrictEqual(result.outcomes.map((o) => o.status), ['applied', 'pendingPublish', 'pendingPublish']);
+ // Idempotent: a second pass finds nothing still reading `applied`.
+ rebucketPendingPublish(result);
+ assert.deepStrictEqual(result.pendingPublish, ['nlSearch', 'm365']);
+ // A result with no per-feature detail (an older SDK shape) is returned untouched.
+ const bare = { applied: ['formFill'] };
+ assert.strictEqual(rebucketPendingPublish(bare), bare);
+ assert.deepStrictEqual(bare, { applied: ['formFill'] });
+ assert.strictEqual(rebucketPendingPublish(undefined), undefined);
});
diff --git a/plugins/model-apps/scripts/tests/ambiguity-sweep.test.js b/plugins/model-apps/scripts/tests/ambiguity-sweep.test.js
index 742e7fe08..12ec66ead 100644
--- a/plugins/model-apps/scripts/tests/ambiguity-sweep.test.js
+++ b/plugins/model-apps/scripts/tests/ambiguity-sweep.test.js
@@ -23,12 +23,13 @@
const { test } = require('node:test');
const assert = require('node:assert');
const vm = require('node:vm');
-const { loadTypescriptOracle, loadBabelOracle } = require('./helpers/typescript-oracle.js');
-const { tokenVocabulary, programsFor, cleanSourceFile, readingAt, isElement, REGEX_BODY, AFTER_WITH_CALL, CONTINUATIONS, FRAMES, PRODUCER_FRAMES, TRIVIA_SEPARATORS, SIGNATURE_FRAMES, SIGNATURE_ENDINGS, HIDING_ENDINGS, CERTAIN_ELEMENTS, GUESSED_ELEMENTS, DECOYS, signaturePages, elementPages } = require('./helpers/angle-frames.js');
+const { loadTypescriptOracle, loadBabelOracle, loadBaseLexer } = require('./helpers/typescript-oracle.js');
+const { tokenVocabulary, programsFor, cleanSourceFile, readingAt, isElement, REGEX_BODY, AFTER_WITH_CALL, CONTINUATIONS, FRAMES, PRODUCER_FRAMES, TRIVIA_SEPARATORS, SIGNATURE_FRAMES, SIGNATURE_ENDINGS, HIDING_ENDINGS, CERTAIN_ELEMENTS, GUESSED_ELEMENTS, HIDDEN_TEXT_ELEMENTS, UNREAD_LIST_ELEMENTS, MEMBER_ELEMENT_FRAMES, NO_MEMBER_ELEMENT_FRAMES, valuedKeywordElements, DECOYS, signaturePages, elementPages, ELEMENT_FRAMES, elementPage, signaturePage, failingLists, LEFT_LISTS, EXACT_DEFAULTS, defaultLists, exactDefaultLists, commentedDefaultLists, commentedConstraintLists, commentedMemberEndings, commentedArrowContinuations, PROSE_SHAPED_LINES, PROSE_OPEN_LINES, PROSE_HIDING_ELEMENTS, PROSE_HIDING_ENDINGS, PROSE_TYPE_ENDINGS, proseElements } = require('./helpers/angle-frames.js');
const { AMBIGUITY_KINDS, blankNonCodePreservingTemplateExpressions } = require('../lib/source-literals.js');
const { extractNavTargets, resolvePageRefs, strayPageRefs, navMalformedRefs, reverseResolveNavIdsReport, navigationFrontier } = require('../lib/pageref-resolver.js');
const { LONG_KEY, MISREAD_PAGES, ELEMENT_AFTER_OPERATOR_PAGES, ELEMENT_LOOKALIKE_PAGES, FUNCTION_TYPE_PAGES } = require('./helpers/misread-page.js');
const { ANY_SPACE } = require('./helpers/jsx-element-fuzz.js');
+const { numberedMemberPages, nestedTextPages, expressionLinePages, literalTagPages, nestedSoupPages, nestedCodePages, nestedTagPages, nestedPairPages, taggedStringPages, importTypePages, accessorNamePages } = require('./helpers/hidden-closing-pages.js');
const ID = '11111111-1111-4111-8111-111111111111';
const CALL = 'navigateTo({pageType:"generative", pageId:"PAGEREF_detail"});';
@@ -745,6 +746,9 @@ test('the committed misread pages are valid to TypeScript, and those that hold a
// TypeScript reads the call in the attribute string as the text of one string (the quote follows white space, so scan() reads a JavaScript string, with escapes), and the call after the
// closing tag in each generator page as the text of a string.
assert.strictEqual(stringTokens(cleanSourceFile(ts, MISREAD_PAGES['jsx-attribute'].code)), 1, 'jsx-attribute: TypeScript reads the token as text in one string');
+ // A regex after a line comment: the token is in the string of a type in the first page and in a regex, in a member's default, in the second.
+ assert.strictEqual(stringTokens(cleanSourceFile(ts, MISREAD_PAGES['generic, a regex after a line comment'].code)), 1, 'a regex after a line comment: TypeScript reads the token as text in a string');
+ assert.strictEqual(regexTokens(cleanSourceFile(ts, MISREAD_PAGES['generic, a regex that holds a closing tag after a line comment'].code)), 1, 'a regex that holds a closing tag after a line comment: TypeScript reads the token as text in a regex');
for (const { name, code } of ELEMENT_LOOKALIKE_PAGES.filter(({ name: what }) => /generator/.test(what))) assert.strictEqual(stringTokens(cleanSourceFile(ts, code)), 1, `${name}: TypeScript reads the token as text in a string`);
for (const { name, code } of ELEMENT_AFTER_OPERATOR_PAGES) {
const source = cleanSourceFile(ts, code);
@@ -768,10 +772,24 @@ function tokenReading(ts, code) {
return { real: tokens.filter(isReal), data: tokens.filter((at) => !isReal(at)), spans: real };
}
-function readTokens(ts, programs) {
- const stats = { generated: 0, valid: 0, exact: 0, guessed: 0, realTokens: 0, dataTokens: 0 };
+// What the lexer before a change (BASE_LIB_PATH) does with a program: whether it accepts it (names no stray token), and then whether it rewrites exactly the calls TypeScript reads or a token that is data.
+function readByBase(base, program, reading) {
+ const resolved = base.resolvePageRefs(new Map([['page', { code: program.code }]]), new Map([['detail', 'gp-detail']]));
+ const accepted = base.strayPageRefs(program.code).length === 0 && resolved.residual.length === 0 && resolved.unresolved.length === 0 && base.navMalformedRefs(program.code).length === 0;
+ if (!accepted) return { accepted };
+ const rewritten = base.extractNavTargets(program.code).filter((target) => target.kind === 'pageref' && !target.afterFrontier).map((target) => `${target.valueStart}-${target.valueEnd}`).sort();
+ const real = reading.spans.map(([from, to]) => `${from}-${to}`).sort();
+ return { accepted, right: JSON.stringify(rewritten) === JSON.stringify(real), rewritesData: rewritten.some((span) => !real.includes(span)) };
+}
+
+// `base`, where it is given, is read the same way: `stats.baseRight` counts the valid programs it reads exactly, `stats.baseMisread` those where it rewrites a token that TypeScript reads as data (what shows that the
+// sweep sees a misread), and `stats.lost` those it reads exactly and this lexer does not (`lostPrograms`): a program that was resolved before must be resolved now.
+function readTokens(ts, programs, base = null) {
+ const stats = { generated: 0, valid: 0, exact: 0, guessed: 0, realTokens: 0, dataTokens: 0, baseRight: 0, baseMisread: 0, lost: 0 };
const problems = [];
const kinds = new Map();
+ const guessedPrograms = [];
+ const lostPrograms = [];
for (const program of programs) {
stats.generated += 1;
const reading = tokenReading(ts, program.code);
@@ -779,20 +797,30 @@ function readTokens(ts, programs) {
stats.valid += 1;
stats.realTokens += reading.real.length;
stats.dataTokens += reading.data.length;
+ const there = base ? readByBase(base, program, reading) : null;
+ if (there && there.right) stats.baseRight += 1;
+ if (there && there.rewritesData) stats.baseMisread += 1;
const stray = new Set(strayPageRefs(program.code).map((found) => found.start));
const missed = reading.data.filter((at) => !stray.has(at));
if (missed.length > 0) problems.push(`${program.label}: a token TypeScript reads as data is not stray (at ${missed}): ${JSON.stringify(program.code)}`);
const frontier = navigationFrontier(program.code);
- if (frontier) { stats.guessed += 1; kinds.set(frontier.kind, (kinds.get(frontier.kind) || 0) + 1); continue; }
+ if (frontier) {
+ stats.guessed += 1;
+ kinds.set(frontier.kind, (kinds.get(frontier.kind) || 0) + 1);
+ guessedPrograms.push(program);
+ if (there && there.right) { stats.lost += 1; lostPrograms.push(program); }
+ continue;
+ }
const extra = [...stray].filter((at) => !reading.data.includes(at));
const rewritten = extractNavTargets(program.code).filter((target) => target.kind === 'pageref' && !target.afterFrontier).map((target) => `${target.valueStart}-${target.valueEnd}`).sort();
if (extra.length > 0) problems.push(`${program.label}: no guess, and a token of a real call is stray (at ${extra}): ${JSON.stringify(program.code)}`);
else if (JSON.stringify(rewritten) !== JSON.stringify(navigationLiteralSpans(ts, cleanSourceFile(ts, program.code)))) problems.push(`${program.label}: no guess, and the calls rewritten are not the real ones: ${JSON.stringify(program.code)}`);
else stats.exact += 1;
}
- return { stats, problems, kinds };
+ return { stats, problems, kinds, guessedPrograms, lostPrograms };
}
-const describeReading = ({ stats, kinds }) => `${stats.generated} programs, ${stats.valid} valid to TypeScript (${stats.dataTokens} tokens read as data, ${stats.realTokens} in real calls): ${stats.exact} read exactly with no guess, ${stats.guessed} refused after a guess (${guessSummary(kinds)})`;
+const describeReading = ({ stats, kinds }) => `${stats.generated} programs, ${stats.valid} valid to TypeScript (${stats.dataTokens} tokens read as data, ${stats.realTokens} in real calls): ${stats.exact} read exactly with no guess, ${stats.guessed} refused after a guess (${guessSummary(kinds)})`
+ + `${stats.baseRight + stats.baseMisread + stats.lost > 0 ? `; the base reads ${stats.baseRight} exactly and misreads ${stats.baseMisread}, and ${stats.lost} of those it reads exactly are refused here` : ''}`;
const guessesOf = (code) => {
const found = [];
blankNonCodePreservingTemplateExpressions(code, { onAmbiguity: (at, kind) => found.push([at, kind]) });
@@ -1069,17 +1097,110 @@ test('sweep (JSX text that starts with a parenthesis, TypeScript parser): the el
assert.strictEqual(reading.stats.guessed, 0, `an element that can be read to its closing tag was guessed at: ${guessSummary(reading.kinds)}`);
assert.strictEqual(reading.stats.exact, reading.stats.valid, 'every valid page is read exactly');
const hiding = [];
- for (const [decoyName, decoy] of Object.entries(DECOYS)) for (const page of elementPages(GUESSED_ELEMENTS, decoy)) hiding.push({ ...page, label: `${decoyName} / ${page.label}` });
+ for (const [decoyName, decoy] of Object.entries(DECOYS)) {
+ // Where a member of a type may begin at the head, a comment, a template or a regex that the text opens could hold the closing tag; a list that the scan cannot read is a guess in every place.
+ for (const page of elementPages(HIDDEN_TEXT_ELEMENTS, decoy, MEMBER_ELEMENT_FRAMES)) hiding.push({ ...page, label: `${decoyName} / ${page.label}` });
+ for (const page of elementPages(UNREAD_LIST_ELEMENTS, decoy)) hiding.push({ ...page, label: `${decoyName} / ${page.label}` });
+ }
const guessed = readTokens(ts, hiding);
assert.deepStrictEqual(guessed.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
assert.strictEqual(guessed.stats.guessed, guessed.stats.valid, 'every valid page whose text could hide its closing tag is refused after a guess');
assert.ok(guessed.stats.valid >= 100, `only ${guessed.stats.valid} such programs were valid`);
+ // After an `=`, a `(`, a `[`, a `:` or an `=>` no member of a type begins: the same texts are elements, for certain, with the decoy after them data and the real call rewritten.
+ const placed = [];
+ for (const [decoyName, decoy] of Object.entries(DECOYS)) for (const page of elementPages(HIDDEN_TEXT_ELEMENTS, decoy, NO_MEMBER_ELEMENT_FRAMES)) placed.push({ ...page, label: `${decoyName} / ${page.label}` });
+ const certain = readTokens(ts, placed);
+ t.diagnostic(`where no member begins: ${describeReading(certain)}`);
+ assert.deepStrictEqual(certain.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(certain.stats.valid >= 150, `only ${certain.stats.valid} such programs were valid`);
+ assert.strictEqual(certain.stats.guessed, 0, `a text read as the element it is, where no type has a member, was guessed at: ${guessSummary(certain.kinds)}`);
+ assert.strictEqual(certain.stats.exact, certain.stats.valid, 'every valid page is read exactly');
+ for (const page of placed.filter((program, index) => index % 7 === 0)) {
+ const source = cleanSourceFile(ts, page.code);
+ if (source) assert.ok(isElement(readingAt(ts, source, page.at)), `TypeScript reads an element: ${page.label}`);
+ }
for (const page of programs.filter((program, index) => index % 11 === 0)) {
const source = cleanSourceFile(ts, page.code);
if (source) assert.ok(isElement(readingAt(ts, source, page.at)), `TypeScript reads an element: ${page.label}`);
}
});
+// A label and a list that TypeScript rejects as one, and a default value that the scan reads exactly (failingLists, defaultLists in helpers/angle-frames.js). Each list is JSX text after a parenthesis in the places an element stands, and
+// the parameter list of a signature in the places a type with members stands (a call signature with and without a return type, a construct signature, a function type), with a decoy after it that holds the closing tag of
+// the head and the text of a call. TypeScript says which programs are pages and which tokens are data: a list read as no list where TypeScript parses a signature reads the text after the signature as an element's, and the
+// call in the decoy as code.
+const SIGNATURE_HEADS_OF_A_LIST = ['<T>(LIST)', '<T>(LIST): T', 'new <T>(LIST)', 'm: <T>(LIST) => T'];
+const listPages = (lists, { elementFrames, signatureFrames, decoys, heads = SIGNATURE_HEADS_OF_A_LIST, endings = [''], every = 1 }) => {
+ const elements = [];
+ const signatures = [];
+ lists.forEach((list, index) => {
+ if (index % every !== 0) return;
+ for (const decoy of decoys) {
+ for (const frame of elementFrames) elements.push({ ...elementPage(frame[1], `<p>(${list})</p>`, decoy), list, label: `element ${frame[0]} / ${JSON.stringify(list)}` });
+ for (const frame of signatureFrames) {
+ for (const head of heads) for (const ending of endings) signatures.push({ ...signaturePage(frame[1], head.replace('LIST', () => list), ending, decoy), list, label: `signature ${frame[0]} / ${head} / ${JSON.stringify(list)} / ${JSON.stringify(ending)}` });
+ }
+ }
+ });
+ return { elements, signatures };
+};
+test('sweep (a list that fails to parse, TypeScript parser): no signature parses, every token is read where TypeScript reads it, and the element is read exactly', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const keywords = [];
+ for (let kind = ts.SyntaxKind.FirstKeyword; kind <= ts.SyntaxKind.LastKeyword; kind += 1) keywords.push(ts.tokenToString(kind));
+ const lists = failingLists(keywords);
+ const { elements, signatures } = listPages(lists, { elementFrames: ELEMENT_FRAMES.slice(0, 4), signatureFrames: SIGNATURE_FRAMES.slice(0, 4), decoys: [DECOYS.string, DECOYS.regex] });
+ // The claim itself: TypeScript parses none of these lists as the parameters of a call signature, a construct signature or a function type, in any place that holds one.
+ const asSignatures = readTokens(ts, signatures);
+ t.diagnostic(`${lists.length} lists as signatures: ${describeReading(asSignatures)}`);
+ assert.ok(asSignatures.stats.generated >= 10000, `only ${asSignatures.stats.generated} signature pages were built`);
+ assert.deepStrictEqual(asSignatures.stats.valid, 0, 'a list that the scan reads as no list is a parameter list');
+ const asElements = readTokens(ts, elements);
+ t.diagnostic(`as elements: ${describeReading(asElements)}`);
+ assert.deepStrictEqual(asElements.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(asElements.stats.valid >= 3000, `only ${asElements.stats.valid} element pages were valid, so the sweep proves little`);
+ // A list that no signature has leaves the element certain: no guess, but for the few lists the scan leaves (a number and `extends`, a modifier before a `/`), and every other valid page is read exactly.
+ assert.ok(asElements.stats.guessed > 0 && asElements.stats.guessed <= 0.03 * asElements.stats.valid, `${asElements.stats.guessed} of ${asElements.stats.valid} pages were guessed at, which the lists the scan leaves explain: ${guessSummary(asElements.kinds)}`);
+ assert.deepStrictEqual([...new Set(asElements.guessedPrograms.map((page) => page.list).filter((list) => !LEFT_LISTS.test(list)))], [], 'an element whose list fails was guessed at');
+ for (const page of elements.filter((program, index) => index % 31 === 0)) {
+ const source = cleanSourceFile(ts, page.code);
+ if (source) assert.ok(isElement(readingAt(ts, source, page.at)), `TypeScript reads an element: ${page.label}`);
+ }
+});
+
+test('sweep (a default value, TypeScript parser): every token is read where TypeScript reads it, and a default the scan reads exactly leaves its element and its signature certain', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const lists = defaultLists();
+ const { elements, signatures } = listPages(lists, { elementFrames: ELEMENT_FRAMES.slice(0, 3), signatureFrames: SIGNATURE_FRAMES.slice(0, 3), decoys: [DECOYS.string, DECOYS.regex, DECOYS.template], every: 2 });
+ const asElements = readTokens(ts, elements);
+ t.diagnostic(`${lists.length} lists as elements: ${describeReading(asElements)}`);
+ assert.deepStrictEqual(asElements.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(asElements.stats.valid >= 2000, `only ${asElements.stats.valid} element pages were valid, so the sweep proves little`);
+ assert.ok(asElements.stats.exact >= 0.25 * asElements.stats.valid && asElements.stats.guessed >= 0.1 * asElements.stats.valid, `${asElements.stats.exact} read exactly and ${asElements.stats.guessed} guessed: both are met`);
+ const asSignatures = readTokens(ts, signatures);
+ t.diagnostic(`as signatures: ${describeReading(asSignatures)}`);
+ assert.deepStrictEqual(asSignatures.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(asSignatures.stats.valid >= 2000 && asSignatures.stats.exact >= 0.25 * asSignatures.stats.valid, `${asSignatures.stats.exact} of ${asSignatures.stats.valid} signature pages were read exactly`);
+
+ // The defaults the scan reads exactly are read exactly: an element with one of them is certain, in every place an element stands, and so is the type that holds it as a call signature or a construct signature with no
+ // return type (a function type and a return type leave the guesses they always did: `<T>(x): T` is JSX text as well). The page of a type has its closing tag in the decoy only, so nothing is hidden in the list.
+ // An element whose text starts with a parenthesis and a colon is exact as an element's text only: in the code of a signature the scan of the page reads it as a call signature that a colon follows.
+ const exactLists = exactDefaultLists();
+ const codeLists = exactLists.filter((list) => !EXACT_DEFAULTS.elementText.some((value) => list.endsWith(value)));
+ const exact = listPages(exactLists, { elementFrames: ELEMENT_FRAMES, signatureFrames: [], decoys: [DECOYS.string, DECOYS.regex, DECOYS.template] });
+ const exactCode = listPages(codeLists, { elementFrames: [], signatureFrames: SIGNATURE_FRAMES.slice(0, 4), heads: ['<T>(LIST)', 'new <T>(LIST)'], decoys: [DECOYS.string, DECOYS.regex, DECOYS.template] });
+ for (const [what, pages] of [['elements', exact.elements], ['signatures', exactCode.signatures]]) {
+ const certain = readTokens(ts, pages);
+ t.diagnostic(`exact defaults as ${what}: ${describeReading(certain)}`);
+ assert.deepStrictEqual(certain.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(certain.stats.valid >= 3000, `only ${certain.stats.valid} ${what} pages were valid, so the sweep proves little`);
+ assert.deepStrictEqual(certain.guessedPrograms.slice(0, 5).map((page) => page.label), [], `a page whose default is read exactly was guessed at (${what})`);
+ assert.strictEqual(certain.stats.exact, certain.stats.valid, 'every valid page is read exactly');
+ }
+});
+
// A signature whose own parameter list holds the closing tag of its head in a string, a template or a comment: `interface I { <T>(x: "</T>") }` is a call signature, and `const e = <T>(x: "</T>;` is an
// element, and both parse with no diagnostic — the text up to the closing tag is the same. So a closing tag that the type reads inside a string, a template or a comment is a guess, whatever follows the `)`.
const HIDING_HEADS = ['<T>(x: "</T>")', "<T>(x: '</T>')", '<T>(x: `</T>`)', '<T>(x /* </T> */)', '<T>(x = "</T>")', '<T>(x: "a</T>b", y)', '<T>(x // </T>\n)', '<T>(x: "\\"</T>")', "<T>(x: '\\'</T>')", '<T>(x: "</T>"): void'];
@@ -1112,6 +1233,344 @@ test('sweep (a call signature whose parameter list holds its own closing tag, Ty
}
});
+// A regex after a line comment (commentedDefaultLists, commentedConstraintLists, commentedMemberEndings and commentedArrowContinuations in helpers/angle-frames.js). The scan of a parameter list reads a `/` after a name or a number
+// as a division, and a line comment ends in a name, a number or a `$` and is trivia to TypeScript, so a `/` that follows one on the next line — after an operator, a keyword or a bracket — begins a regex, whose `)` or closing tag is
+// not the end of the list or of the text:
+// interface I { <T>(a = 1 + // fallback
+// /[)]/); m: '</T>;navigateTo(…);//' }
+// Each family is a place that meets such a regex, with comments that end in a name, a number, a `$`, a letter beyond ASCII, a sign and nothing, and a line break of every kind, and a decoy after it that holds the closing tag of the head and
+// the text of a call — and, where the text of a signature is read to its closing tag, a regex that holds both. TypeScript says which programs are pages and which tokens are data; a division after a name or a number, which is as valid, is
+// in every family that scans a list.
+test('sweep (a regex after a line comment, TypeScript parser): every token is read where TypeScript reads it, and a `/` after a line comment is never a division', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const { elements, signatures } = listPages([...commentedDefaultLists(), ...commentedConstraintLists()], { elementFrames: ELEMENT_FRAMES.slice(0, 2), signatureFrames: SIGNATURE_FRAMES.slice(0, 3), decoys: [DECOYS.string, DECOYS.regex], every: 3 });
+ // The text of a call signature with no return type is read to its closing tag: a later member's default holds the regex, and the regex holds the closing tag and a call.
+ const endings = commentedMemberEndings();
+ const members = SIGNATURE_FRAMES.slice(0, 4).flatMap(([frameName, frame]) => ['<T>(x)', 'new <T>(x)'].flatMap((head) => endings.map((ending) => ({ ...signaturePage(frame, head, ending, DECOYS.string), label: `${frameName} / ${head} / ${JSON.stringify(ending)}` }))));
+ // A generic arrow after each token that leaves a `<` undecided, in the frames where the token and the arrow make a program, and a string that holds a closing tag and a call as the text after it.
+ const after = `; const s = '</T>;navigateTo({pageType:"generative",pageId:"PAGEREF_detail"});//'; const re = /${REGEX_BODY}/; navigateTo({pageType:"generative",pageId:"PAGEREF_detail"});`;
+ const tokenFrames = [['>=', ['type arguments, closed before the token']], ['>>=', ['binary', 'nested type arguments, closed before the token']], ['in', ['for-in head']], ['<', ['type arguments, of a call']],
+ ['yield *', ['generator']], ['void', ['annotation']]];
+ const arrows = tokenFrames.flatMap(([token, names]) => [...labelled(programsFor(token, { after, frames: FRAMES.filter((frame) => names.includes(frame.name)), continuations: commentedArrowContinuations() }))]);
+ const families = [['lists as elements', elements, 1000], ['lists as signatures', signatures, 6000], ['the text of a signature with no return type', members, 900], ['arrows after a token that leaves a `<` undecided', arrows, 1500]];
+ const refusedAfterAGuess = [];
+ for (const [what, programs, least] of families) {
+ const reading = readTokens(ts, programs);
+ t.diagnostic(`${what}: ${describeReading(reading)}`);
+ assert.deepStrictEqual(reading.problems.slice(0, 5), [], `${what}: every token is read where TypeScript reads it`);
+ assert.ok(reading.stats.valid >= least, `${what}: only ${reading.stats.valid} programs were valid, so the sweep proves little`);
+ refusedAfterAGuess.push([what, reading.stats.guessed, reading.stats.valid]);
+ }
+ // The regex after a comment is a guess wherever a scan or a reading of a signature's text meets one, so nearly every valid page of the signatures and of the text of a signature is refused after it: what is read exactly is a function
+ // type whose list holds a regex with no `)` of its own, where the element reading of the text fails at the arrow.
+ for (const [what, guessed, valid] of refusedAfterAGuess.filter(([name]) => /signature/.test(name))) assert.ok(guessed >= 0.9 * valid, `${what}: ${guessed} of ${valid} valid programs were refused after a guess`);
+ for (const page of members.filter((program, index) => index % 17 === 0)) {
+ const source = cleanSourceFile(ts, page.code);
+ if (source) assert.ok(!isElement(readingAt(ts, source, page.at)), `TypeScript reads a signature: ${page.label}`);
+ }
+});
+
+// JSX text that starts with a parenthesis and runs over several lines, one with a `//` in it and a line that starts with a `/` after it (PROSE_COMMENT_LINES, PROSE_PATHS in helpers/angle-frames.js):
+// const e = <p>(optional);
+// https://contoso.com
+// /docs</p>;
+// A type that has the same text for its members reads `//` as a comment, so the `/` on the last line follows the token before the comment — the colon of `https:`, where a type must follow, or a name — and begins
+// no regex that could hold the closing tag: only the element compiles, and it is read for certain, with the decoy after it (a string, a template, a comment, a regex that holds `</p>` and a call) data. The base read the
+// last word of the comment for the token before the `/`, and a lexer that read the comment as nothing refused every such page: the family must stay resolved. The line before the `//` may begin with a parenthesis, a bracket,
+// a quote, a tag or an operator, end in a postfix `!`, a call or an index, have a number with a `.` or an exponent sign, or start with a modifier (PROSE_SHAPED_LINES): each fails as the members of a type, so those pages are
+// read for certain too; where the closing tag could be in the comment (PROSE_HIDING_ELEMENTS, PROSE_HIDING_ENDINGS), a type with the same text compiles
+// too, and the page is a guess.
+test('sweep (JSX text of lines, one with a `//` in it, and a line that starts with a `/`, TypeScript parser): the element is read exactly where no type can have its text, and a guess is made where one can', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ // (The double-quoted string is left out: the text of a call has quotes of its own, and no page holds it.)
+ const decoys = Object.entries(DECOYS).filter(([name]) => name !== 'double-quoted string');
+ // Each element in one place and with one decoy, the places and the decoys taken in turn: the whole family is read, in every frame and after every decoy.
+ const placed = (elements, frames = ELEMENT_FRAMES) => elements.map((element, index) => {
+ const [frameName, frame] = frames[index % frames.length];
+ const [decoyName, decoy] = decoys[Math.floor(index / frames.length) % decoys.length];
+ return { ...elementPage(frame, element, decoy), label: `${decoyName} / ${frameName} / ${JSON.stringify(element)}` };
+ });
+ const base = loadBaseLexer();
+ const family = readTokens(ts, placed([...proseElements()]), base);
+ t.diagnostic(`lines with a comment, a path after them: ${describeReading(family)}`);
+ assert.deepStrictEqual(family.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(family.stats.valid >= 4500, `only ${family.stats.valid} programs were valid, so the sweep proves little`);
+ assert.strictEqual(family.stats.guessed, 0, `a text that no type can hold was guessed at: ${guessSummary(family.kinds)}: ${JSON.stringify(family.guessedPrograms.slice(0, 3).map((program) => program.label))}`);
+ assert.strictEqual(family.stats.exact, family.stats.valid, 'every valid page is read exactly');
+ assert.deepStrictEqual(family.lostPrograms.slice(0, 3).map((program) => program.label), [], 'a page that the base resolves is refused');
+ // The lines that begin with a parenthesis, a bracket, a quote, a tag or an operator, end in a postfix `!`, a call or an index, have a number with a `.` or an exponent sign, or start with a modifier are read token by token
+ // (typeMembersFail): each fails as the members of a type where a member begins or after a name, or at the `/` after the comment, so they are certain too.
+ const shaped = readTokens(ts, placed([...proseElements({ lines: PROSE_SHAPED_LINES, ends: ['</p>'] })]), base);
+ t.diagnostic(`lines that begin or end with a bracket, a quote, a tag, an operator, a postfix or a number: ${describeReading(shaped)}`);
+ assert.deepStrictEqual(shaped.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(shaped.stats.valid >= 2000, `only ${shaped.stats.valid} programs were valid, so the sweep proves little`);
+ assert.strictEqual(shaped.stats.guessed, 0, `a text that no type can hold was guessed at: ${guessSummary(shaped.kinds)}: ${JSON.stringify(shaped.guessedPrograms.slice(0, 3).map((program) => program.label))}`);
+ assert.strictEqual(shaped.stats.exact, shaped.stats.valid, 'every valid page is read exactly');
+ assert.deepStrictEqual(shaped.lostPrograms.slice(0, 3).map((program) => program.label), [], 'a page that the base resolves is refused');
+ // Where the closing tag could be in the comment, as an element and as the members of a type, both compile and the page is a guess — where a member of a type may begin at the head. After an `=`, a `(`, a `[`, a `:` or an `=>` none can,
+ // and the same pages are elements for certain.
+ const hidingElements = PROSE_HIDING_ELEMENTS.flatMap((element) => Array.from({ length: MEMBER_ELEMENT_FRAMES.length * decoys.length }, () => element));
+ const hiding = readTokens(ts, placed(hidingElements, MEMBER_ELEMENT_FRAMES));
+ assert.deepStrictEqual(hiding.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(hiding.stats.valid >= 100, `only ${hiding.stats.valid} programs with a closing tag in a comment were valid`);
+ assert.strictEqual(hiding.stats.guessed, hiding.stats.valid, 'a closing tag that the comment could hold is a guess');
+ const unhidden = readTokens(ts, placed(PROSE_HIDING_ELEMENTS.flatMap((element) => Array.from({ length: NO_MEMBER_ELEMENT_FRAMES.length * decoys.length }, () => element)), NO_MEMBER_ELEMENT_FRAMES));
+ assert.deepStrictEqual(unhidden.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(unhidden.stats.valid >= 100, `only ${unhidden.stats.valid} programs with a closing tag in a comment were valid`);
+ assert.strictEqual(unhidden.stats.guessed, 0, `an element where no member of a type begins was guessed at: ${guessSummary(unhidden.kinds)}`);
+ assert.strictEqual(unhidden.stats.exact, unhidden.stats.valid, 'every valid page is read exactly');
+ // The lines whose `//` stands behind an open `[`, an initializer's `=` after a `?` or a type, or one in a parameter list, and a path on the next line: a regex may begin at the path's `/`, and the closing tag may be inside it, so where a member of a
+ // type may begin at the head both programs compile and the page is a guess. The base read the word that ends the comment for the token before the `/` and resolved them — the pages this lexer cannot read for certain. Where no member begins
+ // the element is the only reading, and is read exactly, as the base reads it.
+ const openElements = [...proseElements({ leads: [';\n ', ','], lines: PROSE_OPEN_LINES, paths: ['/b', '/ x'], ends: ['</p>'] })];
+ const refusedOpen = readTokens(ts, placed(openElements.flatMap((element) => Array.from({ length: MEMBER_ELEMENT_FRAMES.length * decoys.length }, () => element)), MEMBER_ELEMENT_FRAMES), base);
+ t.diagnostic(`lines that end in an open bracket or an initializer, where a member may begin: ${describeReading(refusedOpen)}`);
+ assert.deepStrictEqual(refusedOpen.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(refusedOpen.stats.valid >= 300, `only ${refusedOpen.stats.valid} programs were valid`);
+ assert.strictEqual(refusedOpen.stats.guessed, refusedOpen.stats.valid, 'a regex after the comment could hold the closing tag: a guess');
+ const certainOpen = readTokens(ts, placed(openElements.flatMap((element) => Array.from({ length: NO_MEMBER_ELEMENT_FRAMES.length * decoys.length }, () => element)), NO_MEMBER_ELEMENT_FRAMES), base);
+ t.diagnostic(`the same lines, where no member begins: ${describeReading(certainOpen)}`);
+ assert.deepStrictEqual(certainOpen.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(certainOpen.stats.valid >= 300, `only ${certainOpen.stats.valid} programs were valid`);
+ assert.strictEqual(certainOpen.stats.guessed, 0, `an element where no member of a type begins was guessed at: ${guessSummary(certainOpen.kinds)}`);
+ assert.strictEqual(certainOpen.stats.exact, certainOpen.stats.valid, 'every valid page is read exactly');
+ assert.deepStrictEqual(certainOpen.lostPrograms.slice(0, 3).map((program) => program.label), [], 'a page that the base resolves is refused');
+ // The members of a type with the same text: a closing tag in a comment is a guess and the decoy after the type is data; where there is none, the type is code for certain.
+ const types = [];
+ for (const [decoyName, decoy] of decoys) for (const page of signaturePages(PROSE_HIDING_ENDINGS, decoy)) if (['<T>(x)', 'new <T>(x)', '<T>()'].some((head) => page.label.includes(` / ${head} / `))) types.push({ ...page, label: `${decoyName} / ${page.label}` });
+ const hidden = readTokens(ts, types);
+ t.diagnostic(`members of a type with a closing tag in a comment: ${describeReading(hidden)}`);
+ assert.deepStrictEqual(hidden.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(hidden.stats.valid >= 700, `only ${hidden.stats.valid} types with a closing tag in a comment were valid`);
+ assert.strictEqual(hidden.stats.guessed, hidden.stats.valid, 'a type that holds the closing tag in a comment is refused after a guess');
+ const code = readTokens(ts, signaturePages(PROSE_TYPE_ENDINGS, DECOYS.string).filter((page, index) => index % 3 === 0));
+ assert.deepStrictEqual(code.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(code.stats.valid >= 250, `only ${code.stats.valid} types were valid`);
+ assert.strictEqual(code.stats.exact, code.stats.valid, 'a type with no closing tag in it is code, for certain');
+ // They are TypeScript's signatures, not elements.
+ for (const page of types.filter((program, index) => index % 7 === 0)) {
+ const source = cleanSourceFile(ts, page.code);
+ if (source) assert.ok(!isElement(readingAt(ts, source, page.at)), `TypeScript reads a signature, not an element: ${page.label}`);
+ }
+});
+
+// ─── What the text after a signature can hold: a number for a name, a nested element, the lines of a prose element in an expression ─────────────────────
+//
+// The text after the `)` of `<T>(x)` is read to the closing tag `</T>`: an element ends there, and a type that has the same text for its members may hold the closing tag in a string, a template, a comment or a
+// regex, so that the text of a call after it is data. The sweeps below put pages for each shape (helpers/hidden-closing-pages.js) in front of TypeScript's parser and ask it per token: a token it reads as data is
+// stray, and a lexer that names no guess rewrites exactly the real calls. Where the base (BASE_LIB_PATH) is given, the pages that it misreads show that the sweep sees a misread, and a page that it reads
+// exactly is read exactly here.
+
+// `1e-5` is ONE numeric literal to the scanner (scanNumber), a valid name for a member. A reading that took `1e` for a name and the `-` for a sign said that no type has the text, and that the closing tag in the
+// string after it is no string's: the page was read as an element, and the call in the string was rewritten.
+test('sweep (a member named by a number, TypeScript parser): a decimal literal with a signed exponent is one name, so the closing tag that its type holds is hidden and the token in it is data', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const base = loadBaseLexer();
+ const pages = numberedMemberPages();
+ const reading = readTokens(ts, pages, base);
+ t.diagnostic(describeReading(reading));
+ assert.deepStrictEqual(reading.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(reading.stats.valid >= 6000, `only ${reading.stats.valid} programs were valid, so the sweep proves little`);
+ // A type that holds the closing tag in a string, a template or a comment is refused after a guess — and the one that holds it in an object type, `{ a: '</T>…' }`, which no element has for text, is code for certain. A page
+ // read as an element would have the call in its string rewritten, and `problems` says so.
+ assert.ok(reading.stats.guessed >= 0.8 * reading.stats.valid, `only ${reading.stats.guessed} of ${reading.stats.valid} valid programs were refused after a guess`);
+ assert.strictEqual(reading.stats.guessed + reading.stats.exact, reading.stats.valid, 'a page is read exactly or refused after a guess');
+ // The names that the scanner reads as one token with a sign in it are the ones a reading that stops at the sign gets wrong: they are a large part of the valid pages.
+ const signed = pages.filter((page) => /[eE][+-][0-9]/.test(page.name) && tokenReading(ts, page.code) !== null);
+ assert.ok(signed.length >= 2000, `only ${signed.length} valid pages have a name with a signed exponent`);
+ assert.deepStrictEqual(reading.lostPrograms.slice(0, 3).map((program) => program.label), [], 'a page that the base resolves is refused');
+ // A sign that no digit follows is no part of the number (TS1124), and a hex literal has no exponent: neither is a valid name, so the pages are no type's.
+ const named = (name) => `interface I { <T>(x); ${name}: '</T>;${CALL}' }\n${CALL}\n`;
+ for (const name of ['1e5', '1e+5', '1e-5', '1_0E+1', '.5e-1']) assert.notStrictEqual(tokenReading(ts, named(name)), null, `${name} is a member name`);
+ for (const name of ['1e+x', '1e+', '0x1e+5', '1e-']) assert.strictEqual(tokenReading(ts, named(name)), null, `${name} is no member name`);
+});
+
+// A nested element in an expression of a member — a default value, a computed name, an initializer — is JSX text to a type that reads it as an element, which has no comment or string in it, and code goes on
+// after its closing tag. Read as code, `x // y</b> +` is a comment up to the end of its line, and the `/` on the next line a division; and `<b>'x</b> + '` is a string, which hides the quote that opens the string
+// that holds the closing tag and the text of a call. The text of the nested element opens things that end with it (and the base misreads a part of these pages too: its scan skipped past the nested closing tag).
+test('sweep (the text of a nested element in a default value or a computed name, TypeScript parser): what it opens ends with the element, and the closing tag that a later string, template or regex holds is hidden', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const base = loadBaseLexer();
+ const reading = readTokens(ts, nestedTextPages(20261120, 36000), base);
+ t.diagnostic(describeReading(reading));
+ assert.deepStrictEqual(reading.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(reading.stats.valid >= 5000, `only ${reading.stats.valid} programs were valid, so the sweep proves little`);
+ assert.ok(reading.stats.guessed >= 0.9 * reading.stats.valid, `${reading.stats.guessed} of ${reading.stats.valid} valid programs were refused after a guess`);
+ assert.deepStrictEqual(reading.lostPrograms.slice(0, 3).map((program) => program.label), [], 'a page that the base resolves is refused');
+ // The base calibrates the sweep: it reads a part of these pages wrong, and this lexer reads none of them.
+ if (base) assert.ok(reading.stats.baseMisread >= 200, `the base misreads ${reading.stats.baseMisread} pages, so the sweep may not see a misread`);
+});
+
+// A literal that holds the text of an element — `'<b>c</b>'`, or `<b>` in one string and `</b>` in the next — is a token of the type, and the tags in it are no element's. The element reading takes them for tags that open and
+// close, and a lexer that took the depth they make for the depth of the type's own text ended what a nested element opened at the wrong place: the template after the second literal was read as code, and the closing tag
+// in it as an element's. The tags in the literals open and close in the element reading and in no other.
+test('sweep (a literal that holds the tags of an element, TypeScript parser): the tags in a string, a template, a regex or a comment are no element\'s, and the closing tag a later literal holds is hidden', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const base = loadBaseLexer();
+ const reading = readTokens(ts, literalTagPages(20261122, 36000), base);
+ t.diagnostic(describeReading(reading));
+ assert.deepStrictEqual(reading.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(reading.stats.valid >= 5000, `only ${reading.stats.valid} programs were valid, so the sweep proves little`);
+ assert.deepStrictEqual(reading.lostPrograms.slice(0, 3).map((program) => program.label), [], 'a page that the base resolves is refused');
+ if (base) assert.ok(reading.stats.baseMisread >= 100, `the base misreads ${reading.stats.baseMisread} pages, so the sweep may not see a misread`);
+});
+
+// The text of a nested element, drawn from quotes, back-ticks, comment openers, tags, containers and words, is JSX text to a type that reads the element and code to a reading that does not, and its tags and literals may be
+// one thing in the one and another in the other: wherever either reading hides the closing tag that a later literal holds, it is hidden, and no token in the literal is rewritten.
+test('sweep (the text of a nested element as a soup of quotes, comments and tags, TypeScript parser): either reading of the text may hide the closing tag, and no token is rewritten', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const base = loadBaseLexer();
+ const reading = readTokens(ts, nestedSoupPages(20261123, 60000), base);
+ t.diagnostic(describeReading(reading));
+ assert.deepStrictEqual(reading.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(reading.stats.valid >= 4000, `only ${reading.stats.valid} programs were valid, so the sweep proves little`);
+ assert.deepStrictEqual(reading.lostPrograms.slice(0, 3).map((program) => program.label), [], 'a page that the base resolves is refused');
+ if (base) assert.ok(reading.stats.baseMisread >= 200, `the base misreads ${reading.stats.baseMisread} pages, so the sweep may not see a misread`);
+});
+
+// A nested tag that no element has — the type arguments of a name, a comparison, the type parameters of a signature or a method — is code to a type, and what looks like its closing tag is in a string before it. The element
+// reading closes the nested element there and takes the quote after it for text, where the type ends a string and starts the next, which holds the closing tag of the head and a call: the token in it is data, and the page is
+// refused, with the guess at the head, wherever the closing tag of the head could be inside it.
+test('sweep (a nested tag that no element has, TypeScript parser): the type arguments, comparison or type parameters before a string that holds the nested closing tag leave the closing tag of the head hidden', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const base = loadBaseLexer();
+ const reading = readTokens(ts, nestedCodePages(20261124, 60000), base);
+ t.diagnostic(describeReading(reading));
+ assert.deepStrictEqual(reading.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(reading.stats.valid >= 4000, `only ${reading.stats.valid} programs were valid, so the sweep proves little`);
+ assert.deepStrictEqual(reading.lostPrograms.slice(0, 3).map((program) => program.label), [], 'a page that the base resolves is refused');
+ if (base) assert.ok(reading.stats.baseMisread >= 100, `the base misreads ${reading.stats.baseMisread} pages, so the sweep may not see a misread`);
+});
+
+// After type arguments, a comparison or the type parameters of a signature the text is code, and a string that holds tags — a fragment, a tag with an attribute, a closing tag — holds them as text. The element reading takes
+// them for tags, and a closing tag in the next string would cut it: the quotes that pair as the type reads them pair differently, and the string that holds the closing tag of the head is read as code. Every page that
+// TypeScript parses has the decoy in a literal, so no token in it may be rewritten.
+test('sweep (tags that stand in strings after type arguments, TypeScript parser): the tags are text to the type, and the closing tag of the head that a string holds is hidden', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const base = loadBaseLexer();
+ const reading = readTokens(ts, taggedStringPages(20261125, 60000), base);
+ t.diagnostic(describeReading(reading));
+ assert.deepStrictEqual(reading.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(reading.stats.valid >= 10000, `only ${reading.stats.valid} programs were valid, so the sweep proves little`);
+ assert.deepStrictEqual(reading.lostPrograms.slice(0, 3).map((program) => program.label), [], 'a page that the base resolves is refused');
+});
+
+// The words in a nested tag decide whether a type can read it as code: a modifier (`<public U>(y): T`), an operator (`x <a in b> y`, `x <typeof U> \`t\``), a type operator (`Array<keyof X>`), a dotted or dashed name with one of
+// them, a line break before an `=` (`<a`, `href` and `="/x">` on three lines: a member of a type, and another with an initializer), and an empty pair of angle brackets (`<>(y)`, `f(x)<>`, `a[0]<>`, `a!<>`, `'s'<>`, `{}<>`, and
+// `f // note:` and a line break, then `<> || …`). The pages draw the tag from every keyword TypeScript has, joined to a name, a dot, a dash or a value, and from the words that no keyword
+// is — not only the tags that the lexer's rule already calls code — in every place a tag stands: as the type parameters or arguments of a signature, a name or a call, as a comparison, and as an element. The closing tag of the nested
+// element is in a string before the one that holds the closing tag of the head, where it is a type's.
+test('sweep (the words of a nested tag and a fragment after an operand, TypeScript parser): a tag that a type can read as code leaves the closing tag of the head hidden, whatever its words, and no token is rewritten', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const base = loadBaseLexer();
+ const keywords = [];
+ for (let kind = ts.SyntaxKind.FirstKeyword; kind <= ts.SyntaxKind.LastKeyword; kind += 1) keywords.push(ts.tokenToString(kind));
+ const pages = nestedTagPages(20261201, 40000, keywords);
+ const reading = readTokens(ts, pages, base);
+ t.diagnostic(describeReading(reading));
+ assert.deepStrictEqual(reading.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(reading.stats.valid >= 5000, `only ${reading.stats.valid} programs were valid, so the sweep proves little`);
+ assert.deepStrictEqual(reading.lostPrograms.slice(0, 3).map((program) => program.label), [], 'a page that the base resolves is refused');
+ // The sweep meets each family: tags with a keyword among their words and fragments after an operand, valid to the parser.
+ const valid = pages.filter((page) => tokenReading(ts, page.code) !== null);
+ assert.ok(valid.filter((page) => page.what.startsWith('fragment')).length >= 800, 'fragments after an operand');
+ assert.ok(valid.filter((page) => page.what.startsWith('tag')).length >= 3000, 'tags');
+ assert.ok(valid.filter((page) => page.what.startsWith('tag') && /\\[nru]/.test(page.what)).length >= 1000, 'tags with a line break in them');
+ assert.ok(valid.filter((page) => page.what.startsWith('tag') && /\\n(?:[^"\\]|\\[^n])*\\n="|\\r\\n[^"]*\\r\\n=|\\r[^"]*\\r=/.test(page.what)).length >= 150, 'tags with a line break before an `=`');
+ assert.ok(valid.filter((page) => page.what.startsWith('fragment') && /\/\/ ?(note|c)/.test(page.what)).length >= 500, 'fragments after a line comment');
+ assert.ok(valid.filter((page) => keywords.some((word) => page.what.includes(`"${word} `) || page.what.includes(` ${word}"`) || page.what.includes(` ${word} `))).length >= 1000, 'tags with a keyword among their words');
+ if (base) assert.ok(reading.stats.baseMisread >= 100, `the base misreads ${reading.stats.baseMisread} pages, so the sweep may not see a misread`);
+});
+
+// Two or three nested elements, each with a comment opener, a quote or a back-tick in its text, in a default value, a computed name or an initializer. The region that each text opens may end where another's ends — two `//` comments on
+// one line, a template and a comment, a string and a comment — and a region that is open at the closing tag of an element is a place to choose between the two readings of it, told by where it starts: two with one end are two places,
+// and the head's closing tag is hidden where either reading says so.
+test('sweep (two nested elements whose text opens a region each, TypeScript parser): regions that end at one place are two places, and no token in the string, template or regex after them is rewritten', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const base = loadBaseLexer();
+ const reading = readTokens(ts, nestedPairPages(20261202, 40000), base);
+ t.diagnostic(describeReading(reading));
+ assert.deepStrictEqual(reading.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(reading.stats.valid >= 5000, `only ${reading.stats.valid} programs were valid, so the sweep proves little`);
+ assert.deepStrictEqual(reading.lostPrograms.slice(0, 3).map((program) => program.label), [], 'a page that the base resolves is refused');
+ if (base) assert.ok(reading.stats.baseMisread >= 500, `the base misreads ${reading.stats.baseMisread} pages, so the sweep may not see a misread`);
+});
+
+// An import type has no line-break rule before its `(` (parseImportType): `typeof import` and a line break, then `('./m')`, is one type, where after any other type a `(` at the start of a line begins a call signature, whose first
+// parameter a string is not. A lexer that took the `(` for a signature's parameter list said that no type has the text, and read the closing tag in the path, or in the string, template, comment or regex after the type, as an element's:
+// the token in it was rewritten. The pages draw the two words, the `(` and the path from every kind of line terminator, space and comment, in each place a type stands.
+test('sweep (an import type whose `(` stands on a later line, TypeScript parser): the `(` is the import type\'s, and the closing tag that a literal holds after it is hidden', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const base = loadBaseLexer();
+ const reading = readTokens(ts, importTypePages(20261305, 40000), base);
+ t.diagnostic(describeReading(reading));
+ assert.deepStrictEqual(reading.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(reading.stats.valid >= 14000, `only ${reading.stats.valid} programs were valid, so the sweep proves little`);
+ assert.deepStrictEqual(reading.lostPrograms.slice(0, 3).map((program) => program.label), [], 'a page that the base resolves is refused');
+});
+
+// `get [a, /x/]()` is an accessor whose computed name is a comma expression with a regex in it: parseTypeMember tries `get` and `set` before an index signature, and what they take is any `[`, on any line (canFollowGetOrSetKeyword).
+// After any other word, a `[`, a name and a `,` or a `:` are an index signature, and no `/` follows. A lexer that took the accessor for an index signature said that no type has the text, and read the closing tag in the regex as
+// an element's. The pages draw the modifier, the word, the name and what follows it, with trivia of every kind between the tokens.
+test('sweep (an accessor whose computed name holds a comma and a regex, TypeScript parser): the `[` after `get` or `set` is no index signature, and the regex that holds the closing tag hides it', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const base = loadBaseLexer();
+ const reading = readTokens(ts, accessorNamePages(20261306, 60000), base);
+ t.diagnostic(describeReading(reading));
+ assert.deepStrictEqual(reading.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(reading.stats.valid >= 3500, `only ${reading.stats.valid} programs were valid, so the sweep proves little`);
+ assert.deepStrictEqual(reading.lostPrograms.slice(0, 3).map((program) => program.label), [], 'a page that the base resolves is refused');
+});
+
+// A keyword that is the name of an attribute with a value (`<a break="v">`, `<A.B x in="1">`) is an attribute's, whatever word comes before it: no parameter list of a type has one name after another without a comma, and no
+// comparison has `a break="v"`. So no type has the tag, and its text is JSX text, in every place an element stands. The precision of the reading: none of these pages is a guess, and each is read exactly.
+test('sweep (a keyword as the name of an attribute with a value, TypeScript parser): the tag is an element to every reading, so JSX text in it opens nothing and no page is refused', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const keywords = [];
+ for (let kind = ts.SyntaxKind.FirstKeyword; kind <= ts.SyntaxKind.LastKeyword; kind += 1) keywords.push(ts.tokenToString(kind));
+ const programs = [];
+ for (const decoyName of ['string', 'template', 'line comment']) for (const page of elementPages(valuedKeywordElements(keywords), DECOYS[decoyName])) programs.push({ ...page, label: `${decoyName} / ${page.label}` });
+ const reading = readTokens(ts, programs);
+ t.diagnostic(describeReading(reading));
+ assert.deepStrictEqual(reading.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(reading.stats.valid >= 8000, `only ${reading.stats.valid} programs were valid, so the sweep proves little`);
+ assert.strictEqual(reading.stats.guessed, 0, `a page whose tag has a valued attribute was refused after a guess: ${guessSummary(reading.kinds)}`);
+ assert.strictEqual(reading.stats.exact, reading.stats.valid, 'every valid page is read exactly');
+});
+
+// The lines of a prose element after `(a);` — a bracket, a quote, a tag, an operator, a number, a modifier, a postfix — are certain where no type can have them (PROSE_SHAPED_LINES). In an expression of a type the same
+// lines are a type's, and a regex after the comment may hold the closing tag: the base took the last word of the comment for the token before the `/` and read it as a division, which rewrites the token in the regex.
+// This lexer refuses or reads each page exactly: a `/` after a `)` or a `]` divides, and after anything else it may begin a regex.
+test('sweep (the lines of a prose element in an expression of a type, TypeScript parser): a regex after the comment may hold the closing tag, and no token in it is rewritten', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const base = loadBaseLexer();
+ // The lines up to their comment: the generator adds the comment and the line break, and a path of a regex after them.
+ const prefixes = [...new Set(PROSE_SHAPED_LINES.map((line) => line.replace(/ ?(?:\/\/ c|https:\/\/.*)$/, '')))];
+ const keywords = [];
+ for (let kind = ts.SyntaxKind.FirstKeyword; kind <= ts.SyntaxKind.LastKeyword; kind += 1) keywords.push(ts.tokenToString(kind));
+ const lines = [...prefixes, ...keywords, 'a', 'x1', '\u00e9', '1', 'Docs', 'see', ':', '::', '=>', '>', '<', '</', '\\', '`', '${', '}', ')', ']', ',', ';'];
+ const reading = readTokens(ts, expressionLinePages(lines, 20261121, 90000), base);
+ t.diagnostic(describeReading(reading));
+ assert.deepStrictEqual(reading.problems.slice(0, 5), [], 'every token is read where TypeScript reads it');
+ assert.ok(reading.stats.valid >= 1500, `only ${reading.stats.valid} programs were valid, so the sweep proves little`);
+ assert.deepStrictEqual(reading.lostPrograms.slice(0, 3).map((program) => program.label), [], 'a page that the base resolves is refused');
+ if (base) assert.ok(reading.stats.baseMisread >= 1000, `the base misreads ${reading.stats.baseMisread} pages, so the sweep may not see a misread`);
+});
+
// ─── The delimiters of a tag ────────────────────────────────────────────────────────────────────────────────────────────────────────────────
//
// TypeScript scans the `/` and the `>` of a self-closing tag as two tokens, with trivia of every kind between them: white space, line breaks, comments (parseJsxOpeningOrSelfClosingElementOrOpeningFragment). A lexer that knew only an adjacent
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.js
index b6ee1a7f5..a166aa4d4 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
@@ -1,7 +1,7 @@
'use strict';
// REAL BUNDLE: the app routing description (`app.aiDescription` -> `appmodule.aiappdescription`, #583).
//
-// The plugin's `applyAppAiDescription` and `haltOnUnpublishedAppHeader` lean on five SDK behaviours that
+// The plugin's `applyAppAiDescription` and `haltOnUnpublishedAppHeader` lean on six SDK behaviours that
// its own unit tests can only stub:
// 1. a fetched app carries `aiDescription` ONLY when the row has a value;
// 2. `updateElement('/aiDescription')` on such an app rejects with PATH_NOT_FOUND, while an
@@ -16,7 +16,11 @@
// 5. after a refused push, a plain fetch refuses to discard the unpushed copy once the server has
// moved (LOCAL_EDITS_WOULD_BE_LOST), and `{ overwrite: true }` resets it — which is why the
// never-published halt resets the copy before telling the operator to publish and re-run, and why a
-// concurrent edit's kept copy stops a blind re-run.
+// concurrent edit's kept copy stops a blind re-run;
+// 6. a header write is never unconditional: the ROW token a fetch read is sent even when the SDK's own
+// read of the header fails, and with no token held at all the edit throws APP_UPDATE_NO_ETAG before
+// anything is written. The plugin edits a header only on a copy it has just fetched, so it never
+// meets that refusal; if it did, `pushAppHeader` resets the copy and the next run saves.
// 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 same way sitemap-icon-real-bundle.test.js pins
// the sitemap write.
@@ -65,9 +69,11 @@ async function freshSdk({ ai, componentstate = 0, headerStatus = 204, sitemapSta
tempDirs.push(dir);
const writes = [];
const reads = [];
- const state = { ai, componentstate, headerStatus, sitemapStatus, etag: 'W/"1"', tokens, description: 'Tickets' };
+ // `noAppEtag`: the appmodule answers no version at all (no ETag header, no `@odata.etag`), so a fetch holds no
+ // token for its header. `headerReadFails`: the SDK's own unpublished-aware header read, made at push, answers 500.
+ const state = { ai, componentstate, headerStatus, sitemapStatus, etag: 'W/"1"', tokens, description: 'Tickets', noAppEtag: false, headerReadFails: false };
const appEtag = (url) => (!state.tokens ? state.etag : /RetrieveUnpublished/i.test(url) ? state.tokens.content : state.tokens.row);
- const appRow = (etag = state.etag) => ({ appmoduleid: APP_ID, appmoduleidunique: APP_IDUNIQUE, name: 'Probe', uniquename: APP_UNIQUE, description: state.description, componentstate: state.componentstate, ...(state.ai !== undefined ? { aiappdescription: state.ai } : {}), '@odata.etag': etag });
+ const appRow = (etag = state.etag) => ({ appmoduleid: APP_ID, appmoduleidunique: APP_IDUNIQUE, name: 'Probe', uniquename: APP_UNIQUE, description: state.description, componentstate: state.componentstate, ...(state.ai !== undefined ? { aiappdescription: state.ai } : {}), ...(state.noAppEtag ? {} : { '@odata.etag': etag }) });
const sitemapRow = () => ({ sitemapid: SITEMAP_ID, sitemapnameunique: APP_UNIQUE, sitemapxml: SITEMAP_XML, '@odata.etag': state.etag });
const httpClient = {
get: async (url) => {
@@ -86,6 +92,7 @@ async function freshSdk({ ai, componentstate = 0, headerStatus = 204, sitemapSta
return { status: 200, headers: { etag: state.etag }, body: multi ? { value: [sitemapRow()] } : sitemapRow() };
}
if (/\/appmodules/.test(url)) {
+ if (state.headerReadFails && /RetrieveUnpublished/i.test(url)) return { status: 500, headers: {}, body: { error: { message: 'transient failure' } } };
// The halt's own draft read. While a draft exists, put the PUBLISHED row first, so the test proves
// the unpublished layer is found wherever it sits: the live platform returned only the draft row,
// but does not document that. The SDK's own reads never select componentstate, so they are unaffected.
@@ -94,7 +101,7 @@ async function freshSdk({ ai, componentstate = 0, headerStatus = 204, sitemapSta
}
const multi = /RetrieveUnpublishedMultiple/i.test(url) || /\/appmodules\?/.test(url);
const etag = appEtag(url);
- return { status: 200, headers: { etag }, body: multi ? { value: [appRow(etag)] } : appRow(etag) };
+ return { status: 200, headers: state.noAppEtag ? {} : { etag }, body: multi ? { value: [appRow(etag)] } : appRow(etag) };
}
if (/\/roles/.test(url)) return { status: 200, headers: {}, body: { value: [{ roleid: '66666666-6666-6666-6666-666666666666' }] } };
return { status: 200, headers: {}, body: { value: [] } };
@@ -107,7 +114,10 @@ async function freshSdk({ ai, componentstate = 0, headerStatus = 204, sitemapSta
const ifMatch = (options && options.headers && options.headers['If-Match']) || null;
writes.push({ verb: 'patch', url: String(url), body, ifMatch });
if (/\/appmodules\(/.test(url) && state.tokens) {
- if (ifMatch !== state.tokens.row) {
+ // A PATCH with no `If-Match` is accepted whatever the version — that is what a plain write is, and what a header
+ // write that forgot its token would be — so only a token that is not the row's is refused.
+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/perform-conditional-operations-using-web-api
+ if (ifMatch !== null && ifMatch !== state.tokens.row) {
return { status: 412, headers: {}, body: { error: { code: '0x80060882', message: 'The version of the existing record doesn\'t match the RowVersion property provided.' } } };
}
if (body && body.aiappdescription !== undefined) state.ai = body.aiappdescription;
@@ -321,4 +331,76 @@ test('REAL BUNDLE: a never-published app THROWS its header refusal, and pushAppH
assert.strictEqual(await applyAppAiDescription(sdk, spec(WANT), APP_ID), true);
assert.strictEqual((await pushAppHeader(sdk, APP_ID, 'Probe', true)).saved, true);
assert.strictEqual(state.ai, WANT);
+});
+
+// cds-maker-sdk 0ffa4384 (an app's header write is never unconditional): before it, the SDK sent the appmodule header
+// PLAIN whenever no token was "usable" — none held, or its own header read had failed — so a transient read failure
+// let a push overwrite another writer's header, and a copy that held no header token wrote it blind. The plugin's
+// existing-app path always fetches the app first (a plain fetch of a clean copy re-reads both row tokens), and the one
+// header edit it makes (the routing description) rides that copy, so no ordinary run meets the refusal. These pin what
+// that rests on, and what the plugin does if the refusal is ever reached.
+test('REAL BUNDLE: a header write is always conditional: a failed header read still sends the held ROW token', async () => {
+ const { sdk, state, writes } = await freshSdk({ ai: 'Route Q1', tokens: { row: 'W/"5"', content: 'W/"5"' } });
+ await sdk.fetchArtifact('app', APP_ID);
+ assert.strictEqual(await applyAppAiDescription(sdk, spec(WANT), APP_ID), true);
+ state.headerReadFails = true; // the SDK's own read of the header, made at push, blips
+ const res = await pushAppHeader(sdk, APP_ID, 'Probe', true);
+ assert.strictEqual(res.saved, true, JSON.stringify(res.error && res.error.message));
+ assert.deepStrictEqual(headerWrites(writes).filter((w) => w.verb === 'patch').map((w) => w.ifMatch), ['W/"5"'], 'conditional on the held row token, never a plain PATCH');
+ assert.strictEqual(state.ai, WANT);
+});
+
+test('REAL BUNDLE: the same failed read over another writer\u2019s header change is a refused concurrent edit, never an overwrite', async () => {
+ const { sdk, state, writes } = await freshSdk({ ai: 'Route Q1', tokens: { row: 'W/"5"', content: 'W/"5"' } });
+ await sdk.fetchArtifact('app', APP_ID);
+ assert.strictEqual(await applyAppAiDescription(sdk, spec(WANT), APP_ID), true);
+ // Another writer saves the header after this run's fetch (the row moves), and the SDK's header read then fails.
+ Object.assign(state, { description: 'Another writer', ai: 'Their routing text', tokens: { row: 'W/"7"', content: 'W/"8"' }, componentstate: 1, headerReadFails: true });
+ const res = await pushAppHeader(sdk, APP_ID, 'Probe', true);
+ assert.strictEqual(res.saved, false);
+ assert.strictEqual(res.error && res.error.code, 'VERSION_CONFLICT');
+ assert.throws(() => requireSuccessfulPush(res, 'app Probe'), (e) => e.code === 'version-conflict');
+ assert.strictEqual(state.ai, 'Their routing text', 'their header is intact');
+ assert.strictEqual(state.description, 'Another writer');
+ assert.ok(headerWrites(writes).filter((w) => w.verb === 'patch').every((w) => w.ifMatch === 'W/"5"'), 'the one attempt was conditional');
+});
+
+test('REAL BUNDLE: with no header token held, a header edit is refused before anything is written, and the next run — whose fetch reads one — saves it', async () => {
+ const { sdk, state, writes } = await freshSdk({ ai: 'Route Q1' });
+ state.noAppEtag = true; // the appmodule answers no version, so this fetch holds no token for its header
+ await sdk.fetchArtifact('app', APP_ID);
+ assert.strictEqual(await applyAppAiDescription(sdk, spec(WANT), APP_ID), true);
+ const writesBefore = writes.length;
+ await assert.rejects(pushAppHeader(sdk, APP_ID, 'Probe', true), (e) => {
+ assert.strictEqual(e.code, 'APP_UPDATE_NO_ETAG');
+ assert.match(e.message, /no concurrency token is held for its appmodule header/);
+ assert.match(e.message, /Nothing was modified/);
+ return true;
+ });
+ assert.deepStrictEqual(writes.slice(writesBefore), [], 'no PATCH at all — neither the header nor the sitemap');
+ // pushAppHeader reset the copy the refused push left holding the edit (discardUnrecordedEdits), so the next run is
+ // not stopped by it: its plain fetch would otherwise refuse to discard the edit once the server had moved.
+ assert.strictEqual((await sdk.listArtifacts('app')).find((a) => a.id === APP_ID).isDirty, false, 'the copy is the server\u2019s again');
+ // The next run: the platform answers versions, the plain fetch reads the header's, and the same edit saves — conditionally.
+ state.noAppEtag = false;
+ await sdk.fetchArtifact('app', APP_ID);
+ assert.strictEqual(await applyAppAiDescription(sdk, spec(WANT), APP_ID), true);
+ const res = await pushAppHeader(sdk, APP_ID, 'Probe', true);
+ assert.strictEqual(res.saved, true, JSON.stringify(res.error && res.error.message));
+ assert.deepStrictEqual(headerWrites(writes).filter((w) => w.verb === 'patch').map((w) => w.ifMatch), [state.etag]);
+ assert.strictEqual(state.ai, WANT);
+});
+
+test('REAL BUNDLE: an unchanged header needs no token: a sitemap-only push goes through with none held', async () => {
+ // The refusal is for a header EDIT. An app whose header the push does not change writes only its sitemap, so the
+ // plugin's ordinary rebuild of an existing app — which rewrites the sitemap and leaves the header alone — is untouched.
+ const { sdk, state, writes } = await freshSdk({ ai: 'Written by the platform.' });
+ state.noAppEtag = true;
+ await sdk.fetchArtifact('app', APP_ID);
+ assert.strictEqual(await applyAppAiDescription(sdk, spec(undefined), APP_ID), false, 'the spec leaves the routing description alone');
+ await sdk.updateElement('app', APP_ID, '/siteMap', appDef(spec(undefined), { forms: {}, views: {}, charts: {} }).siteMap);
+ const res = await sdk.pushArtifact('app', APP_ID);
+ assert.strictEqual(res.saved, true, JSON.stringify(res.error && res.error.message));
+ assert.ok(writes.some((w) => /\/sitemaps\(/.test(w.url)), 'the sitemap was written');
+ assert.strictEqual(headerWrites(writes).length, 0, 'the header was not');
});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/app-spec.test.js b/plugins/model-apps/scripts/tests/app-spec.test.js
index 79e5ad82d..df32c0e9b 100644
--- a/plugins/model-apps/scripts/tests/app-spec.test.js
+++ b/plugins/model-apps/scripts/tests/app-spec.test.js
@@ -1130,6 +1130,49 @@ test('validateAppSpec rejects a non-boolean entities[].quickCreate', () => {
assert.ok(r.errors.some((e) => /quickCreate must be a boolean/.test(e)), 'the error names the field');
});
+// --- entities[].primaryAttribute.maxLength (the length of the table's name column) ----------------
+// Accepted and ignored until the build began sending it, so a value the platform cannot take is refused at the spec gate, not
+// part-way through a build. The platform's limit for a table's name column is 850, well under the 4,000 of other text columns:
+// asked for more, the table create is refused — "The maximum length of Primary attribute '<name>' is <asked>. The maximum
+// allowed limit is 850."
+test('validateAppSpec accepts primaryAttribute.maxLength from 1 to 850, and an omitted one', () => {
+ for (const maxLength of [undefined, 1, 100, 120, 849, 850]) {
+ const primaryAttribute = { schemaName: 'new_name', displayName: 'Name', ...(maxLength === undefined ? {} : { maxLength }) };
+ const r = validateAppSpec(quickCreateSpec({ primaryAttribute }), { profile: 'deploy' });
+ assert.ok(r.ok, `${maxLength}: ${JSON.stringify(r.errors)}`);
+ }
+});
+
+test('validateAppSpec rejects a primaryAttribute.maxLength that is not a whole number from 1 to 850, naming the field and the value', () => {
+ for (const bad of [0, -1, 851, 4000, 4001, 12.5, '120', null, true, [], {}]) {
+ const r = validateAppSpec(quickCreateSpec({ primaryAttribute: { schemaName: 'new_name', displayName: 'Name', maxLength: bad } }), { profile: 'deploy' });
+ assert.ok(!r.ok, `${JSON.stringify(bad)} must be rejected`);
+ assert.ok(r.errors.some((e) => e.startsWith('entity new_ticket: primaryAttribute.maxLength must be a whole number from 1 to 850 (got ')), `${JSON.stringify(bad)}: ${JSON.stringify(r.errors)}`);
+ }
+ assert.ok(validateAppSpec(quickCreateSpec({ primaryAttribute: { schemaName: 'new_name', maxLength: 851 } }), { profile: 'deploy' }).errors.some((e) => /\(got 851\)/.test(e)), 'the value is quoted back');
+});
+
+// /genpage and /app-builder reach the build through the provision-entities input gate, not validateAppSpec: it must refuse
+// exactly what the spec gate refuses, because the length goes into the table request as it is written.
+test('the provision-entities input gate applies the same primaryAttribute.maxLength rule as validateAppSpec', () => {
+ const { validateProvisionInput } = require(path.join(__dirname, '..', 'lib', 'provision-input.js'));
+ const lengthErrors = (errors) => errors.filter((e) => /primaryAttribute\.maxLength/.test(e)).map((e) => e.slice(e.indexOf('primaryAttribute.maxLength')));
+ for (const maxLength of [undefined, 1, 120, 850, 851, 4000, 5000, 0, 1.5, -3, '120', null, true, [], {}]) {
+ const primaryAttribute = { schemaName: 'new_name', displayName: 'Name', ...(maxLength === undefined ? {} : { maxLength }) };
+ const spec = validateAppSpec(quickCreateSpec({ primaryAttribute }), { profile: 'deploy' });
+ const input = validateProvisionInput({
+ solution: { uniqueName: 'S', publisherPrefix: 'new' },
+ entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute, columns: [] }],
+ relationships: [],
+ });
+ const label = JSON.stringify(maxLength);
+ assert.deepStrictEqual(lengthErrors(input.errors), lengthErrors(spec.errors), `${label}: the same verdict and wording from both gates`);
+ assert.strictEqual(input.ok, spec.ok, label);
+ const valid = maxLength === undefined || (Number.isInteger(maxLength) && maxLength >= 1 && maxLength <= 850);
+ assert.strictEqual(lengthErrors(input.errors).length === 0, valid, `${label} is ${valid ? 'accepted' : 'rejected'}`);
+ }
+});
+
test('quickCreateEnabledFor: true for an explicit flag, a derived QuickCreate form, else false', () => {
const entity = { schemaName: 'new_ticket', primaryAttribute: { schemaName: 'new_name' }, columns: [] };
// explicit flag — the flag lives on the ENTITY object passed (quickCreateEnabledFor reads entity.quickCreate)
diff --git a/plugins/model-apps/scripts/tests/applied-baseline.test.js b/plugins/model-apps/scripts/tests/applied-baseline.test.js
index 99f2f10c0..37354b868 100644
--- a/plugins/model-apps/scripts/tests/applied-baseline.test.js
+++ b/plugins/model-apps/scripts/tests/applied-baseline.test.js
@@ -69,3 +69,32 @@ test('a baseline that cannot be written never fails the build', () => {
assert.strictEqual(persistAppliedBaseline({ ok: true }, ctx({ apply: true }), write), false);
assert.strictEqual(calls.length, 1);
});
+
+// A changed-only run that finds nothing to apply sends no page, so it has no source to record: it must not record the files as they are when it ends — a page saved while it ran would be
+// recorded as applied. With the real writer, every page keeps the record the last apply left.
+test('a changed-only run that applied nothing keeps the page records it had, and does not record the files as they are', () => {
+ const fs = require('node:fs');
+ const os = require('node:os');
+ const path = require('node:path');
+ const { writeBaseline, readBaseline } = require('../lib/deployed-baseline.js');
+ const { sha256 } = require('../lib/hash.js');
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'noop-baseline-'));
+ try {
+ const identity = { environment: 'https://contoso.crm.dynamics.com', appUniqueName: 'new_a' };
+ const pageSpec = { ...spec, solution: { uniqueName: 'S', publisherPrefix: 'new' }, pages: [{ key: 'home', name: 'Home', source: { kind: 'tsx', codeFile: 'home.tsx' } }] };
+ const ws = path.join(dir, '.maker-workspace');
+ fs.writeFileSync(path.join(dir, 'home.tsx'), 'as last applied');
+ writeBaseline(ws, pageSpec, { appDir: dir, ...identity });
+ const previous = readBaseline(ws, identity);
+ // The maker saves the page while the no-op run is in progress; the run then ends and writes its baseline.
+ fs.writeFileSync(path.join(dir, 'home.tsx'), 'saved while the run was in progress');
+ const noop = { ok: true, dryRun: false, noop: true, created: null, changedOnly: { decision: 'noop' } };
+ assert.strictEqual(persistAppliedBaseline(noop, { spec: pageSpec, opts: { apply: true, baselineSpec: previous }, workspaceDir: ws, appDirAbs: dir, baselineIdentity: identity }), true);
+ assert.strictEqual(readBaseline(ws, identity).pages[0].__contentSha, sha256('as last applied'), 'the record is the one the last apply left');
+ // Control: a result that is not a noop and carries no measurement is hashed from the files, as before.
+ assert.strictEqual(persistAppliedBaseline({ ok: true }, { spec: pageSpec, opts: { apply: true, baselineSpec: previous }, workspaceDir: ws, appDirAbs: dir, baselineIdentity: identity }), true);
+ assert.strictEqual(readBaseline(ws, identity).pages[0].__contentSha, sha256('saved while the run was in progress'));
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/artifact-intent.test.js b/plugins/model-apps/scripts/tests/artifact-intent.test.js
index f4eb550b7..73f7578d8 100644
--- a/plugins/model-apps/scripts/tests/artifact-intent.test.js
+++ b/plugins/model-apps/scripts/tests/artifact-intent.test.js
@@ -15,6 +15,8 @@ const {
firstSectionRowsPointer,
sectionRowsPointer,
findFieldCellPointer,
+ findSectionLocation,
+ findSectionById,
} = require(path.join(__dirname, '..', 'lib', 'artifact-intent.js'));
// ---------------------------------------------------------------------------
@@ -103,10 +105,15 @@ test('fieldCellIntent: includes label only when passed as an explicit override',
// notesCellIntent / notesSectionIntent
// ---------------------------------------------------------------------------
-test('notesCellIntent: returns exact shape with passed-in classId', () => {
+test('notesCellIntent: returns the platform timeline cell with the passed-in classId', () => {
const cell = notesCellIntent('notes-class-guid');
assert.deepStrictEqual(cell, {
+ // A tall cell the empty rows under it are the height of, with the attributes the platform's cell carries.
+ rowspan: 23,
+ bag: { a: [['showlabel', 'false'], ['colspan', '1'], ['rowspan', '23'], ['auto', 'false']], c: [] },
control: {
+ // The one control id Dynamics renders a timeline under — a generated id is published and never shown.
+ id: 'notescontrol',
classId: 'notes-class-guid',
fieldName: null,
label: 'Notes',
@@ -121,16 +128,19 @@ test('notesCellIntent: coerces classId to string (undefined becomes "undefined")
assert.strictEqual(typeof cell.control.classId, 'string');
});
-test('notesSectionIntent: wraps notesCellIntent in the correct section structure', () => {
+test('notesSectionIntent: the section holds the timeline row, then the 22 empty rows its cell spans', () => {
const sec = notesSectionIntent('notes-class-guid');
assert.strictEqual(sec.name, 'section_notes');
assert.strictEqual(sec.label, 'Notes');
assert.strictEqual(sec.visible, true);
assert.strictEqual(sec.showLabel, true);
assert.strictEqual(sec.columns, 1);
- assert.strictEqual(sec.rows.length, 1);
+ assert.strictEqual(sec.rows.length, 23);
assert.strictEqual(sec.rows[0].cells.length, 1);
assert.strictEqual(sec.rows[0].cells[0].control.classId, 'notes-class-guid');
+ assert.strictEqual(sec.rows[0].cells[0].control.id, 'notescontrol');
+ assert.strictEqual(sec.rows[0].cells[0].rowspan, 23);
+ assert.ok(sec.rows.slice(1).every(function (r) { return Array.isArray(r.cells) && r.cells.length === 0; }), 'the other 22 rows are empty');
});
// ---------------------------------------------------------------------------
@@ -488,6 +498,36 @@ test('compileFormIntent: notes section NOT added when neither form.notes nor ent
'no notes section without opt-in');
});
+test('compileFormIntent: the Notes section is the platform timeline host, on an auto and an explicit layout alike', () => {
+ const spec = makeSpec();
+ const layouts = [
+ { entity: 'new_item', notes: true },
+ { entity: 'new_item', notes: true, tabs: [{ name: 'tab_a', label: 'A', sections: [{ name: 'sec_a', columns: 1, fields: ['new_name'] }] }] },
+ ];
+ for (const formSpec of layouts) {
+ const def = compileFormIntent(spec, formSpec, { notesClassId: 'ng' });
+ assert.strictEqual(def.__notes, true, 'the def records that the form asked for the timeline');
+ const sections = def.tabs[0].columns[0].sections;
+ const host = sections[sections.length - 1];
+ assert.strictEqual(host.name, 'section_notes', 'appended last, as before');
+ assert.strictEqual(host.rows.length, 23, 'the timeline row and the 22 rows its cell spans');
+ const timeline = host.rows[0].cells[0];
+ assert.strictEqual(timeline.control.id, 'notescontrol');
+ assert.strictEqual(timeline.rowspan, 23);
+ assert.deepStrictEqual(timeline.bag.a.find(function (p) { return p[0] === 'auto'; }), ['auto', 'false']);
+ assert.ok(host.rows.slice(1).every(function (r) { return r.cells.length === 0; }));
+ // Nothing about it reads as a field: not bound, so it is never placed, pruned or moved as one.
+ assert.deepStrictEqual(formFieldLogicals(def), formFieldLogicals(compileFormIntent(spec, Object.assign({}, formSpec, { notes: false }))));
+ }
+});
+
+test('compileFormIntent: __notes is false for a form that did not ask, and for a form that cannot host the timeline', () => {
+ const spec = makeSpec();
+ assert.strictEqual(compileFormIntent(spec, { entity: 'new_item' }).__notes, false);
+ assert.strictEqual(compileFormIntent(spec, { entity: 'new_item', formType: 'QuickCreate', notes: true }).__notes, false);
+ assert.strictEqual(compileFormIntent(spec, { entity: 'new_item', formType: 'QuickView', notes: true }).__notes, false);
+});
+
// ---------------------------------------------------------------------------
// formFieldLogicals
// ---------------------------------------------------------------------------
@@ -654,6 +694,51 @@ test('findFieldCellPointer: skips null-fieldName controls (notes/subgrid)', () =
assert.strictEqual(findFieldCellPointer(formJson, ''), null);
});
+// A section is found by name, and by the id the SDK mints for it. The id is what a caller holding a section across
+// the addition or removal of the sections around it finds it again by — a section's index moves, and a name can be
+// shared by a real section and the emptied copy an older build left, or be missing.
+const sectionTree = (...tabs) => ({ tabs: tabs.map((columns) => ({ columns: columns.map((sections) => ({ sections })) })) });
+
+test('findSectionLocation: finds a section by name across the whole form, case-insensitively, with where it is', () => {
+ const form = sectionTree([[{ id: 'a', name: 'sec_one' }, { id: 'b', name: 'Sec_Two' }]], [[{ id: 'c', name: 'sec_three' }], [{ id: 'd', name: 'sec_four' }]]);
+ const hit = findSectionLocation(form, 'SEC_TWO');
+ assert.deepStrictEqual([hit.pointer, hit.rowsPointer, hit.tabIndex, hit.columnIndex, hit.sectionIndex, hit.section.id], ['/tabs/0/columns/0/sections/1', '/tabs/0/columns/0/sections/1/rows', 0, 0, 1, 'b']);
+ assert.strictEqual(findSectionLocation(form, 'sec_four').pointer, '/tabs/1/columns/1/sections/0');
+ assert.strictEqual(findSectionLocation(form, 'sec_nope'), null);
+ assert.strictEqual(findSectionLocation(form, ''), null);
+ assert.strictEqual(findSectionLocation({}, 'sec_one'), null);
+});
+
+test('findSectionLocation: `accept` hides a same-named section from the lookup, and the first the caller accepts is the one found', () => {
+ const form = sectionTree([[{ id: 'host', name: 'section_notes', host: true }, { id: 'mine', name: 'section_notes' }]]);
+ assert.strictEqual(findSectionLocation(form, 'section_notes').section.id, 'host', 'document order');
+ assert.strictEqual(findSectionLocation(form, 'section_notes', (s) => !s.host).section.id, 'mine');
+ assert.strictEqual(findSectionLocation(form, 'section_notes', () => false), null);
+});
+
+test('findSectionById: finds a section by its id wherever it is, and still finds it after sections were added or taken out ahead of it', () => {
+ const sections = [{ id: '0F0F0F0F-0000-4000-8000-000000000001', name: 'sec_one' }, { id: '0f0f0f0f-0000-4000-8000-000000000002', name: 'sec_two' }];
+ const form = sectionTree([[sections[0], sections[1]]], [[{ id: 'tab-two-section', name: 'sec_b' }]]);
+ assert.strictEqual(findSectionById(form, sections[1].id).pointer, '/tabs/0/columns/0/sections/1');
+ assert.strictEqual(findSectionById(form, '0f0f0f0f-0000-4000-8000-000000000001').pointer, '/tabs/0/columns/0/sections/0', 'case does not matter');
+ assert.strictEqual(findSectionById(form, 'tab-two-section').pointer, '/tabs/1/columns/0/sections/0');
+ // A section is added ahead of sec_two, and one is taken out of its column: the same section, found at its new place.
+ form.tabs[0].columns[0].sections.unshift({ id: 'grid', name: 'section_grid_x' });
+ assert.strictEqual(findSectionById(form, sections[1].id).pointer, '/tabs/0/columns/0/sections/2');
+ form.tabs[0].columns[0].sections.splice(0, 2);
+ const hit = findSectionById(form, sections[1].id);
+ assert.deepStrictEqual([hit.pointer, hit.rowsPointer, hit.tabIndex, hit.columnIndex, hit.sectionIndex, hit.section.name], ['/tabs/0/columns/0/sections/0', '/tabs/0/columns/0/sections/0/rows', 0, 0, 0, 'sec_two']);
+});
+
+test('findSectionById: a section that is not there, an id that is blank, and a section with no id are all null — never another section', () => {
+ const form = sectionTree([[{ id: 'a', name: 'sec_one' }, { name: 'no_id' }, { id: '', name: 'blank_id' }, { id: null, name: 'null_id' }]]);
+ assert.strictEqual(findSectionById(form, 'zzz'), null);
+ for (const blank of ['', null, undefined]) assert.strictEqual(findSectionById(form, blank), null, `id ${JSON.stringify(blank)}`);
+ assert.strictEqual(findSectionById({}, 'a'), null);
+ assert.strictEqual(findSectionById({ tabs: [{}, { columns: [{}] }] }, 'a'), null);
+ assert.strictEqual(findSectionById(form, 'a').section.name, 'sec_one');
+});
+
// The App Spec has documented `enabled`, `passExecutionContext` and `parameters` on
// `forms[].events[]` all along, but the intent builder HARDCODED all three and never read the
// authored values. An author who wrote `"enabled": false` got a handler that ran anyway — the
diff --git a/plugins/model-apps/scripts/tests/build-model-app.test.js b/plugins/model-apps/scripts/tests/build-model-app.test.js
index 3b8c5fbcd..2133f2b88 100644
--- a/plugins/model-apps/scripts/tests/build-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/build-model-app.test.js
@@ -420,6 +420,28 @@ test('transient auto-retry: a non-transient halt is NOT retried', async () => {
assert.strictEqual(attempts, 1, 'no retry on a non-transient error');
});
+// With --publish the views a rebuild reconciles are published just before the app is written (sdk-build.js,
+// publishReconciledTables), and a refusal there stops the build before the app. A throttled one must still be re-run at
+// once, as it was when each reconcile published its own view: the halt carries the refusal's status out of the runner.
+test('transient auto-retry: a publish refused with a 429 before the app is written is retried, then succeeds', async () => {
+ const { sdk, calls } = mockSdk();
+ sdk.findArtifact = async (kind) => (kind === 'view' ? 'view-existing' : null);
+ let refused = 0;
+ const publish = sdk.publishArtifact;
+ sdk.publishArtifact = async (type, id) => {
+ calls.push(['publishArtifact', type, id]);
+ if (type !== 'view' || refused > 0) return publish(type, id);
+ refused += 1;
+ return { type, id, shipped: false, publish: { kind: 'failed', error: Object.assign(new Error('HTTP 429 from PublishXml: Rate limit exceeded'), { statusCode: 429 }) } };
+ };
+ const events = [];
+ const journal = { path: 'x', record: (e) => events.push(e), close: () => {} };
+ const r = await buildModelApp(desk, { apply: true, publish: true, env: 'https://x', retryDelayMs: 0 }, { sdk, provisionSdk: sdk, journal });
+ assert.strictEqual(r.ok, true, 'the build succeeded after the retry');
+ assert.strictEqual(events.filter((e) => e.status === 'retry').length, 1, 'one retry');
+ assert.strictEqual(calls.filter((c) => c[0] === 'createArtifact' && c[1] === 'app').length, 1, 'only the attempt whose views were published wrote the app');
+});
+
// With --publish the build defers its default-view enrichment's publish to its final phase
// (sdk-build.js, 4b), so a build that halts before that phase still owes it. The CLI pays it only once
// no retry follows: a transient halt is retried at once, and the retry saves the views again and owes
@@ -471,8 +493,8 @@ test('a final halt whose owed publish fails too warns, and still reports the hal
sdk.createArtifact = (t, def) => { if (t === 'app') throw new Error('bad request'); return create(t, def); };
const warnings = [];
await assert.rejects(buildModelApp(desk, { apply: true, publish: true, env: 'https://x', retryDelayMs: 0 }, { sdk, provisionSdk: sdk, warn: (m) => warnings.push(m) }), /bad request/);
- const failed = warnings.filter((w) => /^the build stopped before its publish phase; publish view defview-\w+ FAILED: publish down/.test(w));
- assert.strictEqual(failed.length, 3, `each enriched table is still attempted, and reported: ${warnings.join('\n')}`);
+ const failed = warnings.filter((w) => /^the build stopped before its publish phase; publish default views of \w+ FAILED: publish down/.test(w));
+ assert.strictEqual(failed.length, 3, `each enriched table is still attempted, and reported by name: ${warnings.join('\n')}`);
});
test('without --publish a halted build owes nothing: the enrichment published itself', async () => {
@@ -513,6 +535,20 @@ test('a later attempt whose publish phase ran pays what an earlier one owed, and
assert.deepStrictEqual(twice.map((c) => c[1].map((t) => t.id)), [['defview-a', 'defview-b']]);
});
+test('the names an earlier attempt recorded for a debt are kept when a later attempt stops before them, and a failed settle reports them', async () => {
+ const { sdk } = owingSdk();
+ sdk.publishArtifacts = async () => { throw new Error('envelope refused'); };
+ sdk.publishArtifact = async () => { throw new Error('publish down'); };
+ // The first attempt got as far as the form; the retry stopped after the view. One debt, and both names are still owed.
+ const attempts = [owing(TRANSIENT, [['view', 'v1', ['view Open Tickets', 'form Ticket']]]), owing('bad request', [['view', 'v1', ['view Open Tickets']]])];
+ let n = 0;
+ const runBuild = async () => { throw attempts[n++]; };
+ const warnings = [];
+ await assert.rejects(buildModelApp(desk, { apply: true, publish: true, env: 'https://x', retryDelayMs: 0 }, { sdk, provisionSdk: sdk, runBuild, discoverOpDiffState: async () => quietState, warn: (m) => warnings.push(m) }), /bad request/);
+ assert.strictEqual(n, 2, 'every attempt ran');
+ assert.deepStrictEqual(warnings.filter((w) => /FAILED/.test(w)).map((w) => w.replace(/ FAILED:.*/, '')), ['the build stopped before its publish phase; publish view Open Tickets, form Ticket']);
+});
+
test('transient auto-retry: no retries in dry-run', async () => {
const { sdk } = mockSdk();
const r = await buildModelApp(desk, { apply: false, env: 'https://x' }, { sdk });
@@ -2187,6 +2223,10 @@ test('main changed-only full-fast-noop cycle uses the real flow', async () => {
row.content = Buffer.from(o.content, 'utf8').toString('base64');
};
sdk.dataverse = { get: async (url) => {
+ // The shared-page scan lists the apps that were never published: the one app here is published, so it is the only row.
+ if (url.startsWith('/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()')) {
+ return { status: 200, body: { value: state.app ? [{ appmoduleid: state.app.id, appmoduleidunique: appUniqueValue, uniquename: spec.app.uniqueName, componentstate: 0 }] : [] } };
+ }
assert.match(url, /^\/EntityDefinitions\(LogicalName='/);
return state.table && !url.includes("LogicalName='entity'")
? { status: 200, body: { LogicalName: state.table.logicalName, EntitySetName: state.table.entitySetName } }
diff --git a/plugins/model-apps/scripts/tests/check-auth.test.js b/plugins/model-apps/scripts/tests/check-auth.test.js
index adfc0c6fd..284e7bed4 100644
--- a/plugins/model-apps/scripts/tests/check-auth.test.js
+++ b/plugins/model-apps/scripts/tests/check-auth.test.js
@@ -234,6 +234,8 @@ function makeCancelableExecFile({ pacOrg = null, azUser = '[email protected]', a
async function run({ argv = [], exec = {}, whoAmI, whoAmIThrows, tokenFailure = null }) {
const calls = [];
+ // The token read is an `az` call too: with the Azure CLI missing or logged out it fails, as it would live.
+ const azUnusable = exec.azVersion === null || exec.azUser === null || (exec.notOnPath || []).includes('az');
const cli = loadCli(scriptPath, {
argv,
requires: {
@@ -246,9 +248,10 @@ async function run({ argv = [], exec = {}, whoAmI, whoAmIThrows, tokenFailure =
calls.push(`token ${url}`);
return 'token-value';
},
- getAuthTokenAsync: async (url) => {
+ getAuthTokenAsync: async (url, opts = {}) => {
calls.push(`token ${url}`);
- return tokenFailure ? null : 'token-value';
+ if (opts.signal) opts.signal.addEventListener('abort', () => calls.push(`abort token ${url}`));
+ return tokenFailure || azUnusable ? null : 'token-value';
},
tokenFailureKind: () => tokenFailure,
tokenFailureMessage: (url, fallback) => (tokenFailure === 'timeout' ? `token for ${url} timed out` : fallback),
@@ -309,12 +312,13 @@ async function runWithAsyncChildren({ argv = [], exec = {}, token, whoAmI } = {}
return result;
}
-test('a missing az CLI blocks with az_missing, and no token or WhoAmI is attempted', async () => {
+test('a missing az CLI blocks with az_missing; the token read started beside the account probe is cancelled and no WhoAmI is sent', async () => {
const r = await run({ argv: ['--env', ENVURL], exec: { azVersion: null } });
assert.equal(r.ok, false);
assert.equal(r.blocker, 'az_missing');
assert.match(r.message, /aka\.ms\/azure-cli/);
- assert.ok(!r.calls.some((c) => c.startsWith('token ') || c === 'whoami'), r.calls.join(' | '));
+ assert.ok(!r.calls.includes('whoami'), r.calls.join(' | '));
+ assert.ok(r.calls.includes(`abort token ${ENVURL}`), `the token read must not outlive the verdict: ${r.calls.join(' | ')}`);
});
// A launch that THROWS instead of calling back (Node's execFile does, synchronously, for some launch errors) is a verdict
@@ -324,7 +328,7 @@ test('an az launch that throws synchronously still blocks with a verdict (az_mis
assert.equal(r.ok, false);
assert.equal(r.blocker, 'az_missing');
assert.ok(r.calls.some((c) => c.startsWith('not on PATH: az ')), r.calls.join(' | '));
- assert.ok(!r.calls.some((c) => c.startsWith('token ') || c === 'whoami'), r.calls.join(' | '));
+ assert.ok(!r.calls.includes('whoami'), r.calls.join(' | '));
});
test('az installed but logged out blocks with az_not_logged_in', async () => {
@@ -347,7 +351,7 @@ test('an az probe that runs out of time blocks with az_timeout — not az_missin
assert.match(r.message, /did not answer within 60 s[\s\S]*POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS=120000/, slow);
assert.ok(r.calls.some((c) => /\(timeout 60000\)$/.test(c)), `the az budget is 60 s: ${r.calls.join(' | ')}`);
assert.ok(r.calls.includes('kill pac org who'), `the pac probe is cancelled: ${r.calls.join(' | ')}`);
- assert.ok(!r.calls.some((c) => c.startsWith('token ') || c === 'whoami'), r.calls.join(' | '));
+ assert.ok(r.calls.includes(`abort token ${ENVURL}`), `the token read is cancelled too: ${r.calls.join(' | ')}`);
}
// An account-show timeout is not followed by `az --version`: nothing it answers changes the verdict.
const r = await run({ argv: ['--env', ENVURL], exec: { slow: ['az account show'] } });
@@ -405,14 +409,16 @@ test('a working az login costs ONE az call before WhoAmI: `az --version` only cl
test('pac org who starts before the az probes, and the WhoAmI token is warmed while it runs', async () => {
// Measured cold starts on Windows: pac org who ~7 s, each az call ~3-5 s. Run one after another the
// preflight cost ~19 s at the start of every run; overlapped it costs about the slower branch.
+ // With an explicit environment the token read now starts beside `az account show` (it needs
+ // nothing from it), and WhoAmI is sent as soon as the token is in hand — before pac has answered.
const r = await run({ argv: ['--env', ENVURL], exec: { pacOrg: 'Connected as [email protected]\n' } });
assert.equal(r.ok, true);
assert.deepEqual(r.calls, [
'start pac org who',
'az account show --query user.name -o tsv',
`token ${ENVURL}`,
- 'done pac',
'whoami',
+ 'done pac',
]);
});
@@ -558,4 +564,236 @@ test('a mismatched-but-working identity is reported as ready WITH the caveat', a
assert.equal(r.identitiesMatch, false);
assert.match(r.message, /different identities/);
assert.match(r.message, /403/);
+});
+
+// --- the independent probes overlap, the verdicts do not move ------------------------------------------
+//
+// Gated children: every probe answers only when the test says so, which is what lets a test PROVE the order
+// things started in (not just the order they finished in) and drive each completion order by hand.
+const settle = async () => { for (let i = 0; i < 6; i += 1) await new Promise((resolve) => setImmediate(resolve)); };
+function deferred() {
+ let resolve;
+ const promise = new Promise((res) => { resolve = res; });
+ return { promise, resolve };
+}
+
+function runGated({ argv = ['--env', ENVURL], requirePac = false, tokenKind = null, whoAmIRequest = null } = {}) {
+ const events = [];
+ const gates = { account: deferred(), token: deferred(), pac: deferred(), who: deferred() };
+ const child = (label) => ({
+ killed: false,
+ stdin: { end() {} },
+ kill() { this.killed = true; events.push(`kill ${label}`); },
+ });
+ const execFileAsync = (cmd, args, _opts, cb) => {
+ const argvText = (args || []).join(' ');
+ const c = child(`${cmd} ${argvText}`);
+ if (cmd === 'pac') {
+ events.push('start pac');
+ gates.pac.promise.then((out) => { if (!c.killed) { events.push('pac answered'); cb(out === null ? new Error('spawn pac ENOENT') : null, out || '', ''); } });
+ } else if (argvText.includes('account show')) {
+ events.push('start account');
+ gates.account.promise.then((out) => { if (!c.killed) { events.push('account answered'); cb(out === null ? new Error('Please run az login') : null, out || '', ''); } });
+ } else {
+ // `az --version`, only ever run to classify an account failure.
+ events.push('start az --version');
+ setImmediate(() => cb(null, 'azure-cli 2.60.0', ''));
+ }
+ return c;
+ };
+ const cli = loadCli(scriptPath, {
+ argv: requirePac ? [...argv, '--require-pac'] : argv,
+ requires: {
+ './lib/process-runner': { execFileAsync, runSync: () => { throw new Error('sync child processes must not be used by check-auth'); } },
+ './lib/dataverse-auth': {
+ parseArgs: require('../lib/dataverse-auth.js').parseArgs,
+ validateFlags: require('../lib/dataverse-auth.js').validateFlags,
+ getAuthToken: () => { throw new Error('sync token acquisition must not be used by check-auth'); },
+ getAuthTokenAsync: (url, opts = {}) => {
+ events.push('start token');
+ if (opts.signal) opts.signal.addEventListener('abort', () => events.push('abort token'));
+ return gates.token.promise.then((value) => { events.push(value ? 'token ready' : 'token failed'); return value; });
+ },
+ tokenFailureKind: () => tokenKind,
+ tokenFailureMessage: (url, fallback) => (tokenKind === 'timeout' ? `token for ${url} timed out` : fallback),
+ // `whoAmIRequest(events)` swaps in a different WhoAmI (the real dataverseRequest over a stub transport, say);
+ // by default WhoAmI is a gate the test opens by hand.
+ dataverseRequest: whoAmIRequest ? whoAmIRequest(events) : () => {
+ events.push('start whoami');
+ return gates.who.promise.then((value) => {
+ events.push('whoami answered');
+ if (value instanceof Error) throw value;
+ return value;
+ });
+ },
+ },
+ },
+ });
+ const finished = cli.main().then(() => null, (e) => { if (e.exitCode === undefined) throw e; })
+ .then(() => JSON.parse(cli.stdoutText()));
+ return { events, gates, finished };
+}
+
+const WHO_OK = { status: 200, data: { UserId: 'u-1', OrganizationId: 'o-1' } };
+
+test('the account probe, the token read and pac are all in flight before any of them answers', async () => {
+ const { events, gates, finished } = runGated();
+ await settle();
+ assert.deepEqual(events, ['start pac', 'start account', 'start token'],
+ 'with an explicit --env nothing waits for another probe to start (before: the token read waited for the account probe)');
+ gates.account.resolve('[email protected]');
+ gates.token.resolve('token-value');
+ gates.pac.resolve('Connected as [email protected]\n');
+ gates.who.resolve(WHO_OK);
+ const r = await finished;
+ assert.equal(r.ok, true);
+ assert.equal(r.message, 'Ready (az + pac both signed in as [email protected], env https://contoso.crm.dynamics.com).');
+});
+
+test('WhoAmI is sent the moment the token is ready, while the account probe and pac are still running', async () => {
+ const { events, gates, finished } = runGated();
+ await settle();
+ gates.token.resolve('token-value');
+ await settle();
+ assert.deepEqual(events, ['start pac', 'start account', 'start token', 'token ready', 'start whoami'],
+ 'WhoAmI starts on the token alone (before: after the account probe, the token and pac had all finished)');
+ gates.who.resolve(WHO_OK);
+ await settle();
+ assert.ok(!events.includes('pac answered') && !events.includes('account answered'), 'both slower probes are still running');
+ gates.account.resolve('[email protected]');
+ gates.pac.resolve('Connected as [email protected]\n');
+ const r = await finished;
+ assert.equal(r.ok, true);
+ assert.deepEqual(r.whoAmI, { ok: true, userId: 'u-1', organizationId: 'o-1' });
+});
+
+test('an account failure outranks a token and WhoAmI that already succeeded, and cancels every probe it left running', async () => {
+ const { events, gates, finished } = runGated();
+ await settle();
+ gates.token.resolve('token-value');
+ gates.who.resolve(WHO_OK);
+ await settle();
+ assert.ok(events.includes('whoami answered'), 'WhoAmI had already answered when the account probe failed');
+ gates.account.resolve(null);
+ const r = await finished;
+ assert.equal(r.ok, false);
+ assert.equal(r.blocker, 'az_not_logged_in', 'the verdict order is unchanged: the account probe speaks first');
+ assert.ok(events.includes('kill pac org who'), events.join(' | '));
+ assert.ok(events.includes('abort token'), events.join(' | '));
+ assert.equal(events.filter((e) => e === 'start token').length, 1, 'no second token acquisition');
+});
+
+test('pac still outranks a WhoAmI failure that arrived first (--require-pac)', async () => {
+ const { gates, finished } = runGated({ requirePac: true });
+ await settle();
+ gates.token.resolve('token-value');
+ gates.who.resolve(new Error('getaddrinfo ENOTFOUND'));
+ gates.account.resolve('[email protected]');
+ await settle();
+ gates.pac.resolve(null);
+ const r = await finished;
+ assert.equal(r.blocker, 'pac_not_logged_in', 'before and after: pac is judged before WhoAmI');
+});
+
+test('a WhoAmI failure that arrives before pac does is reported once pac has answered, and is never unhandled', async () => {
+ const unhandled = [];
+ const onUnhandled = (reason) => unhandled.push(reason);
+ process.on('unhandledRejection', onUnhandled);
+ try {
+ const { gates, finished } = runGated();
+ await settle();
+ gates.token.resolve('token-value');
+ gates.who.resolve(new Error('getaddrinfo ENOTFOUND'));
+ gates.account.resolve('[email protected]');
+ await settle();
+ gates.pac.resolve('Connected as [email protected]\n');
+ const r = await finished;
+ assert.equal(r.blocker, 'whoami_error');
+ assert.match(r.message, /WhoAmI probe failed: getaddrinfo ENOTFOUND/);
+ await settle();
+ assert.deepEqual(unhandled, []);
+ } finally {
+ process.off('unhandledRejection', onUnhandled);
+ }
+});
+
+test('a token read that times out is az_timeout with no WhoAmI, and pac is cancelled', async () => {
+ const { events, gates, finished } = runGated({ tokenKind: 'timeout' });
+ await settle();
+ gates.token.resolve(null);
+ gates.account.resolve('[email protected]');
+ const r = await finished;
+ assert.equal(r.blocker, 'az_timeout');
+ assert.match(r.message, /token for https:\/\/contoso\.crm\.dynamics\.com timed out/);
+ assert.ok(!events.includes('start whoami'), 'with no token WhoAmI is not started early (it would run a blocking token read of its own)');
+ assert.ok(events.includes('kill pac org who'), events.join(' | '));
+});
+
+test('without --env nothing is started early, because the environment comes from pac', async () => {
+ const { events, gates, finished } = runGated({ argv: [] });
+ await settle();
+ assert.deepEqual(events, ['start pac', 'start account']);
+ gates.account.resolve('[email protected]');
+ gates.pac.resolve(`Connected as [email protected]\nOrg URL: ${ENVURL}/\n`);
+ await settle();
+ assert.ok(!events.includes('start token'), 'check-auth never reads a token early for an environment it does not know yet');
+ gates.who.resolve(WHO_OK);
+ const r = await finished;
+ assert.equal(r.envUrl, ENVURL);
+ assert.equal(r.ok, true);
+});
+
+// The real dataverseRequest over a stub transport: a 401 makes it replace the token with a SYNCHRONOUS Azure CLI read
+// (seconds on a cold Windows process, with the whole event loop — pac's timeout timer and the other az probe included —
+// frozen), up to twice. A wrong-tenant 401 is exactly what this preflight is run to diagnose, so the early WhoAmI must not
+// do that while the other probes are running.
+test('an early WhoAmI answered 401 does not refresh the token while the other probes run: it is sent again after pac, where the refresh blocks nothing', async () => {
+ const { dataverseRequest: realRequest } = require('../lib/dataverse-auth.js');
+ let sent = 0;
+ const { events, gates, finished } = runGated({
+ whoAmIRequest: (log) => (url, method, apiPath, body, options) => {
+ log.push('start whoami');
+ return realRequest(url, method, apiPath, body, {
+ ...options,
+ getToken: (_origin, tokenOptions) => { log.push(tokenOptions && tokenOptions.fresh ? 'refresh token (synchronous az call)' : 'token from memo'); return 'TOK'; },
+ // The first two sends are refused, the third (after a refresh) is accepted.
+ request: async () => {
+ sent += 1;
+ log.push(sent < 3 ? 'WhoAmI answered 401' : 'WhoAmI answered 200');
+ return sent < 3 ? { statusCode: 401, body: '' } : { statusCode: 200, body: JSON.stringify({ UserId: 'u-1', OrganizationId: 'o-1' }) };
+ },
+ });
+ },
+ });
+ await settle();
+ gates.token.resolve('token-value');
+ await settle();
+ assert.deepEqual(events.slice(3), ['token ready', 'start whoami', 'token from memo', 'WhoAmI answered 401'], 'the early WhoAmI was refused while pac and the account probe were still running');
+ assert.ok(!events.some((e) => /refresh/.test(e)), `no synchronous refresh while other probes run: ${events.join(' | ')}`);
+ gates.account.resolve('[email protected]');
+ gates.pac.resolve('Connected as [email protected]\n');
+ const r = await finished;
+ assert.equal(r.ok, true, JSON.stringify(r));
+ assert.deepEqual(r.whoAmI, { ok: true, userId: 'u-1', organizationId: 'o-1' });
+ const after = events.slice(events.indexOf('pac answered') + 1);
+ assert.deepEqual(after.filter((e) => e !== 'account answered'), ['start whoami', 'token from memo', 'WhoAmI answered 401', 'refresh token (synchronous az call)', 'WhoAmI answered 200'],
+ 'WhoAmI is sent again at its old place, after pac, and only that request refreshes the token');
+ assert.equal(events.filter((e) => /refresh/.test(e)).length, 1);
+});
+
+test('an early WhoAmI that is still refused after the refresh reports whoami_401, as it always did', async () => {
+ const { dataverseRequest: realRequest } = require('../lib/dataverse-auth.js');
+ const { gates, finished } = runGated({
+ whoAmIRequest: () => (url, method, apiPath, body, options) => realRequest(url, method, apiPath, body, {
+ ...options, getToken: () => 'TOK', request: async () => ({ statusCode: 401, body: '' }),
+ }),
+ });
+ await settle();
+ gates.token.resolve('token-value');
+ gates.account.resolve('[email protected]');
+ gates.pac.resolve('Connected as [email protected]\n');
+ const r = await finished;
+ assert.equal(r.ok, false);
+ assert.equal(r.blocker, 'whoami_401');
+ assert.match(r.message, /Dataverse rejected the token \(401\)/);
});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/cli-failure.test.js b/plugins/model-apps/scripts/tests/cli-failure.test.js
index c14b5a9b3..aa75ed15b 100644
--- a/plugins/model-apps/scripts/tests/cli-failure.test.js
+++ b/plugins/model-apps/scripts/tests/cli-failure.test.js
@@ -135,3 +135,179 @@ test('a CLI that answers, refuses, or is absent is not called slow', async () =>
assert.strictEqual(auth.tokenFailureKind(thrown), 'missing');
});
});
+
+// ── The time one `pac model genpage` call may take ────────────────────────────────────────────────────────────────────────────────
+// A page upload once stalled for 17 minutes — no CPU, no network — until someone killed the process, and the build then finished. So a pac call waits a bounded time:
+// generous, because a real upload of a large page is slow and a slow call is not a stalled one (3 min to list or download, 10 min to upload), and overridable for a
+// machine or an environment that is slower than that.
+const { PAC_TIMEOUT_ENV, DEFAULT_PAC_READ_TIMEOUT_MS, DEFAULT_PAC_UPLOAD_TIMEOUT_MS, MIN_PAC_TIMEOUT_MS, MAX_PAC_TIMEOUT_MS, pacTimeoutMs, pacLongerTimeoutMs, pacTimeoutAdvice } = require('../lib/cli-failure.js');
+
+test('pacTimeoutMs: 3 min to list or download, 10 min to upload, or the environment override within 1 s..60 min for any of them', () => {
+ assert.strictEqual(DEFAULT_PAC_READ_TIMEOUT_MS, 180000);
+ assert.strictEqual(DEFAULT_PAC_UPLOAD_TIMEOUT_MS, 600000);
+ for (const kind of ['list', 'download']) assert.strictEqual(pacTimeoutMs(kind, {}), 180000, kind);
+ assert.strictEqual(pacTimeoutMs('upload', {}), 600000);
+ for (const kind of ['list', 'download', 'upload']) {
+ assert.strictEqual(pacTimeoutMs(kind, { [PAC_TIMEOUT_ENV]: '45000' }), 45000, `${kind}: the override applies to every kind`);
+ assert.strictEqual(pacTimeoutMs(kind, { [PAC_TIMEOUT_ENV]: String(MIN_PAC_TIMEOUT_MS) }), MIN_PAC_TIMEOUT_MS, `${kind}: the minimum`);
+ assert.strictEqual(pacTimeoutMs(kind, { [PAC_TIMEOUT_ENV]: String(MAX_PAC_TIMEOUT_MS) }), MAX_PAC_TIMEOUT_MS, `${kind}: the maximum`);
+ }
+ assert.strictEqual(MAX_PAC_TIMEOUT_MS, 3600000);
+ // An unusable value keeps the default for the kind rather than failing the run (the same rule as the Azure CLI budget).
+ for (const bad of ['', 'abc', '999', '3600001', '1.5', '-5000', '0']) {
+ assert.strictEqual(pacTimeoutMs('list', { [PAC_TIMEOUT_ENV]: bad }), 180000, bad);
+ assert.strictEqual(pacTimeoutMs('upload', { [PAC_TIMEOUT_ENV]: bad }), 600000, bad);
+ }
+ assert.strictEqual(pacTimeoutMs('upload'), pacTimeoutMs('upload', process.env), 'the process environment by default');
+});
+
+test('pacLongerTimeoutMs suggests only a budget pacTimeoutMs accepts, and none once the budget is the maximum', () => {
+ for (const ms of [1000, 45000, 180000, 600000, 1799999, 1800000, 3599999]) {
+ const longer = pacLongerTimeoutMs(ms);
+ assert.ok(longer > ms && longer <= MAX_PAC_TIMEOUT_MS, `${ms} -> ${longer}`);
+ assert.strictEqual(pacTimeoutMs('upload', { [PAC_TIMEOUT_ENV]: String(longer) }), longer, `${ms}: ${longer} is accepted, not replaced by the default`);
+ }
+ assert.strictEqual(pacLongerTimeoutMs(1000), 300000, 'at least five minutes');
+ assert.strictEqual(pacLongerTimeoutMs(600000), 1200000, 'otherwise double');
+ assert.strictEqual(pacLongerTimeoutMs(MAX_PAC_TIMEOUT_MS), null, 'nothing larger would be read');
+});
+
+test('pacTimeoutAdvice names the call and its budget, suggests only a budget pacTimeoutMs accepts, and none once the budget is the maximum', () => {
+ assert.match(pacTimeoutAdvice('pac model genpage upload', 600000), /`pac model genpage upload` did not finish within 600 s and was stopped[\s\S]*POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS=1200000/);
+ for (const ms of [1000, 45000, 180000, 600000, 1799999, 1800000, 3599999]) {
+ const m = /POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS=(\d+)/.exec(pacTimeoutAdvice('pac model genpage list', ms));
+ assert.ok(m, `${ms}: a budget is suggested`);
+ const suggested = Number(m[1]);
+ assert.ok(suggested > ms && suggested <= MAX_PAC_TIMEOUT_MS, `${ms} -> ${suggested}`);
+ assert.strictEqual(pacTimeoutMs('list', { [PAC_TIMEOUT_ENV]: m[1] }), suggested, `${ms}: the suggested ${suggested} is accepted, not replaced by the default`);
+ }
+ const atMax = pacTimeoutAdvice('pac model genpage upload', MAX_PAC_TIMEOUT_MS);
+ assert.doesNotMatch(atMax, /POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS=\d/, 'no larger budget to suggest');
+ assert.match(atMax, /did not finish within 3600 s and was stopped\. That is already the longest POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS allows \(60 min\)/);
+});
+
+// A command a message tells the user — or the agent — to paste: a path under a Windows profile folder often has a space ("C:\Users\Dev User\..."), and a path from an
+// untrusted checkout can hold shell syntax (`x;rm -rf ~;.tsx`, `$(…)`, backticks). It must reach the program the command runs as exactly ONE argument that no shell
+// reads anything in — in the shells the skill's commands are written for, PowerShell and the POSIX shells — or not be written into the command at all.
+test('commandArg writes a plain value bare, quotes everything else in single quotes, and has no spelling for what a shell cannot pass on unchanged', () => {
+ const { commandArg, commandArgOrPlaceholder } = require('../lib/cli-failure.js');
+ for (const plain of ['out/overview.tsx', 'page.tsx', 'C:/Users/Dev/page.tsx', 'café/página-1_v2.tsx', 'a:b']) {
+ assert.strictEqual(commandArg(plain), plain, `${plain}: written bare`);
+ }
+ assert.strictEqual(commandArg(42), '42', 'a value that is not a string is written as its text');
+ const quoted = {
+ 'C:\\Users\\Dev\\page.tsx': 'a backslash escapes in a POSIX shell',
+ 'C:\\Users\\Dev User\\page.tsx': 'white space splits',
+ 'my page.tsx': 'white space splits',
+ 'a\tb.tsx': 'a tab splits too',
+ 'x;echo INJECTED;.tsx': 'a semicolon ends the command',
+ 'x$(echo INJECTED).tsx': 'command substitution',
+ 'x`echo INJECTED`.tsx': 'backticks (PowerShell\'s escape, a POSIX substitution)',
+ 'a|b': 'a pipe', 'a&b': 'an ampersand', 'a>b': 'a redirect', '*.tsx': 'a glob', '#x.tsx': 'a comment', '~/x.tsx': 'a home expansion',
+ 'a,b.tsx': 'an array in PowerShell', '@x.tsx': 'splatting in PowerShell', '-x.tsx': 'a leading dash reads as a flag', '{a}.tsx': 'a brace',
+ '$HOME.tsx': 'a variable', 'a!b.tsx': 'history expansion', 'a%b%.tsx': 'a percent',
+ 'x\\': 'a final backslash with no white space: Windows PowerShell does not wrap the value in quotes',
+ 'a b\\x.tsx': 'white space with a backslash that is not the last character',
+ 'a\u201Cb\u201D.tsx': 'PowerShell\'s curly double quotes: literal inside single quotes, passed on as they are',
+ '--%x': 'only the exact value is PowerShell\'s stop-parsing token', ' --%': 'nor is it with white space around it',
+ };
+ for (const [value, why] of Object.entries(quoted)) {
+ assert.strictEqual(commandArg(value), `'${value}'`, `${JSON.stringify(value)} (${why}): single-quoted`);
+ }
+ const none = {
+ "it's.tsx": 'a single quote', 'it\u2019s.tsx': 'one PowerShell reads as a single quote', 'it\u2018s.tsx': 'one PowerShell reads as a single quote',
+ 'it\u201As.tsx': 'one PowerShell reads as a single quote', 'it\u201Bs.tsx': 'one PowerShell reads as a single quote',
+ 'a\nb.tsx': 'a line break', 'a\rb.tsx': 'a carriage return', 'a\u0000b.tsx': 'a control character', 'a\u0085b.tsx': 'a next-line character',
+ 'a\u2028b.tsx': 'a line separator', 'a\u2029b.tsx': 'a paragraph separator',
+ 'x"y.tsx': 'Windows PowerShell drops a double quote on its way to a program',
+ 'C:\\Users\\Dev User\\': 'Windows PowerShell quotes a value with white space, and the program reads its final \\" as an escaped quote',
+ 'a\u3000b\\': 'any white space, not only a space, makes Windows PowerShell quote the value',
+ '': 'Windows PowerShell passes an empty value as no argument at all',
+ '--%': 'PowerShell\'s stop-parsing token, dropped even when quoted',
+ };
+ for (const [value, why] of Object.entries(none)) {
+ assert.strictEqual(commandArg(value), null, `${JSON.stringify(value)} (${why}): no spelling`);
+ const { arg, note } = commandArgOrPlaceholder(value, '<file>');
+ assert.strictEqual(arg, '<file>');
+ assert.strictEqual(note, `<file> is ${JSON.stringify(value)}; it is not written into the command because no way of writing it reaches the command unchanged in both PowerShell and a POSIX shell.`);
+ }
+ assert.deepStrictEqual(commandArgOrPlaceholder('my page.tsx', '<file>'), { arg: "'my page.tsx'", note: '' });
+});
+
+// The claim above, checked against real shells and a real program: every spelling goes, the way the advice is pasted, into a command that runs node, and node's
+// argv must be exactly the values — each one argument, unchanged — with nothing in them run. Printing a value from inside the shell would not do: Windows PowerShell
+// changes an argument only on its way to a native program. Every shell found is used: Windows PowerShell (always there on Windows) and PowerShell 7 (pwsh) when it is
+// installed; elsewhere sh, and bash, zsh and pwsh when they are installed.
+test('commandArg\'s spellings reach a program run from a real shell as exactly the value, and nothing in them runs', () => {
+ const { commandArg } = require('../lib/cli-failure.js');
+ const { spawnSync } = require('node:child_process');
+ const os = require('node:os');
+ const path = require('node:path');
+ const fs = require('node:fs');
+ const values = ['C:\\Users\\Dev User\\page.tsx', 'x;echo INJECTED;.tsx', 'x$(echo INJECTED).tsx', 'x`echo INJECTED`.tsx', 'x"y.tsx', 'a|b', 'a&b', '*.tsx', '#x', '~/x', 'a,b', '@x',
+ '-x', '{a}', '$HOME', '${HOME}', 'a!b', 'a%PATH%b', 'café page.tsx', 'a\tb', 'x\\', 'x\\\\y', 'a b\\x', 'a\u201Cb\u201D', '--%x', ' --%', '\'unused', '', '--%',
+ 'C:\\Users\\Dev User\\'].filter((v) => commandArg(v) !== null);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'command-arg-'));
+ try {
+ const probe = path.join(dir, 'argv.js');
+ fs.writeFileSync(probe, "require('node:fs').writeFileSync(process.env.COMMAND_ARG_OUT, JSON.stringify(process.argv.slice(2)));\n", 'utf8');
+ const program = [process.execPath, probe].map(commandArg);
+ assert.ok(program.every((arg) => arg !== null), `node and the probe have a spelling: ${program}`);
+ const windows = process.platform === 'win32';
+ const shells = windows ? ['powershell.exe', 'pwsh'] : ['sh', 'bash', 'zsh', 'pwsh'];
+ const required = windows ? 'powershell.exe' : 'sh';
+ const ran = [];
+ for (const shell of shells) {
+ const powershell = shell === 'powershell.exe' || shell === 'pwsh';
+ const name = shell.replace(/\W/g, '');
+ const script = path.join(dir, `probe-${name}.${powershell ? 'ps1' : 'sh'}`);
+ // `&` runs a quoted program path in PowerShell. Windows PowerShell reads a script as UTF-8 only with a BOM.
+ fs.writeFileSync(script, `${powershell ? '\uFEFF& ' : ''}${program.join(' ')} ${values.map(commandArg).join(' ')}\n`, 'utf8');
+ const out = path.join(dir, `argv-${name}.json`);
+ const args = powershell ? ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script] : [script];
+ const r = spawnSync(shell, args, { encoding: 'utf8', env: { ...process.env, COMMAND_ARG_OUT: out } });
+ if (r.error && r.error.code === 'ENOENT' && shell !== required) continue;
+ assert.ifError(r.error);
+ assert.strictEqual(r.status, 0, `${shell}: ${r.stderr}`);
+ assert.deepStrictEqual(JSON.parse(fs.readFileSync(out, 'utf8')), values, `${shell}: node got each value as one argument, unchanged`);
+ assert.doesNotMatch(r.stdout, /INJECTED/, `${shell}: no command in a value ran`);
+ ran.push(shell);
+ }
+ assert.ok(ran.includes(required), `ran in ${ran.join(', ')}`);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+// What commandArg refuses, run through the same shells: each value it has no spelling for does NOT arrive unchanged when single-quoted — so refusing it is
+// needed, not just cautious. Windows only: the POSIX shells pass every one of them on; it is Windows PowerShell's command line (and, for `--%`, both PowerShells)
+// that changes them.
+test('a value commandArg has no spelling for is one a real Windows shell does not pass on unchanged when single-quoted', { skip: process.platform !== 'win32' && 'the values are changed on Windows' }, () => {
+ const { commandArg } = require('../lib/cli-failure.js');
+ const { spawnSync } = require('node:child_process');
+ const os = require('node:os');
+ const path = require('node:path');
+ const fs = require('node:fs');
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'command-arg-none-'));
+ try {
+ // The probe writes the arguments after its first to the file its first names, so one script can run it once per value (a `--%` acts only on its own line).
+ const probe = path.join(dir, 'argv.js');
+ fs.writeFileSync(probe, "require('node:fs').writeFileSync(process.argv[2], JSON.stringify(process.argv.slice(3)));\n", 'utf8');
+ const values = ['x"y.tsx', 'C:\\Users\\Dev User\\', 'a\u3000b\\', '', '--%'];
+ // Each value between two markers, so a dropped value shows as two neighbours.
+ const lines = values.map((value, i) => {
+ assert.strictEqual(commandArg(value), null, JSON.stringify(value));
+ return `& ${commandArg(process.execPath)} ${commandArg(probe)} ${commandArg(path.join(dir, `argv-${i}.json`))} '<' '${value}' '>'`;
+ });
+ const script = path.join(dir, 'probe.ps1');
+ fs.writeFileSync(script, `\uFEFF${lines.join('\n')}\n`, 'utf8');
+ const r = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script], { encoding: 'utf8' });
+ assert.ifError(r.error);
+ values.forEach((value, i) => {
+ const got = JSON.parse(fs.readFileSync(path.join(dir, `argv-${i}.json`), 'utf8'));
+ assert.notDeepStrictEqual(got, ['<', value, '>'], `${JSON.stringify(value)} arrives unchanged, so commandArg could spell it`);
+ });
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/content-hash.test.js b/plugins/model-apps/scripts/tests/content-hash.test.js
index 4ef320eec..691eb3a7d 100644
--- a/plugins/model-apps/scripts/tests/content-hash.test.js
+++ b/plugins/model-apps/scripts/tests/content-hash.test.js
@@ -1,7 +1,7 @@
'use strict';
const { test } = require('node:test');
const assert = require('node:assert');
-const { annotateContentHashes, pageContentPath, pageSourceFileErrors } = require('../lib/content-hash.js');
+const { annotateContentHashes, recordedContentSha, pageContentPath, pageSourceFileErrors } = require('../lib/content-hash.js');
const { diffPhases } = require('../lib/phase-diff.js');
// A minimal spec with one implemented tsx page + one contentPath web resource + one inline web resource.
@@ -143,3 +143,23 @@ test('pageSourceFileErrors: a lexically confined link resolving outside the work
"page 'overview': codeFile 'pages/overview.tsx' resolves outside the workspace",
]);
});
+
+// What the build compares a page's source with: the hash an earlier apply recorded in last-applied.json (the annotated spec readBaseline returns). Anything that is not a recorded
+// hash is "no record" — which no source can be said to match — and never a hash that could be mistaken for one.
+test('recordedContentSha: the hash an earlier apply recorded for a page by its key (or its name, for a spec with no key), and null for anything that is not a recorded hash', () => {
+ const recorded = annotateContentHashes(spec(), resolver(baseStore()));
+ const sha = recorded.pages[0].__contentSha;
+ assert.match(sha, /^[0-9a-f]{64}$/);
+ assert.strictEqual(recordedContentSha(recorded, 'overview'), sha);
+ // The same bytes hash to the same record, and an edit does not: that is the comparison the build makes.
+ assert.strictEqual(recordedContentSha(annotateContentHashes(spec(), resolver(baseStore())), 'overview'), sha);
+ assert.notStrictEqual(recordedContentSha(annotateContentHashes(spec(), resolver({ ...baseStore(), 'pages/overview.tsx': 'edited' })), 'overview'), sha);
+ assert.strictEqual(recordedContentSha({ pages: [{ name: 'Legacy', __contentSha: sha }] }, 'Legacy'), sha, 'a page with no key is found by its name');
+ // No record: an intent page (nothing on disk to hash), a page that is not there, a source that could not be read then, a hash that is not text, and no baseline at all.
+ assert.strictEqual(recordedContentSha(recorded, 'design-only'), null);
+ assert.strictEqual(recordedContentSha(recorded, 'missing'), null);
+ assert.strictEqual(recordedContentSha(annotateContentHashes(spec(), resolver({})), 'overview'), null, 'recorded as null when its source could not be read');
+ assert.strictEqual(recordedContentSha({ pages: [{ key: 'overview', __contentSha: '' }] }, 'overview'), null);
+ assert.strictEqual(recordedContentSha({ pages: [{ key: 'overview', __contentSha: 7 }] }, 'overview'), null);
+ for (const none of [undefined, null, {}, { pages: null }, { pages: 'x' }, { pages: [null, 3, 'x'] }]) assert.strictEqual(recordedContentSha(none, 'overview'), null, JSON.stringify(none));
+});
diff --git a/plugins/model-apps/scripts/tests/dataverse-auth.test.js b/plugins/model-apps/scripts/tests/dataverse-auth.test.js
index 19a15d21d..7da2d81d4 100644
--- a/plugins/model-apps/scripts/tests/dataverse-auth.test.js
+++ b/plugins/model-apps/scripts/tests/dataverse-auth.test.js
@@ -311,6 +311,76 @@ test('getAuthTokenAsync shares the token memo with getAuthToken and honors fresh
]);
});
+test('cancelling a getAuthTokenAsync read ends the child\'s whole process tree, not just the wrapper Node starts, and is not a remembered failure', async () => {
+ // check-auth starts this read beside `az account show`; when the account verdict ends the run, the token child is
+ // cancelled. On Windows `az` is a batch shim under cmd.exe, so Node's own abort would end only that wrapper and leave az's
+ // Python process running after this one exits — the abort is handled here, through killProcessTree, and the signal is not
+ // handed to the child's start. The cancellation must also not be recorded as the Azure CLI failing: a later reader of
+ // tokenFailureKind would be told the CLI "failed" when it was simply told to stop.
+ const { getAuthTokenAsync, tokenFailureKind } = require('../lib/dataverse-auth.js');
+ const url = 'https://contoso-abort.crm.dynamics.com';
+ const controller = new AbortController();
+ const child = { pid: 4242 };
+ const killed = [];
+ let seen;
+ let finish;
+ const execFile = (_file, _args, options, cb) => { seen = options; finish = cb; return child; };
+ const pending = getAuthTokenAsync(url, { execFile, signal: controller.signal, killTree: (c) => killed.push(c) });
+ assert.ok(!('signal' in seen), 'the signal is not handed to Node, whose own kill would reach only the cmd.exe wrapper');
+ assert.deepEqual(killed, [], 'nothing is ended before the abort');
+ controller.abort();
+ assert.deepEqual(killed, [child], 'the abort ends the child\'s process tree');
+ finish(Object.assign(new Error('Command failed'), { code: 1 }), '', '');
+ assert.equal(await pending, null);
+ assert.equal(tokenFailureKind(url), null, 'a cancelled read leaves no failure behind');
+});
+
+test('a getAuthTokenAsync read that already finished is not ended by a later abort, and one cancelled before it starts runs nothing', async () => {
+ const { getAuthTokenAsync } = require('../lib/dataverse-auth.js');
+ const controller = new AbortController();
+ const killed = [];
+ const execFile = (_file, _args, _options, cb) => { setImmediate(() => cb(null, 'TOKEN\n', '')); return { pid: 7 }; };
+ assert.equal(await getAuthTokenAsync('https://contoso-finished.crm.dynamics.com', { execFile, signal: controller.signal, killTree: (c) => killed.push(c) }), 'TOKEN');
+ controller.abort();
+ assert.deepEqual(killed, [], 'the child had finished: there is nothing to end');
+ let started = 0;
+ const cancelled = new AbortController();
+ cancelled.abort();
+ assert.equal(await getAuthTokenAsync('https://contoso-never.crm.dynamics.com', { execFile: () => { started += 1; return {}; }, signal: cancelled.signal }), null);
+ assert.equal(started, 0, 'no process is started for a read that was already cancelled');
+});
+
+test('without a signal getAuthTokenAsync starts the CLI with exactly the options it always did, and a real failure is still remembered', async () => {
+ const { getAuthTokenAsync, tokenFailureKind } = require('../lib/dataverse-auth.js');
+ const url = 'https://contoso-plain.crm.dynamics.com';
+ let seen;
+ const execFile = (_file, _args, options, cb) => { seen = options; setImmediate(() => cb(Object.assign(new Error('boom'), { killed: true, signal: 'SIGTERM' }), '', '')); return {}; };
+ assert.equal(await getAuthTokenAsync(url, { execFile }), null);
+ assert.deepEqual(Object.keys(seen).sort(), ['encoding', 'timeout', 'windowsHide'], 'no `signal` key unless the caller supplied one');
+ assert.equal(tokenFailureKind(url), 'timeout');
+});
+
+test('dataverseRequest hands a 401 back without refreshing the token when refreshOn401 is false — the refresh is a synchronous CLI read', async () => {
+ const { dataverseRequest } = require('../lib/dataverse-auth.js');
+ const run = async (options) => {
+ const tokenCalls = [];
+ let sends = 0;
+ const res = await dataverseRequest('https://contoso.crm.dynamics.com', 'GET', 'WhoAmI', null, {
+ getToken: (_url, o) => { tokenCalls.push(Boolean(o && o.fresh)); return 'TOK'; },
+ request: async () => { sends += 1; return { statusCode: 401, body: '' }; },
+ ...options,
+ });
+ return { res, tokenCalls, sends };
+ };
+ const refreshing = await run({});
+ assert.deepEqual(refreshing.tokenCalls, [false, true, true], 'by default each 401 is followed by a fresh token read, twice');
+ assert.equal(refreshing.sends, 3);
+ const handedBack = await run({ refreshOn401: false });
+ assert.equal(handedBack.res.status, 401);
+ assert.deepEqual(handedBack.tokenCalls, [false], 'only the memoized token was used: no synchronous read');
+ assert.equal(handedBack.sends, 1, 'and the 401 was not sent again');
+});
+
test('emitResult: partial-failure object writes JSON to stdout (not [object Object])', () => {
// Spawn a tiny script that calls emitResult(false, {errors:[...]}) and
// verify that stdout contains the JSON payload — not the literal string
@@ -795,6 +865,71 @@ test('dataverseRequest builds the request on the validated origin and requests t
assert.equal(url, 'https://contoso.crm.dynamics.com/api/data/v9.2/WhoAmI');
});
+test('a path that leaves the Web API root is refused before a token is read or a request sent', async () => {
+ const { dataverseRequest } = require('../lib/dataverse-auth.js');
+ // [path, where it resolves]. Each spelling reached an endpoint outside /api/data/v9.2/ on a live
+ // environment with the released code. The client resolves the first seven itself; the server decodes
+ // %2F / %5C and resolves the next three. The last one leaves the root as the client sends it, although
+ // the server's further decoding would bring it back: the client reading is checked on its own too.
+ const escapes = [
+ ['../v9.0/WhoAmI', '/api/data/v9.0/WhoAmI'],
+ ['../../../XRMServices/2011/Organization.svc/web', '/XRMServices/2011/Organization.svc/web'],
+ ['%2e%2e/%2E%2e/%2e%2E/XRMServices/2011/Organization.svc/web', '/XRMServices/2011/Organization.svc/web'],
+ ['.%2e/v9.0/WhoAmI', '/api/data/v9.0/WhoAmI'],
+ ['..\\..\\..\\XRMServices\\2011\\Organization.svc\\web', '/XRMServices/2011/Organization.svc/web'],
+ ['a%2Fb/../../x', '/api/data/x'],
+ ['..', '/api/data/'],
+ ['..%2Fv9.0%2FWhoAmI', '/api/data/v9.0/WhoAmI'],
+ ['..%5cv9.0%5cWhoAmI', '/api/data/v9.0/WhoAmI'],
+ ['.%2e%2Fv9.0%2FWhoAmI', '/api/data/v9.0/WhoAmI'],
+ ['../x%2F..%2Fv9.2%2FWhoAmI', '/api/data/x%2F..%2Fv9.2%2FWhoAmI'],
+ ];
+ for (const [apiPath, resolved] of escapes) {
+ let tokens = 0;
+ let sent = 0;
+ await assert.rejects(
+ dataverseRequest('https://contoso.crm.dynamics.com', 'GET', apiPath, null, {
+ getToken: () => { tokens += 1; return 'TOK'; },
+ request: async () => { sent += 1; return { statusCode: 200, body: '{}' }; },
+ }),
+ (e) => /leaves the Dataverse Web API root \/api\/data\/v9\.2\//.test(e.message) && e.message.includes(`resolves to '${resolved}'`),
+ apiPath
+ );
+ assert.equal(tokens, 0, apiPath);
+ assert.equal(sent, 0, apiPath);
+ }
+ await assert.rejects(
+ dataverseRequest('https://contoso.crm.dynamics.com', 'GET', undefined, null, { getToken: () => 'TOK', request: async () => ({ statusCode: 200, body: '{}' }) }),
+ /must be text \(got undefined\)/
+ );
+});
+
+test('a path inside the Web API root is sent exactly as before', async () => {
+ const { dataverseRequest } = require('../lib/dataverse-auth.js');
+ const accepted = [
+ 'WhoAmI',
+ "EntityDefinitions(LogicalName='account')/Attributes?$select=LogicalName",
+ '$batch',
+ // Dataverse answers /api/data/v9.2//WhoAmI and WhoAmI%2F like WhoAmI (measured).
+ '/WhoAmI',
+ 'WhoAmI%2F',
+ // Decoded by the server, this resolves back inside the root.
+ 'x/..%2F..%2Fv9.2%2FWhoAmI',
+ // Dot segments inside a query are data, not a path.
+ "accounts?$filter=name eq '../../x'",
+ // An absolute URL is only text under the root: it cannot change where the request goes.
+ 'https://example.com/x',
+ ];
+ for (const apiPath of accepted) {
+ let url;
+ await dataverseRequest('https://contoso.crm.dynamics.com', 'GET', apiPath, null, {
+ getToken: () => 'TOK',
+ request: async (o) => { url = o.url; return { statusCode: 200, body: '{}' }; },
+ });
+ assert.equal(url, `https://contoso.crm.dynamics.com/api/data/v9.2/${apiPath}`, apiPath);
+ }
+});
+
test('createAzHttpClient requests its token for the validated origin, never the text it was given', async () => {
const { createAzHttpClient } = require('../lib/sdk-http-client.js');
assert.throws(() => createAzHttpClient('https://contoso.crm.dynamics.com/&whoami', { getToken: () => 'TOK' }), /Invalid Dataverse org URL/);
@@ -842,4 +977,91 @@ test('the Dataverse entry points refuse a non-origin URL before anything runs (r
} finally {
fs.rmSync(work, { recursive: true, force: true });
}
+});
+
+// Cancelling the token read, end to end on a real cmd.exe. `az.cmd` runs the Azure CLI's program as cmd.exe's CHILD, so ending only
+// the cmd.exe Node started (what an AbortSignal handed to execFile does) leaves that program running after the process that
+// cancelled it has exited. Here the "CLI" is a node program that records its pid and idles.
+test('aborting a real getAuthTokenAsync read ends the program the az shim started too, so nothing is left running (real cmd.exe, Windows)', { skip: process.platform !== 'win32' }, () => {
+ const { spawnSync } = require('node:child_process');
+ const fs = require('node:fs');
+ const os = require('node:os');
+ const path = require('node:path');
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), 'dv-abort-e2e-'));
+ const pidFile = path.join(work, 'az-program.pid');
+ const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } };
+ let program = 0;
+ try {
+ const bin = path.join(work, 'bin');
+ fs.mkdirSync(bin);
+ // The timer is a backstop: whatever a failing run leaves behind ends by itself.
+ fs.writeFileSync(path.join(bin, 'idle.js'), `require('fs').writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); setTimeout(() => process.exit(0), 120000);\n`, 'utf8');
+ fs.writeFileSync(path.join(bin, 'az.cmd'), `@echo off\r\n"${process.execPath}" "${path.join(bin, 'idle.js')}" %*\r\n`, 'utf8');
+ const url = 'https://contoso.crm.dynamics.com';
+ const driver = `
+ const fs = require('fs');
+ const { getAuthTokenAsync, tokenFailureKind } = require(${JSON.stringify(path.join(__dirname, '..', 'lib', 'dataverse-auth.js'))});
+ (async () => {
+ const controller = new AbortController();
+ const read = getAuthTokenAsync(${JSON.stringify(url)}, { signal: controller.signal });
+ for (let i = 0; i < 150 && !fs.existsSync(${JSON.stringify(pidFile)}); i += 1) await new Promise((resolve) => setTimeout(resolve, 100));
+ controller.abort();
+ process.stdout.write(JSON.stringify({ token: await read, failure: tokenFailureKind(${JSON.stringify(url)}) }));
+ })();`;
+ const env = { ...process.env, Path: `${bin};${process.env.SystemRoot}\\System32`, PATH: `${bin};${process.env.SystemRoot}\\System32` };
+ const run = spawnSync(process.execPath, ['-e', driver], { cwd: work, env, encoding: 'utf8', timeout: 60000 });
+ assert.equal(run.status, 0, `${run.stdout}${run.stderr}`);
+ assert.deepEqual(JSON.parse(run.stdout), { token: null, failure: null }, 'a cancelled read is null and leaves no failure behind');
+ program = Number(fs.readFileSync(pidFile, 'utf8'));
+ assert.ok(program > 0, 'the az shim started its program');
+ // The tree was ended before the reader that cancelled it exited; allow the OS a moment to finish reaping it.
+ const until = Date.now() + 5000;
+ while (alive(program) && Date.now() < until) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
+ assert.equal(alive(program), false, 'the program the az shim started is no longer running');
+ } finally {
+ // Whatever the assertions above found, never leave the program the shim started running.
+ if (!program && fs.existsSync(pidFile)) program = Number(fs.readFileSync(pidFile, 'utf8')) || 0;
+ if (program && alive(program)) { try { process.kill(program); } catch { /* already gone */ } }
+ fs.rmSync(work, { recursive: true, force: true });
+ }
+});
+
+// --- emitResult: `ascii` keeps a script's stdout pure ASCII ----------------------------------------------------
+//
+// An agent reads a script's stdout off a console. Windows PowerShell 5.1 decodes a child's output with the OEM code
+// page, so UTF-8 bytes of an em dash arrive as three other characters; written as a \uXXXX escape the same JSON
+// survives any code page. Only a script that asks for it changes — every other caller keeps the raw text.
+test('emitResult with `ascii` writes every character above U+007E as a \\uXXXX escape, in either outcome, and leaves stderr as written', () => {
+ const { spawnSync } = require('node:child_process');
+ const path = require('node:path');
+ const libPath = path.join(__dirname, '..', 'lib', 'dataverse-auth.js');
+ // An em dash and an accented letter (BMP), an emoji (a surrogate pair, as JSON writes a character outside the BMP),
+ // DEL, and the characters JSON.stringify already escapes.
+ const message = 'Norwegian Bokm\u00e5l \u2014 \ud83d\ude00 \u007f "quoted" \\ back\nline';
+ for (const [ok, status] of [[true, 0], [false, 1]]) {
+ const payload = { ok, error: message, list: ['1025 ar-SA \u2014 RTL: Yes'] };
+ const code = `
+ const { emitResult } = require(${JSON.stringify(libPath)});
+ emitResult(${ok}, ${JSON.stringify(payload)}, { ascii: true });
+ `;
+ const res = spawnSync(process.execPath, ['-e', code], { encoding: 'utf8' });
+ assert.equal(res.status, status, `ok=${ok}: ${res.stderr}`);
+ assert.match(res.stdout, /^[\x00-\x7e\r\n]*$/, `ok=${ok}: pure ASCII`);
+ assert.ok(res.stdout.includes('\\u2014') && res.stdout.includes('\\u00e5') && res.stdout.includes('\\ud83d\\ude00') && res.stdout.includes('\\u007f'), res.stdout);
+ assert.deepEqual(JSON.parse(res.stdout.trim()), payload, `ok=${ok}: the same document, decoded`);
+ if (!ok) assert.equal(res.stderr.trim(), message.trim(), 'stderr is for people and is not escaped');
+ }
+});
+
+test('emitResult without `ascii` still writes the raw text: no other script\u2019s output changes', () => {
+ const { spawnSync } = require('node:child_process');
+ const path = require('node:path');
+ const libPath = path.join(__dirname, '..', 'lib', 'dataverse-auth.js');
+ const code = `
+ const { emitResult } = require(${JSON.stringify(libPath)});
+ emitResult(true, { s: '1025 ar-SA \\u2014 RTL: Yes' });
+ `;
+ const res = spawnSync(process.execPath, ['-e', code], { encoding: 'utf8' });
+ assert.equal(res.status, 0, res.stderr);
+ assert.ok(res.stdout.includes('\u2014') && !res.stdout.includes('\\u2014'), res.stdout);
});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/dataverse-request.test.js b/plugins/model-apps/scripts/tests/dataverse-request.test.js
index 285e2a5a9..24221e277 100644
--- a/plugins/model-apps/scripts/tests/dataverse-request.test.js
+++ b/plugins/model-apps/scripts/tests/dataverse-request.test.js
@@ -123,3 +123,16 @@ test('Dataverse request failures are written to stderr and exit 1', () => {
assert.equal(res.stdout, '');
assert.match(res.stderr, /^token unavailable\r?\n$/);
});
+
+test('the real script refuses a path that leaves the Web API root, with no Azure CLI on PATH', () => {
+ // No stub: the shipped library runs. An empty PATH means a token read would fail with a different
+ // message, so the assertion also proves the path was refused before any token was asked for.
+ const res = spawnSync(process.execPath, [scriptPath, 'https://contoso.crm.dynamics.com', 'GET', '../../../XRMServices/2011/Organization.svc/web'], {
+ encoding: 'utf8',
+ env: { ...process.env, PATH: mkdirTemp(), Path: undefined },
+ });
+
+ assert.equal(res.status, 1);
+ assert.equal(res.stdout, '');
+ assert.match(res.stderr, /leaves the Dataverse Web API root \/api\/data\/v9\.2\/ \(it resolves to '\/XRMServices\/2011\/Organization\.svc\/web'\)/);
+});
diff --git a/plugins/model-apps/scripts/tests/deployed-baseline.test.js b/plugins/model-apps/scripts/tests/deployed-baseline.test.js
index 4583177ba..36b6195ba 100644
--- a/plugins/model-apps/scripts/tests/deployed-baseline.test.js
+++ b/plugins/model-apps/scripts/tests/deployed-baseline.test.js
@@ -160,3 +160,70 @@ test('a baseline the migrator cannot read is no baseline, not a crash', () => {
fs.rmSync(dir, { recursive: true, force: true });
}
});
+
+// A page's `__contentSha` is the source an apply SENT, and the build's Griffel check judges the next source against it (sdk-build.js griffelStanding). So it must describe what the apply
+// looked at — not the file as it is when the baseline is written, which a maker can have saved over while the build ran (the baseline is written when the build ends).
+const { sha256 } = require('../lib/hash.js');
+const twoPages = () => ({ ...spec(), pages: [
+ { key: 'home', name: 'Home', source: { kind: 'tsx', codeFile: 'pages/home.tsx' } },
+ { key: 'about', name: 'About', source: { kind: 'tsx', codeFile: 'pages/about.tsx' } },
+ { key: 'idea', name: 'Idea', source: { kind: 'intent' } },
+] });
+function twoPageFolder(dir, home, about) {
+ fs.mkdirSync(path.join(dir, 'pages'), { recursive: true });
+ fs.writeFileSync(path.join(dir, 'pages', 'home.tsx'), home);
+ fs.writeFileSync(path.join(dir, 'pages', 'about.tsx'), about);
+}
+const shaOf = (baseline, key) => baseline.pages.find((p) => p.key === key).__contentSha;
+
+test('a page the apply sent is recorded as the source it sent, not as the file is when the baseline is written', () => {
+ const dir = tmp();
+ try {
+ const ws = path.join(dir, '.maker-workspace');
+ const identity = { appDir: dir, environment: ENV, appUniqueName: 'new_a' };
+ twoPageFolder(dir, 'export default () => "home as sent";', 'export default () => "about as sent";');
+ const sent = { home: sha256('export default () => "home as sent";'), about: sha256('export default () => "about as sent";') };
+ // The maker saves both pages while the build runs; the baseline is written afterwards.
+ twoPageFolder(dir, 'export default () => "home saved during the build";', 'export default () => "about saved during the build";');
+ writeBaseline(ws, twoPages(), { ...identity, created: { pageSourceShas: sent, pages: { home: A, about: B } } });
+ const recorded = readBaseline(ws, { environment: ENV, appUniqueName: 'new_a' });
+ assert.strictEqual(shaOf(recorded, 'home'), sent.home, 'the record is the source that was sent');
+ assert.strictEqual(shaOf(recorded, 'about'), sent.about);
+ assert.ok(!('__contentSha' in recorded.pages.find((p) => p.key === 'idea')), 'an intent page has no source to record');
+ // Without a measurement — a download, whose files ARE the deployed state, or a caller that measured nothing — the files are hashed as they are.
+ writeBaseline(ws, twoPages(), { ...identity, fromSpec: true });
+ const hashed = readBaseline(ws, { environment: ENV, appUniqueName: 'new_a' });
+ assert.strictEqual(shaOf(hashed, 'home'), sha256('export default () => "home saved during the build";'));
+ writeBaseline(ws, twoPages(), { ...identity, created: { pages: { home: A } } });
+ assert.strictEqual(shaOf(readBaseline(ws, { environment: ENV, appUniqueName: 'new_a' }), 'about'), sha256('export default () => "about saved during the build";'), 'a result with no pageSourceShas is hashed from the files too');
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+// A changed-only run sends only the pages it selects. A page it did not send keeps the record it had — what was last sent is still what is deployed — and, with no earlier record to keep,
+// falls back to the file as it is (as before; no record at all would be no stricter: the next build reads it as "unrecorded" and goes on with a warning).
+test('a page the apply did not send keeps the record it had, and without one is recorded as the file is', () => {
+ const dir = tmp();
+ try {
+ const ws = path.join(dir, '.maker-workspace');
+ const identity = { appDir: dir, environment: ENV, appUniqueName: 'new_a' };
+ twoPageFolder(dir, 'export default () => "home v1";', 'export default () => "about v1";');
+ writeBaseline(ws, twoPages(), identity);
+ const earlier = readBaseline(ws, { environment: ENV, appUniqueName: 'new_a' });
+ twoPageFolder(dir, 'export default () => "home v2, sent";', 'export default () => "about v2, saved but never sent";');
+ const sentHome = sha256('export default () => "home v2, sent";');
+ writeBaseline(ws, twoPages(), { ...identity, created: { pageSourceShas: { home: sentHome } }, previous: earlier });
+ const after = readBaseline(ws, { environment: ENV, appUniqueName: 'new_a' });
+ assert.strictEqual(shaOf(after, 'home'), sentHome, 'the page that was sent: what was sent');
+ assert.strictEqual(shaOf(after, 'about'), sha256('export default () => "about v1";'), 'the page that was not: the record it had, whatever the file says now');
+ writeBaseline(ws, twoPages(), { ...identity, created: { pageSourceShas: { home: sentHome } } });
+ assert.strictEqual(shaOf(readBaseline(ws, { environment: ENV, appUniqueName: 'new_a' }), 'about'), sha256('export default () => "about v2, saved but never sent";'), 'with no earlier record: the file as it is');
+ // A record that was not a hash is not carried over as one: the file as it is.
+ const damaged = { ...earlier, pages: earlier.pages.map((p) => (p.key === 'about' ? { ...p, __contentSha: 42 } : p)) };
+ writeBaseline(ws, twoPages(), { ...identity, created: { pageSourceShas: { home: sentHome } }, previous: damaged });
+ assert.strictEqual(shaOf(readBaseline(ws, { environment: ENV, appUniqueName: 'new_a' }), 'about'), sha256('export default () => "about v2, saved but never sent";'));
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/download-parallel-reads.test.js b/plugins/model-apps/scripts/tests/download-parallel-reads.test.js
new file mode 100644
index 000000000..9bbe65eb7
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/download-parallel-reads.test.js
@@ -0,0 +1,733 @@
+'use strict';
+
+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 BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
+const { readEntityWithDescriptions, readRelationships, runDownload } = require('../download-model-app.js');
+const { currentReadSdk } = require('./helpers/app-membership-sdk.js');
+
+const tempDirs = [];
+test.after(() => {
+ for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true });
+});
+
+// The OS temp directory, never a folder under scripts/: sdk-async-surface.test.js lists every .js file
+// under scripts/ and reads each one later, so a scratch directory removed in between fails that scan.
+function tempDir(prefix) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), `${prefix}`));
+ tempDirs.push(dir);
+ return dir;
+}
+
+function clone(value) {
+ return JSON.parse(JSON.stringify(value));
+}
+
+function sleep(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function label(en, es) {
+ const rows = [{ Label: en, LanguageCode: 1033 }];
+ if (es) rows.push({ Label: es, LanguageCode: 3082 });
+ return {
+ LocalizedLabels: rows,
+ UserLocalizedLabel: rows[0],
+ };
+}
+
+function recursiveFiles(root, relative = '') {
+ const here = path.join(root, relative);
+ const entries = fs.readdirSync(here, { withFileTypes: true });
+ const out = [];
+ for (const entry of entries) {
+ const next = path.join(relative, entry.name);
+ if (entry.isDirectory()) out.push(...recursiveFiles(root, next));
+ else out.push(next.replace(/\\/g, '/'));
+ }
+ return out.sort();
+}
+
+function snapshotDir(root) {
+ const files = recursiveFiles(root);
+ return Object.fromEntries(files.map((file) => [file, fs.readFileSync(path.join(root, file))]));
+}
+
+async function captureStderr(fn) {
+ const original = process.stderr.write;
+ let text = '';
+ process.stderr.write = (chunk, ...rest) => {
+ text += String(chunk);
+ return true;
+ };
+ try {
+ return { result: await fn(), stderr: text };
+ } finally {
+ process.stderr.write = original;
+ }
+}
+
+function makeBarrier(expected) {
+ if (!expected) return { wait: async () => {} };
+ let seen = 0;
+ let release;
+ const gate = new Promise((resolve) => { release = resolve; });
+ return {
+ wait: async () => {
+ seen += 1;
+ if (seen === expected) release();
+ await gate;
+ },
+ };
+}
+
+function makeStageStats() {
+ return {
+ current: 0,
+ max: 0,
+ counts: Object.create(null),
+ completed: [],
+ };
+}
+
+function enterStage(stats, route) {
+ stats.current += 1;
+ stats.max = Math.max(stats.max, stats.current);
+ stats.counts[route] = (stats.counts[route] || 0) + 1;
+ return () => {
+ stats.current -= 1;
+ stats.completed.push(route);
+ };
+}
+
+function normalizedUrl(url) {
+ return decodeURIComponent(String(url || ''));
+}
+
+function matchAuxRoute(url) {
+ const text = normalizedUrl(url);
+ if (/\?\$select=LogicalName,Description,DisplayName,DisplayCollectionName$/.test(text)) return 'entity-labels';
+ if (/\/Attributes\?\$select=LogicalName,Description,DisplayName,IsLogical,AttributeOf,AttributeTypeName$/.test(text)) return 'attribute-labels';
+ if (/MoneyAttributeMetadata\?\$select=LogicalName,IsBaseCurrency$/.test(text)) return 'money';
+ if (/PicklistAttributeMetadata\?\$select=LogicalName&\$expand=OptionSet\(\$select=Name,IsGlobal,Options\)/.test(text)) return 'picklist';
+ if (/MultiSelectPicklistAttributeMetadata\?\$select=LogicalName&\$expand=OptionSet\(\$select=Name,IsGlobal,Options\)/.test(text)) return 'multiselect';
+ return null;
+}
+
+function entityBase(logical) {
+ const prefix = logical.split('_')[0];
+ return {
+ logicalName: logical,
+ schemaName: logical,
+ displayName: logical.replace(/^contoso_/, '').replace(/^\w/, (c) => c.toUpperCase()),
+ primaryNameAttribute: `${prefix}_name`,
+ attributes: [
+ { logicalName: `${prefix}_name`, displayName: 'Name', attributeType: 'String', isCustomAttribute: true },
+ { logicalName: `${prefix}_amount`, displayName: 'Amount', attributeType: 'Money', isCustomAttribute: true },
+ { logicalName: `${prefix}_amount_base`, displayName: 'Amount (Base)', attributeType: 'Money', isCustomAttribute: true },
+ { logicalName: `${prefix}_localchoice`, displayName: 'Local Choice', attributeType: 'Picklist', isCustomAttribute: true },
+ { logicalName: `${prefix}_globalchoice`, displayName: 'Global Choice', attributeType: 'Picklist', isCustomAttribute: true },
+ { logicalName: `${prefix}_multi`, displayName: 'Multi', attributeType: 'MultiSelectPicklist', isCustomAttribute: true },
+ ],
+ relationships: [],
+ };
+}
+
+function auxEntityResponse(logical, route) {
+ const prefix = logical.split('_')[0];
+ switch (route) {
+ case 'entity-labels':
+ return { status: 200, body: { LogicalName: logical, Description: label(`${logical} description`, `${logical} descripción`), DisplayName: label(`${logical} label`, `${logical} etiqueta`), DisplayCollectionName: label(`${logical} rows`, `${logical} filas`) } };
+ case 'attribute-labels':
+ return {
+ status: 200,
+ body: {
+ value: [
+ { LogicalName: `${prefix}_name`, DisplayName: label('Name', 'Nombre'), AttributeTypeName: { Value: 'StringType' } },
+ { LogicalName: `${prefix}_amount`, DisplayName: label('Amount', 'Importe'), AttributeTypeName: { Value: 'MoneyType' } },
+ { LogicalName: `${prefix}_amount_base`, DisplayName: label('Amount (Base)', 'Importe (base)'), AttributeTypeName: { Value: 'MoneyType' } },
+ { LogicalName: `${prefix}_localchoice`, DisplayName: label('Local Choice', 'Elección local'), AttributeTypeName: { Value: 'PicklistType' } },
+ { LogicalName: `${prefix}_globalchoice`, DisplayName: label('Global Choice', 'Elección global'), AttributeTypeName: { Value: 'PicklistType' } },
+ { LogicalName: `${prefix}_multi`, DisplayName: label('Multi', 'Multi'), AttributeTypeName: { Value: 'MultiSelectPicklistType' } },
+ ],
+ },
+ };
+ case 'money':
+ return { status: 200, body: { value: [{ LogicalName: `${prefix}_amount_base`, IsBaseCurrency: true }] } };
+ case 'picklist':
+ return {
+ status: 200,
+ body: {
+ value: [
+ {
+ LogicalName: `${prefix}_localchoice`,
+ OptionSet: {
+ Name: `${logical}_localchoice`,
+ IsGlobal: false,
+ Options: [{ Value: 100000000, Label: label('One', 'Uno') }, { Value: 100000001, Label: label('Two', 'Dos') }],
+ },
+ },
+ {
+ LogicalName: `${prefix}_globalchoice`,
+ OptionSet: {
+ Name: 'shared_stage',
+ IsGlobal: true,
+ Options: [{ Value: 1, Label: label('Draft', 'Borrador') }, { Value: 2, Label: label('Final', 'Final') }],
+ },
+ },
+ ],
+ },
+ };
+ case 'multiselect':
+ return {
+ status: 200,
+ body: {
+ value: [{
+ LogicalName: `${prefix}_multi`,
+ OptionSet: {
+ Name: `${logical}_multi`,
+ IsGlobal: false,
+ Options: [{ Value: 1, Label: label('North', 'Norte') }, { Value: 2, Label: label('South', 'Sur') }],
+ },
+ }],
+ },
+ };
+ default:
+ return { status: 404, body: null };
+ }
+}
+
+async function runEntityReadWithStub(logical, { concurrency, barrier = false, fail = {}, delays = {} } = {}) {
+ const stats = makeStageStats();
+ const gate = makeBarrier(barrier ? 4 : 0);
+ const sdk = {
+ fetchEntityMetadata: async () => entityBase(logical),
+ dataverse: {
+ get: async (url) => {
+ const route = matchAuxRoute(url);
+ if (!route) throw new Error(`unexpected aux url: ${url}`);
+ const leave = enterStage(stats, route);
+ try {
+ if (barrier && ['entity-labels', 'attribute-labels', 'money', 'picklist'].includes(route)) await gate.wait();
+ if (delays[route]) await sleep(delays[route]);
+ const response = fail[route];
+ if (response && response.throw) throw new Error(response.throw);
+ if (response && response.status) return { status: response.status, body: response.body || null };
+ return auxEntityResponse(logical, route);
+ } finally {
+ leave();
+ }
+ },
+ },
+ };
+ const meta = await readEntityWithDescriptions(sdk, logical, { concurrency });
+ return { meta, stats };
+}
+
+function makeRealBundleHttpClient({ auxBarrier = false, delays = {} } = {}) {
+ const stats = makeStageStats();
+ const barrier = makeBarrier(auxBarrier ? 4 : 0);
+ const responseFor = (url) => {
+ const text = normalizedUrl(url);
+ if (/EntityDefinitions\(LogicalName='contoso_alpha'\)\?/.test(text)) {
+ return {
+ status: 200,
+ headers: {},
+ body: {
+ LogicalName: 'contoso_alpha',
+ SchemaName: 'contoso_alpha',
+ DisplayName: label('Alpha', 'Alfa'),
+ Description: label('Alpha table', 'Tabla Alfa'),
+ EntitySetName: 'contoso_alphas',
+ IsCustomEntity: true,
+ PrimaryNameAttribute: 'contoso_name',
+ PrimaryIdAttribute: 'contoso_alphaid',
+ Attributes: [
+ { LogicalName: 'contoso_name', DisplayName: label('Name', 'Nombre'), AttributeType: 'String', AttributeTypeName: { Value: 'StringType' }, IsCustomAttribute: true },
+ { LogicalName: 'contoso_amount', DisplayName: label('Amount', 'Importe'), AttributeType: 'Money', AttributeTypeName: { Value: 'MoneyType' }, IsCustomAttribute: true },
+ { LogicalName: 'contoso_amount_base', DisplayName: label('Amount (Base)', 'Importe (base)'), AttributeType: 'Money', AttributeTypeName: { Value: 'MoneyType' }, IsCustomAttribute: true },
+ { LogicalName: 'contoso_localchoice', DisplayName: label('Local Choice', 'Elección local'), AttributeType: 'Picklist', AttributeTypeName: { Value: 'PicklistType' }, IsCustomAttribute: true },
+ { LogicalName: 'contoso_multi', DisplayName: label('Multi', 'Multi'), AttributeType: 'MultiSelectPicklist', AttributeTypeName: { Value: 'MultiSelectPicklistType' }, IsCustomAttribute: true },
+ ],
+ },
+ };
+ }
+ if (/StringAttributeMetadata/.test(text)) return { status: 200, headers: {}, body: { value: [] } };
+ if (/PicklistAttributeMetadata/.test(text) && /\$select=Options\)/.test(text)) {
+ return {
+ status: 200,
+ headers: {},
+ body: {
+ value: [{
+ LogicalName: 'contoso_localchoice',
+ OptionSet: { Options: [{ Value: 100000000, Label: label('One', 'Uno') }, { Value: 100000001, Label: label('Two', 'Dos') }] },
+ }],
+ },
+ };
+ }
+ if (/MultiSelectPicklistAttributeMetadata/.test(text) && /\$select=Options\)/.test(text)) {
+ return {
+ status: 200,
+ headers: {},
+ body: {
+ value: [{
+ LogicalName: 'contoso_multi',
+ OptionSet: { Options: [{ Value: 1, Label: label('North', 'Norte') }, { Value: 2, Label: label('South', 'Sur') }] },
+ }],
+ },
+ };
+ }
+ if (/LookupAttributeMetadata/.test(text)) return { status: 200, headers: {}, body: { value: [] } };
+ if (/ManyToOneRelationships/.test(text) || /ManyToManyRelationships/.test(text) || /OneToManyRelationships/.test(text)) {
+ return { status: 200, headers: {}, body: { value: [] } };
+ }
+ const route = matchAuxRoute(text);
+ if (route) return { status: 200, headers: {}, body: auxEntityResponse('contoso_alpha', route).body };
+ if (/StateAttributeMetadata/.test(text) || /StatusAttributeMetadata/.test(text)) return { status: 200, headers: {}, body: { value: [] } };
+ throw new Error(`unexpected real-bundle url: ${url}`);
+ };
+ const get = async (url) => {
+ const route = matchAuxRoute(url);
+ const leave = route ? enterStage(stats, route) : () => {};
+ try {
+ if (route && auxBarrier && ['entity-labels', 'attribute-labels', 'money', 'picklist'].includes(route)) await barrier.wait();
+ if (route && delays[route]) await sleep(delays[route]);
+ return responseFor(url);
+ } finally {
+ leave();
+ }
+ };
+ return {
+ stats,
+ httpClient: {
+ get,
+ post: async () => ({ status: 204, headers: {}, body: {} }),
+ patch: async () => ({ status: 204, headers: {}, body: {} }),
+ delete: async () => ({ status: 204, headers: {}, body: {} }),
+ put: async () => ({ status: 204, headers: {}, body: {} }),
+ },
+ };
+}
+
+async function runRealBundleEntityRead(concurrency, { barrier = false } = {}) {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const workspace = tempDir('download-parallel-real-bundle-');
+ const { httpClient, stats } = makeRealBundleHttpClient({ auxBarrier: barrier, delays: { 'entity-labels': 8, 'attribute-labels': 6, money: 7, picklist: 9, multiselect: 5 } });
+ const sdk = createMakerSdk({
+ workspaceStorage: createNodeWorkspaceStorage(workspace),
+ instanceUrl: 'https://contoso.crm.dynamics.com',
+ httpClient,
+ });
+ await sdk.initWorkspace();
+ const meta = await readEntityWithDescriptions(sdk, 'contoso_alpha', { concurrency });
+ return { meta, stats };
+}
+
+function relationshipScenario({ barrier = false, delays = {}, failures = {} } = {}) {
+ const stats = makeStageStats();
+ const gate = makeBarrier(barrier ? 3 : 0);
+ const labelMap = {
+ contoso_alpha_ownerid: { LogicalName: 'contoso_alpha_ownerid', SchemaName: 'contoso_AlphaOwnerId', DisplayName: label('Owner', 'Propietario'), Targets: ['systemuser'] },
+ contoso_beta_alphaid: { LogicalName: 'contoso_beta_alphaid', SchemaName: 'contoso_BetaAlphaId', DisplayName: label('Alpha', 'Alfa'), Targets: ['contoso_alpha'] },
+ contoso_beta_polyid: { LogicalName: 'contoso_beta_polyid', SchemaName: 'contoso_BetaPolyId', DisplayName: label('Poly', 'Poli'), Targets: ['account', 'contact'] },
+ contoso_gamma_customid: { LogicalName: 'contoso_gamma_customid', SchemaName: 'contoso_GammaCustomId', DisplayName: label('Custom', 'Personalizado'), Targets: ['contoso_customparent'] },
+ contoso_gamma_unknownid: { LogicalName: 'contoso_gamma_unknownid', SchemaName: 'contoso_GammaUnknownId', DisplayName: label('Unknown', 'Desconocido'), Targets: ['contoso_unknownparent'] },
+ };
+ const manyToOne = {
+ contoso_alpha: [
+ { IsCustomRelationship: true, SchemaName: 'contoso_systemuser_contoso_alpha', ReferencedEntity: 'systemuser', ReferencingEntity: 'contoso_alpha', ReferencingAttribute: 'contoso_alpha_ownerid' },
+ ],
+ contoso_beta: [
+ { IsCustomRelationship: true, SchemaName: 'contoso_alpha_contoso_beta', ReferencedEntity: 'contoso_alpha', ReferencingEntity: 'contoso_beta', ReferencingAttribute: 'contoso_beta_alphaid' },
+ { IsCustomRelationship: true, SchemaName: 'contoso_beta_account', ReferencedEntity: 'account', ReferencingEntity: 'contoso_beta', ReferencingAttribute: 'contoso_beta_polyid' },
+ { IsCustomRelationship: true, SchemaName: 'contoso_beta_contact', ReferencedEntity: 'contact', ReferencingEntity: 'contoso_beta', ReferencingAttribute: 'contoso_beta_polyid' },
+ ],
+ contoso_gamma: [
+ { IsCustomRelationship: true, SchemaName: 'contoso_customparent_contoso_gamma', ReferencedEntity: 'contoso_customparent', ReferencingEntity: 'contoso_gamma', ReferencingAttribute: 'contoso_gamma_customid' },
+ { IsCustomRelationship: true, SchemaName: 'contoso_unknownparent_contoso_gamma', ReferencedEntity: 'contoso_unknownparent', ReferencingEntity: 'contoso_gamma', ReferencingAttribute: 'contoso_gamma_unknownid' },
+ ],
+ };
+ const manyToMany = {
+ contoso_alpha: [{ IsCustomRelationship: true, SchemaName: 'contoso_alpha_contoso_gamma', Entity1LogicalName: 'contoso_alpha', Entity2LogicalName: 'contoso_gamma' }],
+ contoso_gamma: [{ IsCustomRelationship: true, SchemaName: 'contoso_alpha_contoso_gamma', Entity1LogicalName: 'contoso_alpha', Entity2LogicalName: 'contoso_gamma' }],
+ };
+ const customStates = {
+ systemuser: false,
+ contoso_customparent: true,
+ };
+ const ofEntity = (url) => (url.match(/LogicalName='([^']+)'/) || [])[1];
+ const get = async (url) => {
+ const logical = ofEntity(url);
+ const route = /ManyToOneRelationships/.test(url) ? `${logical}:m2o`
+ : /LookupAttributeMetadata/.test(url) ? `${logical}:lookup`
+ : /ManyToManyRelationships/.test(url) ? `${logical}:m2m`
+ : /\?\$select=IsCustomEntity/.test(url) ? `${logical}:parent`
+ : null;
+ if (!route) throw new Error(`unexpected relationship url: ${url}`);
+ const leave = enterStage(stats, route);
+ try {
+ if (barrier && /:m2o$/.test(route)) await gate.wait();
+ if (delays[route]) await sleep(delays[route]);
+ const fail = failures[route];
+ if (fail && fail.throw) throw new Error(fail.throw);
+ if (fail && fail.status) return { status: fail.status, body: fail.body || null };
+ if (/ManyToOneRelationships/.test(url)) return { status: 200, body: { value: manyToOne[logical] || [] } };
+ if (/LookupAttributeMetadata/.test(url)) {
+ const rows = (manyToOne[logical] || []).map((row) => labelMap[row.ReferencingAttribute]).filter(Boolean);
+ return { status: 200, body: { value: rows } };
+ }
+ if (/ManyToManyRelationships/.test(url)) return { status: 200, body: { value: manyToMany[logical] || [] } };
+ if (logical === 'contoso_unknownparent') return { status: 503, body: null };
+ return { status: 200, body: { IsCustomEntity: customStates[logical] !== false } };
+ } finally {
+ leave();
+ }
+ };
+ return { sdk: { dataverse: { get } }, stats };
+}
+
+async function runRelationshipRead({ concurrency, barrier = false, delays = {}, failures = {} } = {}) {
+ const warnings = [];
+ const { sdk, stats } = relationshipScenario({ barrier, delays, failures });
+ const rel = await readRelationships(sdk, ['contoso_alpha', 'contoso_beta', 'contoso_gamma'], 'contoso', (message) => warnings.push(message), { concurrency });
+ return { rel, warnings, stats };
+}
+
+function richDownloadFixture() {
+ const appId = 'aaaaaaaa-0000-4000-8000-000000000001';
+ const layerId = 'aaaaaaaa-0000-4000-8000-000000000002';
+ const appUnique = 'contoso_downloadapp';
+ const pageOverview = 'bbbbbbbb-0000-4000-8000-000000000001';
+ const pageDetail = 'bbbbbbbb-0000-4000-8000-000000000002';
+ const sitemapXml = `<SiteMap><Area><Group>`
+ + `<SubArea Entity="contoso_alpha" Title="Alpha"/>`
+ + `<SubArea Entity="contoso_beta" Title="Beta"/>`
+ + `<SubArea Entity="contoso_gamma" Title="Gamma"/>`
+ + `<SubArea GenPageId="${pageOverview}" Title="Overview"/>`
+ + `<SubArea GenPageId="${pageDetail}" Title="Detail"/>`
+ + `</Group></Area></SiteMap>`;
+ const auxStats = makeStageStats();
+ const relStats = makeStageStats();
+ const componentRows = [];
+ const app = {
+ name: 'Download App',
+ uniqueName: appUnique,
+ description: '',
+ siteMap: {
+ areas: [{
+ title: 'Main',
+ groups: [{
+ title: 'Data',
+ subAreas: [
+ { type: 'Entity', entity: 'contoso_alpha', title: 'Alpha' },
+ { type: 'Entity', entity: 'contoso_beta', title: 'Beta' },
+ { type: 'Entity', entity: 'contoso_gamma', title: 'Gamma' },
+ { type: 'GenPage', genPageId: pageOverview, title: 'Overview' },
+ { type: 'GenPage', genPageId: pageDetail, title: 'Detail' },
+ ],
+ }],
+ }],
+ },
+ };
+ const baseMeta = {
+ contoso_alpha: {
+ schemaName: 'contoso_alpha',
+ displayName: 'Alpha',
+ primaryNameAttribute: 'contoso_name',
+ attributes: [
+ { logicalName: 'contoso_name', displayName: 'Name', attributeType: 'String', isCustomAttribute: true },
+ { logicalName: 'contoso_amount', displayName: 'Amount', attributeType: 'Money', isCustomAttribute: true },
+ { logicalName: 'contoso_amount_base', displayName: 'Amount (Base)', attributeType: 'Money', isCustomAttribute: true },
+ { logicalName: 'contoso_localchoice', displayName: 'Local Choice', attributeType: 'Picklist', isCustomAttribute: true },
+ ],
+ relationships: [],
+ },
+ contoso_beta: {
+ schemaName: 'contoso_beta',
+ displayName: 'Beta',
+ primaryNameAttribute: 'contoso_name',
+ attributes: [
+ { logicalName: 'contoso_name', displayName: 'Name', attributeType: 'String', isCustomAttribute: true },
+ { logicalName: 'contoso_globalchoice', displayName: 'Global Choice', attributeType: 'Picklist', isCustomAttribute: true },
+ { logicalName: 'contoso_multi', displayName: 'Tags', attributeType: 'MultiSelectPicklist', isCustomAttribute: true },
+ ],
+ relationships: [],
+ },
+ contoso_gamma: {
+ schemaName: 'contoso_gamma',
+ displayName: 'Gamma',
+ primaryNameAttribute: 'contoso_name',
+ attributes: [
+ { logicalName: 'contoso_name', displayName: 'Name', attributeType: 'String', isCustomAttribute: true },
+ { logicalName: 'contoso_problem', displayName: 'Problem', attributeType: 'Picklist', isCustomAttribute: true },
+ ],
+ relationships: [],
+ },
+ };
+ const metadataRows = {
+ contoso_alpha: auxEntityResponse('contoso_alpha', 'attribute-labels').body.value,
+ contoso_beta: auxEntityResponse('contoso_beta', 'attribute-labels').body.value,
+ contoso_gamma: auxEntityResponse('contoso_gamma', 'attribute-labels').body.value,
+ };
+ const ofEntity = (url) => (url.match(/LogicalName='([^']+)'/) || [])[1];
+ const lookupRows = {
+ contoso_alpha: [{ LogicalName: 'contoso_alpha_ownerid', SchemaName: 'contoso_AlphaOwnerId', DisplayName: label('Owner', 'Propietario'), Targets: ['systemuser'] }],
+ contoso_beta: [
+ { LogicalName: 'contoso_beta_alphaid', SchemaName: 'contoso_BetaAlphaId', DisplayName: label('Alpha', 'Alfa'), Targets: ['contoso_alpha'] },
+ { LogicalName: 'contoso_beta_polyid', SchemaName: 'contoso_BetaPolyId', DisplayName: label('Poly', 'Poli'), Targets: ['account', 'contact'] },
+ ],
+ contoso_gamma: [{ LogicalName: 'contoso_gamma_unknownid', SchemaName: 'contoso_GammaUnknownId', DisplayName: label('Unknown', 'Desconocido'), Targets: ['contoso_unknownparent'] }],
+ };
+ const manyToOne = {
+ contoso_alpha: [{ IsCustomRelationship: true, SchemaName: 'contoso_systemuser_contoso_alpha', ReferencedEntity: 'systemuser', ReferencingEntity: 'contoso_alpha', ReferencingAttribute: 'contoso_alpha_ownerid' }],
+ contoso_beta: [
+ { IsCustomRelationship: true, SchemaName: 'contoso_alpha_contoso_beta', ReferencedEntity: 'contoso_alpha', ReferencingEntity: 'contoso_beta', ReferencingAttribute: 'contoso_beta_alphaid' },
+ { IsCustomRelationship: true, SchemaName: 'contoso_beta_account', ReferencedEntity: 'account', ReferencingEntity: 'contoso_beta', ReferencingAttribute: 'contoso_beta_polyid' },
+ { IsCustomRelationship: true, SchemaName: 'contoso_beta_contact', ReferencedEntity: 'contact', ReferencingEntity: 'contoso_beta', ReferencingAttribute: 'contoso_beta_polyid' },
+ ],
+ contoso_gamma: [{ IsCustomRelationship: true, SchemaName: 'contoso_unknownparent_contoso_gamma', ReferencedEntity: 'contoso_unknownparent', ReferencingEntity: 'contoso_gamma', ReferencingAttribute: 'contoso_gamma_unknownid' }],
+ };
+ const manyToMany = {
+ contoso_alpha: [{ IsCustomRelationship: true, SchemaName: 'contoso_alpha_contoso_gamma', Entity1LogicalName: 'contoso_alpha', Entity2LogicalName: 'contoso_gamma' }],
+ contoso_gamma: [{ IsCustomRelationship: true, SchemaName: 'contoso_alpha_contoso_gamma', Entity1LogicalName: 'contoso_alpha', Entity2LogicalName: 'contoso_gamma' }],
+ };
+ const delays = {
+ 'contoso_alpha:entity-labels': 25,
+ 'contoso_alpha:attribute-labels': 20,
+ 'contoso_alpha:money': 15,
+ 'contoso_alpha:picklist': 12,
+ 'contoso_alpha:multiselect': 10,
+ 'contoso_beta:entity-labels': 12,
+ 'contoso_beta:attribute-labels': 10,
+ 'contoso_beta:money': 6,
+ 'contoso_beta:picklist': 14,
+ 'contoso_beta:multiselect': 8,
+ 'contoso_gamma:entity-labels': 5,
+ 'contoso_gamma:attribute-labels': 7,
+ 'contoso_gamma:money': 4,
+ 'contoso_gamma:picklist': 6,
+ 'contoso_gamma:multiselect': 3,
+ 'contoso_alpha:m2o': 18,
+ 'contoso_beta:m2o': 7,
+ 'contoso_gamma:m2o': 4,
+ 'contoso_alpha:lookup': 6,
+ 'contoso_beta:lookup': 5,
+ 'contoso_gamma:lookup': 3,
+ 'contoso_alpha:m2m': 9,
+ 'contoso_beta:m2m': 8,
+ 'contoso_gamma:m2m': 6,
+ };
+ const sdk = currentReadSdk({
+ fetchArtifact: async () => clone(app),
+ fetchEntityMetadata: async (logical) => clone(baseMeta[logical]),
+ retrieveSetting: async () => null,
+ queryRecords: async (set, opts = {}) => {
+ const filter = opts.filter || '';
+ if (set === 'appmodule') return [{ appmoduleid: appId, appmoduleidunique: layerId, uniquename: appUnique }];
+ if (set === 'appmodulecomponent') {
+ if (filter.includes('componenttype eq 62')) return [{ objectid: 'cccccccc-0000-4000-8000-000000000001', componenttype: 62 }];
+ return componentRows;
+ }
+ if (set === 'sitemap') return [{ sitemapxml: sitemapXml }];
+ if (set === 'webresource') return [];
+ if (set === 'systemform' || set === 'savedquery' || set === 'savedqueryvisualization' || set === 'solutioncomponent' || set === 'solution' || set === 'workflow') return [];
+ return [];
+ },
+ dataverse: {
+ get: async (url) => {
+ const logical = ofEntity(url);
+ const auxRoute = matchAuxRoute(url);
+ if (auxRoute) {
+ const leave = enterStage(auxStats, auxRoute);
+ try {
+ await sleep(delays[`${logical}:${auxRoute}`] || 1);
+ if (logical === 'contoso_alpha' && auxRoute === 'entity-labels') return { status: 503, body: null };
+ if (logical === 'contoso_gamma' && auxRoute === 'attribute-labels') throw new Error('gamma labels offline');
+ if (logical === 'contoso_gamma' && (auxRoute === 'picklist' || auxRoute === 'multiselect')) return { status: 503, body: null };
+ if (auxRoute === 'entity-labels') return { status: 200, body: auxEntityResponse(logical, auxRoute).body };
+ if (auxRoute === 'attribute-labels') return { status: 200, body: { value: metadataRows[logical] || [] } };
+ if (auxRoute === 'money') return { status: 200, body: auxEntityResponse(logical, auxRoute).body };
+ if (auxRoute === 'picklist') {
+ if (logical === 'contoso_beta') {
+ return {
+ status: 200,
+ body: {
+ value: [{
+ LogicalName: 'contoso_globalchoice',
+ OptionSet: { Name: 'shared_stage', IsGlobal: true, Options: [{ Value: 1, Label: label('Draft', 'Borrador') }, { Value: 2, Label: label('Final', 'Final') }] },
+ }],
+ },
+ };
+ }
+ return { status: 200, body: auxEntityResponse(logical, auxRoute).body };
+ }
+ if (auxRoute === 'multiselect') {
+ if (logical === 'contoso_beta') {
+ return {
+ status: 200,
+ body: {
+ value: [{
+ LogicalName: 'contoso_multi',
+ OptionSet: { Name: 'contoso_beta_multi', IsGlobal: false, Options: [{ Value: 1, Label: label('North', 'Norte') }, { Value: 2, Label: label('South', 'Sur') }] },
+ }],
+ },
+ };
+ }
+ return { status: 200, body: { value: [] } };
+ }
+ throw new Error(`unhandled aux route ${auxRoute}`);
+ } finally {
+ leave();
+ }
+ }
+ if (/ManyToOneRelationships/.test(url) || /LookupAttributeMetadata/.test(url) || /ManyToManyRelationships/.test(url) || /\?\$select=IsCustomEntity/.test(url)) {
+ const route = /ManyToOneRelationships/.test(url) ? 'm2o'
+ : /LookupAttributeMetadata/.test(url) ? 'lookup'
+ : /ManyToManyRelationships/.test(url) ? 'm2m'
+ : 'parent';
+ const leave = enterStage(relStats, `${logical}:${route}`);
+ try {
+ await sleep(delays[`${logical}:${route}`] || 1);
+ if (route === 'm2o') return { status: 200, body: { value: manyToOne[logical] || [] } };
+ if (route === 'lookup') return { status: 200, body: { value: lookupRows[logical] || [] } };
+ if (route === 'm2m') return { status: 200, body: { value: manyToMany[logical] || [] } };
+ if (logical === 'contoso_unknownparent') return { status: 503, body: null };
+ if (logical === 'systemuser' || logical === 'account' || logical === 'contact') return { status: 200, body: { IsCustomEntity: false } };
+ return { status: 200, body: { IsCustomEntity: true } };
+ } finally {
+ leave();
+ }
+ }
+ if (/EntityDefinitions\([0-9a-fA-F-]+\)\?\$select=LogicalName,IsCustomEntity/.test(url)) {
+ return { status: 200, body: { LogicalName: 'contoso_alpha', IsCustomEntity: true } };
+ }
+ if (/\/systemforms\?\$select=formid,name,formactivationstate/.test(url)) {
+ return { status: 200, body: { value: [] } };
+ }
+ if (/\/GlobalOptionSetDefinitions\?\$select=Name,Description,IsManaged,MetadataId/.test(url)) {
+ return { status: 200, body: { value: [] } };
+ }
+ throw new Error(`unexpected fixture url: ${url}`);
+ },
+ },
+ }, { appId, layerId, sitemapXml });
+ const genpageCli = {
+ enumerateEnv: async () => ({
+ ok: true,
+ ids: [pageOverview.toLowerCase(), pageDetail.toLowerCase()],
+ pages: [{ pageId: pageOverview, name: 'Overview' }, { pageId: pageDetail, name: 'Detail' }],
+ }),
+ download: async ({ outputDir, pageIds }) => {
+ for (const pageId of pageIds) {
+ const pageDir = path.join(outputDir, pageId);
+ fs.mkdirSync(pageDir, { recursive: true });
+ fs.writeFileSync(path.join(pageDir, 'page.tsx'),
+ pageId === pageOverview
+ ? 'export default function Overview() { return "overview"; }\n'
+ : 'export default function Detail() { return "detail"; }\n',
+ 'utf8');
+ fs.writeFileSync(path.join(pageDir, 'config.json'),
+ JSON.stringify({ dataSources: pageId === pageOverview ? ['contoso_alpha'] : ['contoso_beta'] }),
+ 'utf8');
+ }
+ return true;
+ },
+ };
+ return { sdk, genpageCli, appId, appUnique, auxStats, relStats };
+}
+
+async function runDownloadSnapshot(concurrency) {
+ const outDir = tempDir(`download-parallel-${concurrency}-`);
+ const fixture = richDownloadFixture();
+ const { result, stderr } = await captureStderr(() => runDownload({
+ sdk: fixture.sdk,
+ genpageCli: fixture.genpageCli,
+ outDir,
+ appId: fixture.appId,
+ appUnique: fixture.appUnique,
+ concurrency,
+ }));
+ assert.ok(result.ok, JSON.stringify(result));
+ fs.writeFileSync(path.join(outDir, 'app-spec.json'), JSON.stringify(result.spec, null, 2), 'utf8');
+ return { outDir, stderr, result, auxStats: fixture.auxStats, relStats: fixture.relStats };
+}
+
+test('real bundle overlaps one table\'s auxiliary metadata reads with the same bounded GET count', async () => {
+ const sequential = await runRealBundleEntityRead(1);
+ const parallel = await runRealBundleEntityRead(undefined);
+
+ assert.deepStrictEqual(parallel.meta, sequential.meta, 'parallel aux reads must reconstruct the same metadata');
+ assert.strictEqual(sequential.stats.max, 1, 'concurrency:1 keeps the aux stage sequential');
+ assert.ok(parallel.stats.max > 1, `default concurrency must overlap aux reads (max ${parallel.stats.max})`);
+ assert.ok(parallel.stats.max <= 4, `aux overlap stays bounded at 4 (max ${parallel.stats.max})`);
+ for (const route of ['entity-labels', 'attribute-labels', 'money', 'picklist', 'multiselect']) {
+ assert.strictEqual(parallel.stats.counts[route], sequential.stats.counts[route], `GET count stable for ${route}`);
+ }
+ for (const route of ['entity-labels', 'attribute-labels', 'money', 'picklist']) {
+ assert.ok(parallel.stats.counts[route] >= 1, `${route} issued at least once`);
+ }
+});
+
+test('runDownload keeps app-spec, pages, and warnings byte-identical while overlapping table and relationship reads', async () => {
+ const sequential = await runDownloadSnapshot(1);
+ const parallel = await runDownloadSnapshot(undefined);
+
+ assert.strictEqual(sequential.auxStats.max, 1, 'concurrency:1 keeps table aux reads sequential');
+ assert.ok(parallel.auxStats.max > 1, `default concurrency overlaps table aux reads (max ${parallel.auxStats.max})`);
+ assert.ok(parallel.auxStats.max <= 4, `table aux reads stay bounded at 4 (max ${parallel.auxStats.max})`);
+ assert.strictEqual(sequential.relStats.max, 1, 'concurrency:1 keeps per-table relationship chains sequential');
+ assert.ok(parallel.relStats.max > 1, `default concurrency overlaps relationship table reads (max ${parallel.relStats.max})`);
+ assert.ok(parallel.relStats.max <= 4, `relationship overlap stays bounded at 4 (max ${parallel.relStats.max})`);
+ assert.deepStrictEqual(parallel.auxStats.counts, sequential.auxStats.counts, 'table aux GET count must stay unchanged');
+ assert.deepStrictEqual(parallel.relStats.counts, sequential.relStats.counts, 'relationship GET count must stay unchanged');
+ assert.strictEqual(parallel.stderr, sequential.stderr, 'warning transcript must stay byte-identical');
+ assert.deepStrictEqual(snapshotDir(parallel.outDir), snapshotDir(sequential.outDir), 'downloaded files must stay byte-identical');
+ assert.deepStrictEqual(parallel.result.spec, sequential.result.spec, 'spec object must stay identical too');
+});
+
+test('failure parity stays identical when later tables finish first in time', async () => {
+ const attrFirst = await runEntityReadWithStub('contoso_alpha', {
+ concurrency: undefined,
+ delays: { 'entity-labels': 20, 'attribute-labels': 1, money: 8, picklist: 7, multiselect: 6 },
+ fail: {
+ 'entity-labels': { status: 503 },
+ 'attribute-labels': { throw: 'attribute labels failed first' },
+ money: { throw: 'money timed out' },
+ picklist: { status: 503 },
+ },
+ });
+ const attrSequential = await runEntityReadWithStub('contoso_alpha', {
+ concurrency: 1,
+ fail: {
+ 'entity-labels': { status: 503 },
+ 'attribute-labels': { throw: 'attribute labels failed first' },
+ money: { throw: 'money timed out' },
+ picklist: { status: 503 },
+ },
+ });
+ assert.ok(attrFirst.stats.max > 1, `default concurrency must overlap aux failure reads too (max ${attrFirst.stats.max})`);
+ assert.deepStrictEqual(attrFirst.meta, attrSequential.meta, 'aux read failures must preserve sequential metadata + precedence');
+ assert.strictEqual(attrFirst.meta.labelReadFailed, 'HTTP 503', 'the first sequential label failure keeps precedence even if another fails earlier in time');
+ assert.strictEqual(attrFirst.meta.optionSetReadFailed, 'HTTP 503');
+
+ for (const [name, failures] of [
+ ['many-to-one non-2xx', { 'contoso_beta:m2o': { status: 503 } }],
+ ['lookup throw', { 'contoso_beta:lookup': { throw: 'lookup labels unavailable' } }],
+ ['many-to-many throw', { 'contoso_gamma:m2m': { throw: 'm2m down' } }],
+ ['parent unreadable', {}],
+ ]) {
+ const seq = await runRelationshipRead({ concurrency: 1, failures });
+ const par = await runRelationshipRead({
+ concurrency: undefined,
+ delays: { 'contoso_alpha:m2o': 18, 'contoso_beta:m2o': 4, 'contoso_gamma:m2o': 2 },
+ failures,
+ });
+ assert.ok(par.stats.max > 1, `${name}: default concurrency must overlap relationship table reads (max ${par.stats.max})`);
+ assert.deepStrictEqual(par.rel, seq.rel, `${name}: relationship output must match sequential`);
+ assert.deepStrictEqual(par.warnings, seq.warnings, `${name}: warning order + wording must match sequential`);
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.js b/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.js
index cfd13e571..5de046e8d 100644
--- a/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.js
+++ b/plugins/model-apps/scripts/tests/download-rebuild-teardown.test.js
@@ -80,6 +80,12 @@ function recordingLifecycleSdk({ systemOnly = false } = {}) {
] }), 4);
resource('contoso_foreign.svg', 11, '<svg/>', 5);
const appById = (id) => [...state.apps.values()].find((a) => a.id === id);
+ const sitemapXml = (app) => {
+ const entries = app.siteMap.areas.flatMap((a) => a.groups.flatMap((g) => g.subAreas || []));
+ return `<SiteMap><Area><Group>${entries.map((s) =>
+ s.genPageId ? `<SubArea GenPageId="${s.genPageId}"/>` : s.entity ? `<SubArea Entity="${s.entity}"/>`
+ : s.url ? `<SubArea Url="${s.url}"/>` : '').join('')}</Group></Area></SiteMap>`;
+ };
sdk.initWorkspace = async () => {};
sdk.listArtifacts = async () => [...state.apps.values()].map((a) => ({ id: a.id, isDirty: false }));
sdk.findArtifact = async (kind, identity) => kind === 'app' ? state.apps.get(identity.uniqueName)?.id || null : null;
@@ -107,6 +113,15 @@ function recordingLifecycleSdk({ systemOnly = false } = {}) {
}] : [] } };
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 is
+ // its published one.
+ if (url.startsWith('/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()')) {
+ return { status: 200, body: { value: [...state.apps.values()].map((a) => ({ sitemapid: a.sitemapId, sitemapxml: sitemapXml(a), componentstate: 0 })) } };
+ }
+ // The current layer of every app, read once to find the apps that were never published. Every app here is published, so each has its one published row.
+ if (url.startsWith('/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()')) {
+ return { status: 200, body: { value: [...state.apps.values()].map((a) => ({ appmoduleid: a.id, appmoduleidunique: a.lookup, uniquename: a.uniquename, componentstate: 0 })) } };
+ }
assert.ok(state.tables.has(logical), `only declared table metadata may be read: ${url}`);
return { status: 200, body: { LogicalName: logical, EntitySetName: `${logical}s` } };
} };
@@ -125,10 +140,7 @@ function recordingLifecycleSdk({ systemOnly = false } = {}) {
if (set === 'sitemap') {
const app = [...state.apps.values()].find((a) => filter === `sitemapid eq ${a.sitemapId}` || filter === `sitemapnameunique eq '${a.uniquename}'`);
if (!app) return [];
- const entries = app.siteMap.areas.flatMap((a) => a.groups.flatMap((g) => g.subAreas || []));
- return [{ sitemapid: app.sitemapId, sitemapxml: `<SiteMap><Area><Group>${entries.map((s) =>
- s.genPageId ? `<SubArea GenPageId="${s.genPageId}"/>` : s.entity ? `<SubArea Entity="${s.entity}"/>`
- : s.url ? `<SubArea Url="${s.url}"/>` : '').join('')}</Group></Area></SiteMap>` }];
+ return [{ sitemapid: app.sitemapId, sitemapxml: sitemapXml(app) }];
}
if (set === 'solutioncomponent') {
if (!filter.startsWith('objectid eq ')) return [];
diff --git a/plugins/model-apps/scripts/tests/form-create-recovery-real-bundle.test.js b/plugins/model-apps/scripts/tests/form-create-recovery-real-bundle.test.js
new file mode 100644
index 000000000..7203f8a65
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/form-create-recovery-real-bundle.test.js
@@ -0,0 +1,219 @@
+'use strict';
+// A Main form whose create COMMITTED but whose answer was lost converges instead of halting the build.
+//
+// How the situation arises in this plugin: the HTTP client (lib/sdk-http-client.js) re-sends a POST that got no
+// answer — a dropped connection, or the 5-minute write timeout — and the SDK mints a form's id itself, so the
+// re-send meets the row the first attempt already created and Dataverse answers 412 ("a record with matching
+// key values already exists"). Without `createRecovery` the SDK reports that as ARTIFACT_ALREADY_EXISTS, and
+// the build halts asking for a manual workspace reset. With `createRecovery: 'adoptExact'` the SDK reads the
+// row and, only when it is exactly what the retry sent, adopts it locally and writes nothing.
+//
+// These tests drive the REAL bundle through the plugin's REAL HTTP client over a fake Dataverse that models
+// the lost answer at the transport. The SDK is built from the options the build's own `makeSdk` passes (captured
+// below), so a build that stops asking for the recovery fails here, rather than a test constructing its own SDK
+// and proving only the bundle.
+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 { createAzHttpClient } = require('../lib/sdk-http-client.js');
+const { pushFailed, requireSuccessfulPush, reportPartialPush } = require('../lib/entity-provision.js');
+
+const scriptsDir = path.join(__dirname, '..');
+const BUNDLE = path.join(scriptsDir, 'vendor', 'cds-maker-sdk.cjs');
+const ENV = 'https://contoso.crm.dynamics.com';
+const SENTINEL = new Error('stop after construction');
+
+const tempDirs = [];
+test.after(() => { for (const d of tempDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+// The two option bags build-model-app.js's makeSdk hands `createMakerSdk` — [header-carrying `sdk`, `provisionSdk`] —
+// captured by running its main() against a bundle that records them and then stops.
+async function buildOptions() {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'recovery-app-'));
+ tempDirs.push(dir);
+ 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 captured = [];
+ const cli = loadCli(path.join(scriptsDir, 'build-model-app.js'), {
+ argv: ['--env', ENV, '--spec', `@${path.join(dir, 'app-spec.json')}`, '--no-live-plan'],
+ requires: {
+ './lib/dataverse-auth.js': authCli.exports,
+ './lib/sdk-http-client.js': { createAzHttpClient: () => ({}), SQL_DEADLOCK_VICTIM: /Sql Number: 1205/ },
+ './vendor/cds-maker-sdk.cjs': {
+ createNodeWorkspaceStorage: (d) => ({ dir: d }),
+ createMakerSdk: (options) => { captured.push(options); return { initWorkspace: async () => { throw SENTINEL; } }; },
+ },
+ },
+ });
+ await assert.rejects(cli.main(), (err) => err === SENTINEL);
+ assert.strictEqual(captured.length, 2, 'the build constructs the header-carrying SDK and the workspace-owning one');
+ return { sdk: captured[0], provision: captured[1] };
+}
+
+// A Dataverse that holds `systemforms` rows and loses the answer to the first create it receives. `answerForDuplicate`
+// is what it says when a create names an id that exists: 412 0x80040237 (measured on production builds) or 404
+// 0x80040217 (measured on a test build, where the SDK never adopts).
+function fakeOrg({ loseFirstAnswer = true, answerForDuplicate = 412, editAfterCommit } = {}) {
+ const rows = new Map();
+ const requests = [];
+ let lost = false;
+ const json = (statusCode, body, headers = {}) => ({ statusCode, headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body) });
+ async function request({ url, method, body }) {
+ const u = new URL(url);
+ requests.push({ method, path: decodeURIComponent(u.pathname + u.search) });
+ if (method === 'POST' && /\/systemforms$/.test(u.pathname)) {
+ const sent = JSON.parse(body);
+ if (rows.has(sent.formid)) {
+ return answerForDuplicate === 404
+ ? json(404, { error: { code: '0x80040217', message: `Entity 'systemform' With Id = ${sent.formid} Does Not Exist` } })
+ : json(412, { error: { code: '0x80040237', message: 'A record with matching key values already exists.' } });
+ }
+ const row = { formid: sent.formid, name: sent.name, objecttypecode: sent.objecttypecode, type: sent.type, formxml: sent.formxml, formpresentation: 0, formactivationstate: 1 };
+ rows.set(sent.formid, row);
+ if (editAfterCommit) editAfterCommit(row);
+ if (loseFirstAnswer && !lost) {
+ lost = true;
+ // No status line ever arrives: the transport reports the request failed (makeRequest's `{ error }`).
+ return { error: 'socket hang up' };
+ }
+ return { statusCode: 204, headers: { 'odata-entityid': `${ENV}/api/data/v9.0/systemforms(${sent.formid})` }, body: '' };
+ }
+ const read = /systemforms\(([0-9a-f-]+)\)\/Microsoft\.Dynamics\.CRM\.RetrieveUnpublished/i.exec(u.pathname + u.search);
+ if (method === 'GET' && read && rows.has(read[1])) {
+ return json(200, { ...rows.get(read[1]), '@odata.etag': 'W/"1001"' }, { etag: 'W/"1001"' });
+ }
+ return json(200, { value: [] });
+ }
+ return { request, requests, rows, writes: () => requests.filter((r) => r.method !== 'GET') };
+}
+
+// A real SDK with the build's own options, over the plugin's own HTTP client talking to `org`.
+async function buildSdk(options, org, { withRecovery = true } = {}) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'recovery-ws-'));
+ tempDirs.push(dir);
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const client = createAzHttpClient(ENV, { getToken: () => 'token', request: org.request, sleep: async () => {} });
+ const { createRecovery, ...rest } = options;
+ const sdk = createMakerSdk({ ...rest, ...(withRecovery && createRecovery ? { createRecovery } : {}), workspaceStorage: createNodeWorkspaceStorage(dir), httpClient: client });
+ await sdk.initWorkspace();
+ return sdk;
+}
+
+const mainForm = { name: 'Account form', entityLogicalName: 'account', formType: 'Main', status: 'Active' };
+
+// --- the option, as the build passes it ---------------------------------------------------------------
+
+test('the build asks for the recovery on the SDK that creates forms, and on no other', async () => {
+ const { sdk, provision } = await buildOptions();
+ assert.strictEqual(provision.createRecovery, 'adoptExact', 'the workspace-owning SDK pushes every form');
+ assert.strictEqual(sdk.createRecovery, undefined, 'the header-carrying SDK creates no artifact');
+ // With a solution configured the SDK would also have to PROVE membership before adopting, and the plugin adds
+ // a form to its solution after the push — a create lost without the header is never a member (the SDK measured
+ // this). This SDK is header-less on purpose, so the recovery is judged on the row alone.
+ assert.strictEqual(provision.solutionUniqueName, undefined);
+});
+
+// --- the convergence ----------------------------------------------------------------------------------
+
+test('a lost-answer create is adopted: the retry\u2019s 412 is read, judged exact, and nothing is written again', async () => {
+ const { provision } = await buildOptions();
+ const org = fakeOrg();
+ const sdk = await buildSdk(provision, org);
+ const art = await sdk.createArtifact('form', mainForm);
+
+ const result = await sdk.pushArtifact('form', art.id);
+
+ assert.strictEqual(result.adoptedExisting, true);
+ assert.strictEqual(result.saved, false, 'nothing was written by this attempt — the SDK says so with saved:false');
+ assert.strictEqual(pushFailed(result), false, 'an adoption is not a failure, whatever its saved flag says');
+ const warnings = [];
+ assert.strictEqual(requireSuccessfulPush(result, 'form Account form', (m) => warnings.push(m)), result, 'the build goes on');
+ assert.strictEqual(warnings.length, 1, 'and says what happened');
+ assert.match(warnings[0], /form Account form/);
+ assert.match(warnings[0], /already created.*adopted|adopted.*already created/i);
+
+ const creates = org.requests.filter((r) => r.method === 'POST');
+ assert.strictEqual(creates.length, 2, 'the lost create and the client\u2019s one re-send — no third write from the recovery');
+ assert.deepStrictEqual(org.writes().map((r) => r.method), ['POST', 'POST'], 'the recovery issues no PATCH, DELETE or publish');
+ assert.strictEqual(org.requests.filter((r) => /RetrieveUnpublished/.test(r.path)).length, 1, 'one exact read by id decided it');
+ assert.strictEqual(org.rows.size, 1, 'and no duplicate form exists');
+});
+
+test('without the recovery the same lost answer halts the build, as it did before', async () => {
+ // The control: it is the option that makes the difference, not the fake.
+ const { provision } = await buildOptions();
+ const org = fakeOrg();
+ const sdk = await buildSdk(provision, org, { withRecovery: false });
+ const art = await sdk.createArtifact('form', mainForm);
+ const result = await sdk.pushArtifact('form', art.id);
+ assert.strictEqual(result.error && result.error.code, 'ARTIFACT_ALREADY_EXISTS');
+ assert.strictEqual(pushFailed(result), true);
+ assert.throws(() => requireSuccessfulPush(result, 'form Account form'), (err) => err.code === 'already-exists');
+});
+
+// --- the refusals, exactly as before -----------------------------------------------------------------
+
+test('a row that is not what was sent is refused: the build still halts, and says why it was not adopted', async () => {
+ const { provision } = await buildOptions();
+ // Someone edited the form between the commit and the retry.
+ const org = fakeOrg({ editAfterCommit: (row) => { row.formxml += '<!-- edited elsewhere -->'; } });
+ const sdk = await buildSdk(provision, org);
+ const art = await sdk.createArtifact('form', mainForm);
+ const result = await sdk.pushArtifact('form', art.id);
+
+ assert.strictEqual(result.adoptedExisting, undefined);
+ assert.strictEqual(pushFailed(result), true);
+ assert.throws(() => requireSuccessfulPush(result, 'form Account form'), (err) => {
+ assert.strictEqual(err.code, 'already-exists');
+ assert.match(err.message, /did not adopt it: the existing row is not what this create wrote \(it differs in formxml\)/);
+ assert.match(err.message, /delete everything in it except last-applied\.json/, 'the plugin\u2019s own workspace-reset advice is unchanged');
+ return true;
+ });
+ assert.deepStrictEqual(org.writes().map((r) => r.method), ['POST', 'POST']);
+});
+
+test('the build that answers a replayed create with 404 never adopts — the halt is the same', async () => {
+ const { provision } = await buildOptions();
+ const org = fakeOrg({ answerForDuplicate: 404 });
+ const sdk = await buildSdk(provision, org);
+ const art = await sdk.createArtifact('form', mainForm);
+ const result = await sdk.pushArtifact('form', art.id);
+ assert.strictEqual(result.error && result.error.code, 'ARTIFACT_ALREADY_EXISTS');
+ assert.throws(() => requireSuccessfulPush(result, 'form Account form'), (err) => err.code === 'already-exists');
+});
+
+test('only a Main form is adopted: a Quick Create form that lost its answer halts as before', async () => {
+ const { provision } = await buildOptions();
+ const org = fakeOrg();
+ const sdk = await buildSdk(provision, org);
+ const art = await sdk.createArtifact('form', { ...mainForm, name: 'Account quick create', formType: 'QuickCreate' });
+ const result = await sdk.pushArtifact('form', art.id);
+ assert.strictEqual(result.adoptedExisting, undefined);
+ assert.throws(() => requireSuccessfulPush(result, 'form Account quick create'), (err) => err.code === 'already-exists' && /only a Main form is adopted/.test(err.message));
+});
+
+// --- the plugin's reading of a push result ------------------------------------------------------------
+
+test('pushFailed: an adoption is the one saved:false that is not a failure', () => {
+ assert.strictEqual(pushFailed({ saved: false, adoptedExisting: true }), false);
+ // Everything that WAS a failure still is — including a result that claims adoption but carries an error.
+ assert.strictEqual(pushFailed({ saved: false, error: { code: 'VERSION_CONFLICT' } }), true);
+ assert.strictEqual(pushFailed({ saved: false }), true);
+ assert.strictEqual(pushFailed({ success: false }), true);
+ assert.strictEqual(pushFailed({ saved: false, adoptedExisting: true, error: new Error('x') }), true);
+ assert.strictEqual(pushFailed({ saved: false, adoptedExisting: 'true' }), true, 'only the boolean the SDK sets counts');
+ assert.strictEqual(pushFailed({ saved: true }), false);
+ assert.strictEqual(pushFailed(undefined), false);
+});
+
+test('reportPartialPush tells the operator an adoption happened, and stays silent for an ordinary push', () => {
+ const said = [];
+ reportPartialPush({ saved: false, adoptedExisting: true }, 'form Contact', (m) => said.push(m));
+ assert.strictEqual(said.length, 1);
+ assert.match(said[0], /form Contact/);
+ reportPartialPush({ saved: true, publish: { kind: 'notRequested' } }, 'form Contact', (m) => said.push(m));
+ assert.strictEqual(said.length, 1);
+});
diff --git a/plugins/model-apps/scripts/tests/form-field-options.test.js b/plugins/model-apps/scripts/tests/form-field-options.test.js
index 0776a872c..c862b3a03 100644
--- a/plugins/model-apps/scripts/tests/form-field-options.test.js
+++ b/plugins/model-apps/scripts/tests/form-field-options.test.js
@@ -26,6 +26,7 @@ const {
fieldCellIntent,
formFieldLogicals,
findFieldCellLocation,
+ findFieldCellLocations,
normalizeFieldEntry,
fieldOptionsMap,
NON_FORM_RENDERABLE_TYPES,
@@ -374,6 +375,29 @@ test('findFieldCellLocation returns the containing arrays, indices, and the SECT
assert.strictEqual(findFieldCellLocation(form, 'zzz'), null);
});
+test('findFieldCellLocations returns EVERY cell of a field the form holds more than once, in form order — and findFieldCellLocation the first', () => {
+ const quickView = { fieldName: 'b', classId: '{5C5600E0-1D6E-4205-A272-BE80DA87FD42}' };
+ const form = {
+ tabs: [
+ { columns: [{ sections: [{ rows: [
+ { cells: [{ control: { fieldName: 'a' } }, { control: { fieldName: 'B' } }] },
+ { cells: [{ control: quickView }] },
+ ] }, { rows: [{ cells: [{ control: { fieldName: 'b' } }] }] }] }] },
+ { columns: [{ sections: [{ rows: [{ cells: [{ control: { fieldName: 'b' } }] }] }] }] },
+ ],
+ };
+ const all = findFieldCellLocations(form, 'b');
+ assert.deepStrictEqual(all.map((l) => l.cellPointer), [
+ '/tabs/0/columns/0/sections/0/rows/0/cells/1',
+ '/tabs/0/columns/0/sections/1/rows/0/cells/0',
+ '/tabs/1/columns/0/sections/0/rows/0/cells/0',
+ ], 'each placement, across sections and tabs, matched case-insensitively — and never the quick-view control that carries the field as its lookup');
+ assert.deepStrictEqual(all[0], findFieldCellLocation(form, 'b'), 'the first is the one findFieldCellLocation gives');
+ assert.deepStrictEqual(findFieldCellLocations(form, 'a').length, 1);
+ assert.deepStrictEqual(findFieldCellLocations(form, 'zzz'), []);
+ assert.deepStrictEqual(findFieldCellLocations({}, 'b'), [], 'a form with no tabs has no cells');
+});
+
// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------
diff --git a/plugins/model-apps/scripts/tests/form-kind-real-bundle.test.js b/plugins/model-apps/scripts/tests/form-kind-real-bundle.test.js
new file mode 100644
index 000000000..8efb47ec4
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/form-kind-real-bundle.test.js
@@ -0,0 +1,97 @@
+'use strict';
+// REAL BUNDLE: a form and a dashboard are each read and written only as their own kind. `systemforms` holds every
+// form kind and every dashboard, and the SDK used to project ANY row a by-id read named through the grammar the caller
+// asked for — a dashboard became a "form", a form a "dashboard" — and a push wrote the re-serialized document back. It
+// now decodes the row's `type` from the read it already makes and refuses (SYSTEMFORM_KIND_MISMATCH) before it
+// projects or writes, and a form push refuses to change the form's type (FORM_TYPE_IMMUTABLE: the platform ignores a
+// type change, so the push would report a change that never happened).
+//
+// The plugin addresses forms and dashboards by id in three places a wrong id can reach: the forms phase (a form it
+// resolved or created), the security-roles/order step (form-order-real-bundle.test.js) and a download, which reads
+// every dashboard its app's sitemap names. The plugin's own pin checks refuse a wrong pin first (resolveExistingFormId,
+// findPinnedDashboard); these pin the SDK's second line and what the download does with it. The stub holds ONE
+// systemform row, whose `type` a test changes the way a platform would answer it.
+const test = require('node:test');
+const assert = require('node:assert');
+const ai = require('../lib/artifact-intent.js');
+const { readDashboards } = require('../download-model-app.js');
+const { createHarness, seedForm, NOTES_CLASS_ID } = require('./helpers/form-store-harness.js');
+
+const spec = {
+ $schemaVersion: '1.0',
+ solution: { uniqueName: 'Kinds', displayName: 'Kinds', publisherPrefix: 'new' },
+ app: { name: 'Kinds', uniqueName: 'new_kinds' },
+ entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', pluralName: 'Tickets', existing: true,
+ primaryAttribute: { schemaName: 'new_name', displayName: 'Name' },
+ columns: [{ schemaName: 'new_code', displayName: 'Code', type: 'Text' }] }],
+ forms: [{ entity: 'new_ticket', name: 'Main', tabs: [{ name: 'tab_a', label: 'A', sections: [{ name: 'sec_main', label: 'Main', columns: 1, fields: ['new_name', 'new_code'] }] }] }],
+};
+const tabs = () => ai.compileFormIntent(spec, spec.forms[0], { notesClassId: NOTES_CLASS_ID }).tabs;
+
+const harnesses = [];
+// A harness whose one row is a Main form that has been serialized, and an SDK over it.
+async function seeded() {
+ const h = createHarness();
+ harnesses.push(h);
+ await seedForm(h, tabs());
+ const { sdk } = await h.freshSdk();
+ const patches = () => h.writes.filter((w) => w.method === 'patch');
+ return { h, sdk, id: h.formId, patches };
+}
+test.after(() => { for (const h of harnesses) h.cleanup(); });
+
+const KIND = (code, pattern) => (err) => { assert.strictEqual(err.code, code, err.message); assert.match(err.message, pattern); return true; };
+
+test('a dashboard\u2019s id is refused as a form, and a form\u2019s as a dashboard, and neither is stored', async () => {
+ const { h, sdk, id } = await seeded();
+ // A Main form (type 2) fetched as a dashboard.
+ await assert.rejects(sdk.fetchArtifact('dashboard', id), KIND('SYSTEMFORM_KIND_MISMATCH', /Refusing to fetch systemform '[^']+' as a dashboard: it is a Main form \(type 2\)\. Nothing was read into the workspace\. Fetch it as a form\./));
+ assert.deepStrictEqual(await sdk.listArtifacts('dashboard'), [], 'no dashboard copy was stored');
+ // The same row, now a dashboard (type 0), fetched as a form.
+ h.store.row.type = 0;
+ await assert.rejects(sdk.fetchArtifact('form', id), KIND('SYSTEMFORM_KIND_MISMATCH', /as a form: it is a dashboard \(type 0\)\. Nothing was read into the workspace\. Fetch it as a dashboard\./));
+ assert.ok(!(await sdk.listArtifacts('form')).some((a) => a.id === id), 'no form copy was stored');
+});
+
+test('a form a copy was fetched for, whose row has since become another kind, is refused at push and nothing is written', async () => {
+ const { h, sdk, id, patches } = await seeded();
+ await sdk.fetchArtifact('form', id);
+ await sdk.updateElement('form', id, '/name', 'Renamed');
+ h.store.row.type = 10; // an interactive dashboard now holds this id
+ const before = patches().length;
+ await assert.rejects(sdk.pushArtifact('form', id), KIND('SYSTEMFORM_KIND_MISMATCH', /Refusing to write systemform '[^']+' as a form: it is an? interactive dashboard \(type 10\)\. Nothing was written\./));
+ assert.strictEqual(patches().length, before, 'no PATCH');
+ assert.notStrictEqual(h.store.row.name, 'Renamed');
+});
+
+test('a form push cannot change the form\u2019s type: refused FORM_TYPE_IMMUTABLE, nothing written', async () => {
+ // The plugin never edits an existing form's type (a changed `formType` finds no row of that type and creates a new
+ // form), so this is the SDK refusing what the platform would silently ignore.
+ const { h, sdk, id, patches } = await seeded();
+ await sdk.fetchArtifact('form', id);
+ await sdk.updateElement('form', id, '/formType', 'QuickCreate');
+ const before = patches().length;
+ await assert.rejects(sdk.pushArtifact('form', id), KIND('FORM_TYPE_IMMUTABLE', /it would change it from a Main form \(type 2\) to a Quick Create form \(type 7\)\. The platform ignores a type change[\s\S]*Nothing was written\./));
+ assert.strictEqual(patches().length, before, 'no PATCH');
+ assert.strictEqual(h.store.row.type, 2);
+});
+
+test('a form pushed with the type it has is written as it always was', async () => {
+ const { sdk, id, patches } = await seeded();
+ await sdk.fetchArtifact('form', id);
+ await sdk.updateElement('form', id, '/name', 'Renamed');
+ const pushed = await sdk.pushArtifact('form', id);
+ assert.notStrictEqual(pushed.saved, false, JSON.stringify(pushed.error && pushed.error.message));
+ assert.strictEqual(patches().length, 1);
+ assert.strictEqual(patches()[0].body.name, 'Renamed');
+});
+
+test('download: a sitemap dashboard subarea whose id is a form is reported as unreadable and left out, never read as a dashboard', async () => {
+ const { sdk, id } = await seeded();
+ const app = { siteMap: { areas: [{ groups: [{ subAreas: [{ type: 'DashBoard', dashboardId: id, title: 'Ops' }] }] }] } };
+ const warnings = [];
+ const dashboards = await readDashboards(sdk, app, (message) => warnings.push(message));
+ assert.deepStrictEqual(dashboards, [], 'nothing is emitted for it');
+ assert.strictEqual(warnings.length, 1, JSON.stringify(warnings));
+ assert.match(warnings[0], /^dashboard 'Ops' \([0-9a-f-]{36}\) could not be read: Refusing to fetch systemform '[0-9a-f-]{36}' as a dashboard: it is a Main form \(type 2\)\./);
+});
diff --git a/plugins/model-apps/scripts/tests/form-order-real-bundle.test.js b/plugins/model-apps/scripts/tests/form-order-real-bundle.test.js
index f495f1d41..55b532199 100644
--- a/plugins/model-apps/scripts/tests/form-order-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/form-order-real-bundle.test.js
@@ -12,11 +12,26 @@ const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
const FORM_ID = '11111111-1111-1111-1111-111111111111';
const ROLE_A = '22222222-2222-2222-2222-222222222222';
const ROLE_B = '33333333-3333-3333-3333-333333333333';
+// systemform.type of a Main form. The SDK reads the type of every form it reads or writes by id and refuses a row of
+// another kind (a dashboard is 0), or one that answers no type, so the row must carry it as the platform's does.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/systemform#BKMK_Type
+const FORM_TYPE_MAIN = 2;
const tempDirs = [];
test.after(() => { for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true }); });
-async function freshSdk(initialXml) {
+// The columns a `$select` names, as the platform answers them: a column that was not selected is not in the body
+// (the SDK's own checks run on the columns it asked for, so a read that forgets `type` must see it missing here too),
+// and `RetrieveUnpublished()` leaves out a selected column whose value is null.
+function selectedColumns(url, row) {
+ const select = /[?&]\$select=([^&]*)/.exec(String(url));
+ const present = Object.entries(row).filter(([column, value]) => value !== null || column.startsWith('@'));
+ if (!select) return Object.fromEntries(present);
+ const wanted = new Set(decodeURIComponent(select[1]).split(',').map((c) => c.trim()));
+ return Object.fromEntries(present.filter(([column]) => wanted.has(column) || column.startsWith('@')));
+}
+
+async function freshSdk(initialXml, { type = FORM_TYPE_MAIN } = {}) {
const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'form-order-sdk-'));
tempDirs.push(dir);
@@ -26,7 +41,8 @@ async function freshSdk(initialXml) {
get: async (url) => {
calls.push({ verb: 'get', url: String(url) });
if (/RetrieveUnpublished\(\)/.test(url)) {
- return { status: 200, headers: {}, body: { formid: FORM_ID, formxml: state.formxml, '@odata.etag': state.etag } };
+ const row = { formid: FORM_ID, formxml: state.formxml, type, '@odata.etag': state.etag };
+ return { status: 200, headers: {}, body: selectedColumns(url, row) };
}
if (/\/systemforms\(/.test(url)) {
return { status: 200, headers: {}, body: { formid: FORM_ID, '@odata.etag': state.etag } };
@@ -104,6 +120,33 @@ test('forms without DisplayConditions refuse order-only writes, while everyone+f
assert.strictEqual(withoutDisplayConditions(xml), withoutDisplayConditions(original), 'adding DisplayConditions leaves the existing form body unchanged');
});
+// A form's id is all the forms phase hands the SDK, and `systemforms` also holds every dashboard (type 0) and the
+// form kinds the SDK does not model. Reading or rewriting such a row as a form would project it through the Main-form
+// grammar and write the re-serialized document back, so the SDK refuses a row of another kind — from the `type` the
+// read already selects — before it parses or writes anything. The plugin checks a pinned id first (resolveExistingFormId);
+// this is the second line, for an id that changed kind or was passed by mistake.
+test('a dashboard\u2019s id is refused as a form: nothing is read into a form, nothing is written', async () => {
+ const live = '<form><tabs><tab name="general" /></tabs><DisplayConditions Order="0" FallbackForm="true"><Everyone /></DisplayConditions></form>';
+ const dashboard = await freshSdk(live, { type: 0 });
+ await assert.rejects(dashboard.sdk.getFormSecurityRoles(FORM_ID), (e) => e.code === 'SYSTEMFORM_KIND_MISMATCH' && /it is a dashboard \(type 0\)/.test(e.message));
+ await assert.rejects(dashboard.sdk.setFormSecurityRoles(FORM_ID, { order: 2 }), (e) => e.code === 'SYSTEMFORM_KIND_MISMATCH' && /Nothing was written/.test(e.message));
+ assert.strictEqual(dashboard.calls.some((c) => c.verb === 'patch'), false, 'no PATCH reached the row');
+ assert.strictEqual(dashboard.state.formxml, live, 'the row is as it was');
+
+ // A kind the SDK does not model reads the same: a task flow form (type 9) is no Main form either.
+ const taskFlow = await freshSdk(live, { type: 9 });
+ await assert.rejects(taskFlow.sdk.setFormSecurityRoles(FORM_ID, { order: 2 }), (e) => e.code === 'SYSTEMFORM_KIND_MISMATCH' && /task flow form \(type 9\)/.test(e.message));
+ assert.strictEqual(taskFlow.calls.some((c) => c.verb === 'patch'), false);
+});
+
+test('a row whose type cannot be read is refused too, never taken for a Main form', async () => {
+ const live = '<form><tabs><tab name="general" /></tabs><DisplayConditions Order="0" FallbackForm="true"><Everyone /></DisplayConditions></form>';
+ const untyped = await freshSdk(live, { type: null });
+ await assert.rejects(untyped.sdk.getFormSecurityRoles(FORM_ID), (e) => e.code === 'SYSTEMFORM_KIND_MISMATCH' && /type could not be read/.test(e.message));
+ await assert.rejects(untyped.sdk.setFormSecurityRoles(FORM_ID, { order: 2 }), (e) => e.code === 'SYSTEMFORM_KIND_MISMATCH');
+ assert.strictEqual(untyped.calls.some((c) => c.verb === 'patch'), false);
+});
+
// The build places a Main form it creates on a table whose order it does not set IN ITS CREATE
// (createInPlace, sdk-build.js): it finds the <DisplayConditions> the SDK gives the new form in its root
// bag and replaces that node before the first push. This pins the SDK side of that: if the node moved or
diff --git a/plugins/model-apps/scripts/tests/form-reconcile-roundtrip-real-bundle.test.js b/plugins/model-apps/scripts/tests/form-reconcile-roundtrip-real-bundle.test.js
index 88af344de..46045d5c9 100644
--- a/plugins/model-apps/scripts/tests/form-reconcile-roundtrip-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/form-reconcile-roundtrip-real-bundle.test.js
@@ -74,7 +74,9 @@ function existingTabs(spec) {
section.id = guid(next++);
for (const row of section.rows) for (const c of row.cells) {
c.id = guid(next++);
- if (c.control) c.control.id = guid(next++);
+ // The timeline keeps the fixed id the platform renders it under: this form is one the engine already
+ // built correctly, which is what "untouched" below is a claim about. (A generated id would be repaired.)
+ if (c.control && c.control.id !== 'notescontrol') c.control.id = guid(next++);
}
}
}
diff --git a/plugins/model-apps/scripts/tests/form-subgrid-placement-real-bundle.test.js b/plugins/model-apps/scripts/tests/form-subgrid-placement-real-bundle.test.js
new file mode 100644
index 000000000..f66a15459
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/form-subgrid-placement-real-bundle.test.js
@@ -0,0 +1,792 @@
+'use strict';
+// REAL BUNDLE: where a form's sub-grid sections go (forms[].subgrids[].tab / column / after / before) — what the
+// build writes for a new grid, how a rebuild moves an older one into place, what it never touches, and what
+// `--verify` says about it. The vendored SDK serializes and re-reads every form here, against a stub HTTP client
+// that stores one systemform row. The pure rules and the spec gate are in form-subgrid-placement.test.js.
+const test = require('node:test');
+const assert = require('node:assert');
+const ai = require('../lib/artifact-intent.js');
+const { runSdkBuild } = require('../lib/sdk-build.js');
+const { createHarness, seedForm, verifyForms, clone, NOTES_CLASS_ID, SUBGRID_CLASS_ID, VIEW_ID } = require('./helpers/form-store-harness.js');
+
+const TASK = 'new_ticket_new_task';
+const COMMENT = 'new_ticket_new_comment';
+const GRID_TASK = `section_grid_${TASK}`;
+const GRID_COMMENT = `section_grid_${COMMENT}`;
+
+function specFor({ layout = 'explicit', subgrids = [], notes = false, mutate } = {}) {
+ const spec = {
+ $schemaVersion: '1.0',
+ solution: { uniqueName: 'Grids', displayName: 'Grids', publisherPrefix: 'new' },
+ app: { name: 'Grids', uniqueName: 'new_grids' },
+ entities: [
+ { schemaName: 'new_ticket', displayName: 'Ticket', pluralName: 'Tickets', existing: true,
+ primaryAttribute: { schemaName: 'new_name', displayName: 'Name' },
+ columns: [
+ { schemaName: 'new_code', displayName: 'Code', type: 'Text' },
+ { schemaName: 'new_notes', displayName: 'Notes', type: 'Memo' },
+ { schemaName: 'new_area', displayName: 'Area', type: 'Text' },
+ { schemaName: 'new_extra', displayName: 'Extra', type: 'Text' },
+ ] },
+ { schemaName: 'new_task', displayName: 'Task', pluralName: 'Tasks', existing: true, primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns: [] },
+ { schemaName: 'new_comment', displayName: 'Comment', pluralName: 'Comments', existing: true, primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns: [] },
+ ],
+ relationships: [
+ { type: 'OneToMany', referenced: 'new_ticket', referencing: 'new_task', lookup: { schemaName: 'new_TicketId', displayName: 'Ticket' } },
+ { type: 'OneToMany', referenced: 'new_ticket', referencing: 'new_comment', lookup: { schemaName: 'new_TicketId2', displayName: 'Ticket' } },
+ ],
+ forms: [layout === 'explicit'
+ ? { entity: 'new_ticket', name: 'Main', notes, subgrids, tabs: [
+ { name: 'tab_a', label: 'A', sections: [
+ { name: 'sec_main', label: 'Main', columns: 2, fields: ['new_name', 'new_code'] },
+ { name: 'sec_more', label: 'More', columns: 1, fields: ['new_notes', 'new_area'] },
+ ] },
+ { name: 'tab_b', label: 'B', sections: [{ name: 'sec_b', label: 'B', columns: 1, fields: [] }] },
+ ] }
+ : layout === 'columns'
+ ? { entity: 'new_ticket', name: 'Main', notes, subgrids, tabs: [{ name: 'tab_a', label: 'A', columns: [
+ { width: '50%', sections: [{ name: 'sec_left', label: 'Left', columns: 1, fields: ['new_name', 'new_code'] }] },
+ { width: '50%', sections: [{ name: 'sec_right', label: 'Right', columns: 1, fields: ['new_notes', 'new_area'] }] },
+ ] }] }
+ : { entity: 'new_ticket', name: 'Main', notes, subgrids }],
+ };
+ if (mutate) mutate(spec);
+ return spec;
+}
+
+const compiledTabs = (spec) => ai.compileFormIntent(spec, spec.forms[0], { notesClassId: NOTES_CLASS_ID }).tabs;
+const layoutOf = (form) => form.tabs.map((t) => t.columns.map((c) => c.sections.map((s) => s.name)));
+const sectionsOf = (form) => form.tabs.flatMap((t) => t.columns.flatMap((c) => c.sections));
+const sectionOf = (form, name) => sectionsOf(form).find((s) => s.name === name);
+const idsByName = (form) => Object.fromEntries(sectionsOf(form).map((s) => [s.name, s.id]));
+const cellsOf = (section) => section.rows.flatMap((r) => r.cells);
+const layoutMutations = (mutations) => mutations.filter((m) => ['addElement', 'updateElement', 'moveElement', 'removeElement'].includes(m.method));
+const GUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g;
+const masked = (value) => JSON.parse(JSON.stringify(value).replace(GUID, '<id>'));
+
+const harnesses = [];
+const newHarness = (options) => { const h = createHarness(options); harnesses.push(h); return h; };
+test.after(() => { for (const h of harnesses) h.cleanup(); });
+
+const fetched = async (h) => clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+const gridChecks = async (h, spec) => (await verifyForms(h, spec)).checks.filter((c) => c.kind === 'form-subgrid');
+
+// One build of the forms phase over a fresh SDK, with what it wrote and said.
+async function build(h, spec) {
+ const run = await h.freshSdk();
+ const warnings = [];
+ const built = await runSdkBuild(spec, { sdk: run.sdk, apply: true, phases: ['forms'], warn: (m) => warnings.push(String(m)) });
+ assert.strictEqual(built.ok, true, JSON.stringify(built.error || built.halt || ''));
+ return { built, warnings, mutations: run.mutations, writes: layoutMutations(run.mutations) };
+}
+
+// --- no placement: what the build has always written ------------------------------------------------------
+
+// A spec whose grids say nothing about where they go must build the form it always did. The writes below are what
+// the build made before the keys existed — recorded, with generated ids masked — so a change to the path an
+// unplaced grid takes shows up here whatever else the placement logic does.
+const GRID_ADD = (relationshipName, target, label) => ['addElement', 'form', '<id>', '/tabs/0/columns/0/sections', {
+ name: `section_grid_${relationshipName}`, label, visible: true, showLabel: true, columns: 1,
+ rows: [{ cells: [{ control: { classId: SUBGRID_CLASS_ID, label, parameters: {
+ TargetEntityType: target, ViewId: '<id>', IsUserView: 'false', RelationshipName: relationshipName, ChartGridMode: 'Grid', RecordsPerPage: '10' } } }] }],
+}];
+const recorded = (writes) => masked(writes.map((m) => [m.method, ...m.args]));
+
+test('no placement: an explicit layout gets each grid appended to the end of the first tab\'s first form-column, as it always did', async () => {
+ const h = newHarness(); delete h.store.row.formxml;
+ const spec = specFor({ subgrids: [{ childEntity: 'new_task' }, { childEntity: 'new_comment', label: 'Notes about it' }] });
+ const first = await build(h, spec);
+ assert.deepStrictEqual(first.writes.map((m) => [m.method, m.args[2]]), [
+ ['addElement', '/tabs'], ['addElement', '/tabs'], ['removeElement', '/tabs/0'], ['updateElement', '/bag/c/2'],
+ ['addElement', '/tabs/0/columns/0/sections'], ['addElement', '/tabs/0/columns/0/sections'],
+ ]);
+ const grids = recorded(first.writes.slice(-2));
+ assert.deepStrictEqual(grids, [GRID_ADD(TASK, 'new_task', 'Tasks'), GRID_ADD(COMMENT, 'new_comment', 'Notes about it')]);
+ assert.ok(first.writes.slice(-2).every((m) => m.args.length === 4), 'no position, no option: the call the build always made');
+ assert.deepStrictEqual(layoutOf(await fetched(h)), [[['sec_main', 'sec_more', GRID_TASK, GRID_COMMENT]], [['sec_b']]]);
+ assert.deepStrictEqual(await gridChecks(h, spec), [], 'a grid that places nothing is held to no place');
+ const again = await build(h, spec);
+ assert.deepStrictEqual(again.mutations, [], 'a rebuild writes nothing');
+});
+
+test('no placement: an auto layout gets its grid the same way, and an existing form is appended to once', async () => {
+ const h = newHarness(); delete h.store.row.formxml;
+ const spec = specFor({ layout: 'auto', subgrids: [{ childEntity: 'new_task' }] });
+ const first = await build(h, spec);
+ assert.deepStrictEqual(recorded(first.writes.slice(-1)), [GRID_ADD(TASK, 'new_task', 'Tasks')]);
+ assert.deepStrictEqual(layoutOf(await fetched(h)), [[['section_general', GRID_TASK]]]);
+
+ const existing = newHarness();
+ const withTwo = specFor({ subgrids: [{ childEntity: 'new_task' }, { childEntity: 'new_comment' }] });
+ await seedForm(existing, compiledTabs(withTwo));
+ const added = await build(existing, withTwo);
+ assert.deepStrictEqual(added.writes.map((m) => [m.method, m.args[2], m.args.length]), [
+ ['addElement', '/tabs/0/columns/0/sections', 4], ['addElement', '/tabs/0/columns/0/sections', 4]]);
+ assert.deepStrictEqual(layoutOf(await fetched(existing)), [[['sec_main', 'sec_more', GRID_TASK, GRID_COMMENT]], [['sec_b']]]);
+ assert.deepStrictEqual((await build(existing, withTwo)).mutations, []);
+});
+
+test('no placement: a grid the maker moved is never moved back, and a grid in a section of the maker\'s own is left alone', async () => {
+ const h = newHarness(); delete h.store.row.formxml;
+ const unplaced = specFor({ subgrids: [{ childEntity: 'new_task' }] });
+ await build(h, unplaced);
+ // The maker drags the engine's grid section into the second tab, in the designer.
+ const moving = await h.freshSdk();
+ await moving.sdk.fetchArtifact('form', h.formId);
+ await moving.sdk.moveElement('form', h.formId, `/tabs/0/columns/0/sections/2`, '/tabs/1/columns/0/sections', { index: 1 });
+ await moving.sdk.pushArtifact('form', h.formId);
+ assert.deepStrictEqual(layoutOf(await fetched(h)), [[['sec_main', 'sec_more']], [['sec_b', GRID_TASK]]]);
+ const rebuilt = await build(h, unplaced);
+ assert.deepStrictEqual(rebuilt.mutations, [], 'nothing the spec did not place is moved');
+ assert.deepStrictEqual(layoutOf(await fetched(h)), [[['sec_main', 'sec_more']], [['sec_b', GRID_TASK]]]);
+});
+
+test('no placement: naming the first tab is the same form as naming nothing', async () => {
+ const plain = newHarness(); delete plain.store.row.formxml;
+ await build(plain, specFor({ subgrids: [{ childEntity: 'new_task' }] }));
+ const named = newHarness(); delete named.store.row.formxml;
+ const { writes } = await build(named, specFor({ subgrids: [{ childEntity: 'new_task', tab: 'tab_a' }] }));
+ assert.deepStrictEqual(masked(await fetched(named)), masked(await fetched(plain)));
+ assert.deepStrictEqual(masked(named.store.row.formxml), masked(plain.store.row.formxml));
+ assert.ok(writes.slice(-1).every((m) => m.args.length === 4), 'appended to the end of the column, with no position');
+});
+
+// --- a NEW grid goes where the spec says -------------------------------------------------------------------
+
+test('placed: a new grid is created between the sections the spec names — in a one-column section of its own, with one write', async () => {
+ const h = newHarness(); delete h.store.row.formxml;
+ const spec = specFor({ subgrids: [{ childEntity: 'new_task', after: 'sec_main' }] });
+ const { writes, warnings, mutations } = await build(h, spec);
+ const form = await fetched(h);
+ assert.deepStrictEqual(layoutOf(form), [[['sec_main', GRID_TASK, 'sec_more']], [['sec_b']]]);
+ const grid = sectionOf(form, GRID_TASK);
+ assert.deepStrictEqual({ columns: grid.columns, label: grid.label, showLabel: grid.showLabel, rows: grid.rows.length }, { columns: 1, label: 'Tasks', showLabel: true, rows: 1 });
+ assert.strictEqual(grid.rows[0].cells[0].control.parameters.RelationshipName, TASK);
+ const adds = writes.filter((m) => m.method === 'addElement' && /sections$/.test(m.args[2]));
+ assert.strictEqual(adds.length, 1);
+ assert.deepStrictEqual(adds[0].args[4], { position: { index: 1 } }, 'written at its place, not appended and moved');
+ assert.deepStrictEqual(mutations.filter((m) => m.method === 'moveElement'), []);
+ assert.deepStrictEqual(warnings, [], 'a new form needs no report');
+ // The server holds it in that order, and verify reads it back where it is.
+ const xml = h.store.row.formxml;
+ assert.ok(xml.indexOf('name="sec_main"') < xml.indexOf(`name="${GRID_TASK}"`) && xml.indexOf(`name="${GRID_TASK}"`) < xml.indexOf('name="sec_more"'));
+ assert.match(xml, /<RelationshipName>new_ticket_new_task<\/RelationshipName>/);
+ const [check] = await gridChecks(h, spec);
+ assert.deepStrictEqual([check.name, check.present, check.detail], ['new_ticket.Main: sub-grid new_task', true, '']);
+ assert.deepStrictEqual((await build(h, spec)).mutations, [], 'idempotent: a rebuild writes nothing');
+});
+
+test('placed: before a section, and after the last one — ahead of the Notes section the build appends', async () => {
+ const before = newHarness(); delete before.store.row.formxml;
+ await build(before, specFor({ subgrids: [{ childEntity: 'new_task', before: 'sec_main' }] }));
+ assert.deepStrictEqual(layoutOf(await fetched(before))[0], [[GRID_TASK, 'sec_main', 'sec_more']]);
+
+ const last = newHarness(); delete last.store.row.formxml;
+ const spec = specFor({ notes: true, subgrids: [{ childEntity: 'new_task', after: 'sec_more' }] });
+ await build(last, spec);
+ assert.deepStrictEqual(layoutOf(await fetched(last))[0], [['sec_main', 'sec_more', GRID_TASK, 'section_notes']]);
+ assert.strictEqual((await gridChecks(last, spec))[0].present, true);
+});
+
+test('placed: a new grid is added to a form that already exists at its place, in one write, with the other sections where they were', async () => {
+ const h = newHarness();
+ const spec = specFor({ subgrids: [{ childEntity: 'new_task', after: 'sec_main' }] });
+ await seedForm(h, compiledTabs(specFor()));
+ const before = await fetched(h);
+ const { writes, warnings } = await build(h, spec);
+ assert.strictEqual(writes.length, 1, JSON.stringify(writes.map((m) => [m.method, m.args[2]])));
+ assert.deepStrictEqual([writes[0].method, writes[0].args[2], writes[0].args[4]], ['addElement', '/tabs/0/columns/0/sections', { position: { index: 1 } }]);
+ assert.deepStrictEqual(warnings, []);
+ const after = await fetched(h);
+ assert.deepStrictEqual(layoutOf(after), [[['sec_main', GRID_TASK, 'sec_more']], [['sec_b']]]);
+ for (const name of ['sec_main', 'sec_more', 'sec_b']) assert.deepStrictEqual(sectionOf(after, name), sectionOf(before, name), `${name} is untouched`);
+});
+
+test('placed: grids that share an anchor go in the order they are declared; declaring them the other way round moves one grid', async () => {
+ const h = newHarness(); delete h.store.row.formxml;
+ const both = (a, b) => specFor({ subgrids: [{ childEntity: a, after: 'sec_main' }, { childEntity: b, after: 'sec_main' }] });
+ await build(h, both('new_task', 'new_comment'));
+ assert.deepStrictEqual(layoutOf(await fetched(h))[0], [['sec_main', GRID_TASK, GRID_COMMENT, 'sec_more']]);
+ const ids = idsByName(await fetched(h));
+
+ const flipped = both('new_comment', 'new_task');
+ const { writes, warnings } = await build(h, flipped);
+ assert.deepStrictEqual(writes.map((m) => [m.method, m.args[2], m.args[4]]), [['moveElement', '/tabs/0/columns/0/sections/2', { index: 1 }]], 'the comment grid, from the third place to the second');
+ assert.strictEqual(warnings.length, 1);
+ assert.match(warnings[0], /^form Main: moved the sub-grid for 'new_comment' \(section 'section_grid_new_ticket_new_comment'\) to sit directly after section 'sec_main', in tab 'tab_a' \(form-column 1\), where subgrids\[\] places it\.$/);
+ const form = await fetched(h);
+ assert.deepStrictEqual(layoutOf(form)[0], [['sec_main', GRID_COMMENT, GRID_TASK, 'sec_more']]);
+ assert.deepStrictEqual(idsByName(form), ids, 'the same sections, in another order');
+ assert.ok((await gridChecks(h, flipped)).every((c) => c.present));
+ assert.deepStrictEqual((await build(h, flipped)).mutations, []);
+});
+
+test('placed: each grid ends directly beside its own anchor — before one section, after another — and the sections between move for no grid', async () => {
+ const h = newHarness(); delete h.store.row.formxml;
+ await build(h, specFor({ subgrids: [{ childEntity: 'new_task', after: 'sec_main' }, { childEntity: 'new_comment', after: 'sec_main' }] }));
+ const ids = idsByName(await fetched(h));
+ const spec = specFor({ subgrids: [{ childEntity: 'new_comment', before: 'sec_main' }, { childEntity: 'new_task', after: 'sec_more' }] });
+ const { writes } = await build(h, spec);
+ assert.deepStrictEqual(layoutOf(await fetched(h))[0], [[GRID_COMMENT, 'sec_main', 'sec_more', GRID_TASK]]);
+ assert.strictEqual(writes.length, 2, 'one move for each grid');
+ assert.deepStrictEqual(idsByName(await fetched(h)), ids, 'no section was made or lost');
+ assert.ok((await gridChecks(h, spec)).every((c) => c.present));
+ assert.deepStrictEqual((await build(h, spec)).mutations, []);
+});
+
+test('placed: a grid that names a tab goes to the end of that tab; one that names a form-column goes to the end of that form-column', async () => {
+ const tabs = newHarness(); delete tabs.store.row.formxml;
+ const inB = specFor({ subgrids: [{ childEntity: 'new_task', tab: 'tab_b' }] });
+ await build(tabs, inB);
+ assert.deepStrictEqual(layoutOf(await fetched(tabs)), [[['sec_main', 'sec_more']], [['sec_b', GRID_TASK]]]);
+ assert.strictEqual((await gridChecks(tabs, inB))[0].present, true);
+
+ const columns = newHarness(); delete columns.store.row.formxml;
+ const second = specFor({ layout: 'columns', subgrids: [{ childEntity: 'new_task', tab: 'tab_a', column: 1 }] });
+ await build(columns, second);
+ assert.deepStrictEqual(layoutOf(await fetched(columns)), [[['sec_left'], ['sec_right', GRID_TASK]]]);
+ assert.strictEqual((await gridChecks(columns, second))[0].present, true);
+ assert.deepStrictEqual((await build(columns, second)).mutations, []);
+
+ // A spec that names only the tab accepts any form-column of it: a grid already in the second one stays.
+ const anyColumn = specFor({ layout: 'columns', subgrids: [{ childEntity: 'new_task', tab: 'tab_a' }] });
+ assert.deepStrictEqual((await build(columns, anyColumn)).mutations, [], 'naming the tab alone is membership of the tab');
+ assert.strictEqual((await gridChecks(columns, anyColumn))[0].present, true);
+});
+
+test('placed: an anchor in the second form-column puts the grid in that form-column, beside its anchor', async () => {
+ const h = newHarness(); delete h.store.row.formxml;
+ const spec = specFor({ layout: 'columns', subgrids: [{ childEntity: 'new_task', after: 'sec_right' }, { childEntity: 'new_comment', before: 'sec_left' }] });
+ await build(h, spec);
+ assert.deepStrictEqual(layoutOf(await fetched(h)), [[[GRID_COMMENT, 'sec_left'], ['sec_right', GRID_TASK]]]);
+ assert.ok((await gridChecks(h, spec)).every((c) => c.present));
+});
+
+test('placed: an auto layout places a grid before or after its one section, and a tab-only grid in its one tab', async () => {
+ const h = newHarness(); delete h.store.row.formxml;
+ const spec = specFor({ layout: 'auto', subgrids: [{ childEntity: 'new_task', before: 'section_general' }, { childEntity: 'new_comment', after: 'section_general' }] });
+ await build(h, spec);
+ assert.deepStrictEqual(layoutOf(await fetched(h)), [[[GRID_TASK, 'section_general', GRID_COMMENT]]]);
+ assert.ok((await gridChecks(h, spec)).every((c) => c.present));
+ assert.deepStrictEqual((await build(h, spec)).mutations, []);
+
+ const tabOnly = newHarness(); delete tabOnly.store.row.formxml;
+ const named = specFor({ layout: 'auto', subgrids: [{ childEntity: 'new_task', tab: 'tab_general' }] });
+ await build(tabOnly, named);
+ assert.deepStrictEqual(layoutOf(await fetched(tabOnly)), [[['section_general', GRID_TASK]]]);
+ assert.strictEqual((await gridChecks(tabOnly, named))[0].present, true);
+});
+
+test('placed: grids the spec places and grids added by autoSubgrids sit together; the added ones go to the end', async () => {
+ const h = newHarness(); delete h.store.row.formxml;
+ const spec = specFor({ subgrids: [{ childEntity: 'new_task', after: 'sec_main' }], mutate: (s) => { s.forms[0].autoSubgrids = true; } });
+ await build(h, spec);
+ assert.deepStrictEqual(layoutOf(await fetched(h))[0], [['sec_main', GRID_TASK, 'sec_more', GRID_COMMENT]]);
+ assert.deepStrictEqual((await build(h, spec)).mutations, []);
+});
+
+// --- a rebuild CONVERGES an older form ---------------------------------------------------------------------
+
+test('converge: a rebuild moves the grid an older build appended to the end of the form into the place the spec now gives it', async () => {
+ const h = newHarness(); delete h.store.row.formxml;
+ await build(h, specFor({ subgrids: [{ childEntity: 'new_task' }] })); // what every earlier version wrote
+ const old = await fetched(h);
+ assert.deepStrictEqual(layoutOf(old)[0], [['sec_main', 'sec_more', GRID_TASK]]);
+ const ids = idsByName(old);
+ const gridBefore = sectionOf(old, GRID_TASK);
+
+ const spec = specFor({ subgrids: [{ childEntity: 'new_task', after: 'sec_main' }] });
+ const stale = await gridChecks(h, spec);
+ assert.strictEqual(stale[0].present, false, 'verify says the fix is not applied');
+ assert.match(stale[0].detail, /the grid is not directly after section 'sec_main' in tab 'tab_a' form-column 1: 'sec_more' sits between them/);
+
+ const { writes, warnings } = await build(h, spec);
+ assert.deepStrictEqual(writes.map((m) => [m.method, m.args[2], m.args[3], m.args[4]]), [['moveElement', '/tabs/0/columns/0/sections/2', '/tabs/0/columns/0/sections', { index: 1 }]], 'the GRID moves, once; nothing is added, removed or rewritten');
+ assert.strictEqual(warnings.length, 1);
+ assert.match(warnings[0], /^form Main: moved the sub-grid for 'new_task' \(section 'section_grid_new_ticket_new_task'\) to sit directly after section 'sec_main', in tab 'tab_a' \(form-column 1\), where subgrids\[\] places it\.$/);
+ const after = await fetched(h);
+ assert.deepStrictEqual(layoutOf(after)[0], [['sec_main', GRID_TASK, 'sec_more']]);
+ assert.deepStrictEqual(idsByName(after), ids, 'the same sections — no grid was deleted and made again');
+ assert.deepStrictEqual(sectionOf(after, GRID_TASK), gridBefore, 'the grid section, its cell and its control are what they were');
+ assert.strictEqual((await gridChecks(h, spec))[0].present, true);
+ assert.deepStrictEqual((await build(h, spec)).mutations, [], 'a second rebuild writes nothing');
+});
+
+// --- the form the released builds deployed ---------------------------------------------------------------------
+
+// An explicit-layout Main form with `notes: true` and one sub-grid, as every release before this one deployed it: the
+// first tab's sections in the order sec_summary, sec_money, section_notes, section_grid_<relationship> — the grid BEHIND
+// the Notes section, since the grid was appended to the end of the column after the Notes section was — and the
+// timeline as it was written then: a generated control id in a one-row cell, no rows under it, no `auto`.
+const releasedSpec = (subgrid) => specFor({ notes: true, subgrids: [subgrid], mutate: (s) => {
+ s.forms[0].tabs = [{ name: 'tab_a', label: 'A', sections: [
+ { name: 'sec_summary', label: 'Summary', columns: 2, fields: ['new_name', 'new_code'] },
+ { name: 'sec_money', label: 'Money', columns: 1, fields: ['new_notes', 'new_area'] },
+ ] }];
+} });
+const releasedNotesHost = () => ({ name: 'section_notes', label: 'Notes', visible: true, showLabel: true, columns: 1,
+ rows: [{ cells: [{ control: { classId: NOTES_CLASS_ID, fieldName: null, label: 'Notes', showLabel: false, parameters: {} } }] }] });
+const engineGridSection = () => ai.subgridSectionIntent({ subgridClassId: SUBGRID_CLASS_ID, targetEntity: 'new_task', relationshipName: TASK, viewId: VIEW_ID, label: 'Tasks' });
+async function seedReleased(h, spec) {
+ const tabs = compiledTabs(spec);
+ const sections = tabs[0].columns[0].sections;
+ sections[sections.findIndex((s) => s.name === 'section_notes')] = releasedNotesHost();
+ sections.push(engineGridSection());
+ await seedForm(h, tabs);
+}
+const RELEASED_ORDER = ['sec_summary', 'sec_money', 'section_notes', GRID_TASK];
+
+for (const [label, subgrid, expected] of [
+ ['with no placement, where it is', { childEntity: 'new_task' }, RELEASED_ORDER],
+ ['after the first section — mid-form, ahead of the Notes section', { childEntity: 'new_task', after: 'sec_summary' }, ['sec_summary', GRID_TASK, 'sec_money', 'section_notes']],
+ ['after the last section — directly after it, not behind the Notes section', { childEntity: 'new_task', after: 'sec_money' }, ['sec_summary', 'sec_money', GRID_TASK, 'section_notes']],
+ ['before the first section', { childEntity: 'new_task', before: 'sec_summary' }, [GRID_TASK, 'sec_summary', 'sec_money', 'section_notes']],
+ ['in its tab only, where it is', { childEntity: 'new_task', tab: 'tab_a' }, RELEASED_ORDER],
+]) {
+ test(`released form: a rebuild repairs the timeline in place and puts the grid ${label} — the same sections, in the order a new form gets`, async () => {
+ const h = newHarness();
+ const spec = releasedSpec(subgrid);
+ await seedReleased(h, spec);
+ const before = await fetched(h);
+ assert.deepStrictEqual(layoutOf(before), [[RELEASED_ORDER]], 'the premise: the grid behind the Notes section');
+ const timelineBefore = cellsOf(sectionOf(before, 'section_notes'))[0];
+ assert.match(timelineBefore.control.id, /^[0-9a-f-]{36}$/, 'the premise: a generated control id');
+ assert.deepStrictEqual([timelineBefore.rowspan, sectionOf(before, 'section_notes').rows.length], [1, 1], 'a one-row cell with nothing under it');
+ assert.ok(!h.store.row.formxml.includes('notescontrol'), 'no notescontrol anywhere on the form');
+ const gridId = sectionOf(before, GRID_TASK).id;
+ const placed = expected !== RELEASED_ORDER;
+ assert.strictEqual((await verifyForms(h, spec)).checks.find((c) => c.kind === 'form-timeline').present, false, 'verify: the timeline fix is not applied');
+ if (placed) assert.strictEqual((await gridChecks(h, spec))[0].present, false, 'verify: the grid is not where the spec places it');
+
+ const { writes } = await build(h, spec);
+ const after = await fetched(h);
+ assert.deepStrictEqual(layoutOf(after), [[expected]]);
+ // The timeline is repaired in place: the same section and the same cell, now the shape Dynamics renders.
+ const host = sectionOf(after, 'section_notes');
+ assert.strictEqual(host.id, sectionOf(before, 'section_notes').id);
+ assert.strictEqual(cellsOf(host)[0].id, timelineBefore.id);
+ assert.deepStrictEqual([cellsOf(host)[0].control.id, cellsOf(host)[0].rowspan, host.rows.length], ['notescontrol', 23, 23]);
+ // The grid is the same section, moved when the spec places it elsewhere — and it is the ONLY thing that moves:
+ // not an authored section, not the Notes section.
+ assert.strictEqual(sectionOf(after, GRID_TASK).id, gridId);
+ const moves = writes.filter((m) => m.method === 'moveElement');
+ assert.deepStrictEqual(moves.map((m) => m.args[2]), placed ? ['/tabs/0/columns/0/sections/3'] : [], 'the grid section, from where it was');
+ assert.deepStrictEqual(writes.filter((m) => m.method !== 'moveElement').map((m) => [m.method, m.args[2].replace(/sections\/\d+/, 'sections/N')]), [['updateElement', '/tabs/0/columns/0/sections/N/rows']], 'the timeline repair is one write of the host\u2019s rows');
+ for (const name of ['sec_summary', 'sec_money']) assert.deepStrictEqual(sectionOf(after, name), sectionOf(before, name), `${name} is untouched`);
+ // Verify is clean, a second rebuild writes nothing, and a new form built from the same spec has the same order.
+ const verified = await verifyForms(h, spec);
+ assert.strictEqual(verified.checks.find((c) => c.kind === 'form-timeline').present, true);
+ if (placed) assert.strictEqual((await gridChecks(h, spec))[0].present, true);
+ assert.deepStrictEqual((await build(h, spec)).mutations, []);
+ const created = newHarness(); delete created.store.row.formxml;
+ await build(created, spec);
+ assert.deepStrictEqual(layoutOf(await fetched(created)), layoutOf(after), 'a rebuilt form and a new one agree');
+ });
+}
+
+test('released form, auto layout: the grid behind the Notes section is put directly after the one section, and the timeline repaired in place', async () => {
+ const h = newHarness();
+ const spec = specFor({ layout: 'auto', notes: true, subgrids: [{ childEntity: 'new_task', after: 'section_general' }] });
+ const tabs = compiledTabs(spec);
+ const sections = tabs[0].columns[0].sections;
+ sections[sections.findIndex((s) => s.name === 'section_notes')] = releasedNotesHost();
+ sections.push(engineGridSection());
+ await seedForm(h, tabs);
+ const before = await fetched(h);
+ assert.deepStrictEqual(layoutOf(before), [[['section_general', 'section_notes', GRID_TASK]]]);
+ const { writes } = await build(h, spec);
+ const after = await fetched(h);
+ assert.deepStrictEqual(layoutOf(after), [[['section_general', GRID_TASK, 'section_notes']]]);
+ assert.strictEqual(sectionOf(after, GRID_TASK).id, sectionOf(before, GRID_TASK).id);
+ assert.strictEqual(sectionOf(after, 'section_notes').id, sectionOf(before, 'section_notes').id);
+ assert.deepStrictEqual([cellsOf(sectionOf(after, 'section_notes'))[0].control.id, sectionOf(after, 'section_notes').rows.length], ['notescontrol', 23]);
+ assert.deepStrictEqual(writes.map((m) => m.method).sort(), ['moveElement', 'updateElement']);
+ assert.ok((await gridChecks(h, spec)).every((c) => c.present));
+ assert.strictEqual((await verifyForms(h, spec)).checks.find((c) => c.kind === 'form-timeline').present, true);
+ assert.deepStrictEqual((await build(h, spec)).mutations, []);
+ const created = newHarness(); delete created.store.row.formxml;
+ await build(created, spec);
+ assert.deepStrictEqual(layoutOf(await fetched(created)), layoutOf(after));
+});
+
+test('placed: a section a maker put between the grid and its anchor stays where it is, behind the grid — only the grid moves', async () => {
+ const h = newHarness();
+ const spec = specFor({ subgrids: [{ childEntity: 'new_task', after: 'sec_main' }], mutate: (s) => { s.forms[0].prune = false; } });
+ const tabs = compiledTabs(specFor());
+ const maker = { name: 'maker_section', label: 'Maker', visible: true, showLabel: true, columns: 1, rows: [{ cells: [ai.fieldCellIntent('new_extra')] }] };
+ tabs[0].columns[0].sections.push(maker, engineGridSection());
+ await seedForm(h, tabs);
+ const before = await fetched(h);
+ assert.deepStrictEqual(layoutOf(before)[0], [['sec_main', 'sec_more', 'maker_section', GRID_TASK]]);
+ const unplaced = (await gridChecks(h, spec))[0];
+ assert.strictEqual(unplaced.present, false);
+ assert.match(unplaced.detail, /the grid is not directly after section 'sec_main' in tab 'tab_a' form-column 1: 'sec_more', 'maker_section' sit between them/);
+
+ const { writes } = await build(h, spec);
+ assert.deepStrictEqual(writes.map((m) => [m.method, m.args[2], m.args[4]]), [['moveElement', '/tabs/0/columns/0/sections/3', { index: 1 }]]);
+ const after = await fetched(h);
+ assert.deepStrictEqual(layoutOf(after)[0], [['sec_main', GRID_TASK, 'sec_more', 'maker_section']]);
+ assert.deepStrictEqual(sectionOf(after, 'maker_section'), sectionOf(before, 'maker_section'), 'the maker\u2019s section is exactly what it was');
+ assert.strictEqual((await gridChecks(h, spec))[0].present, true);
+ assert.deepStrictEqual((await build(h, spec)).mutations, []);
+});
+
+test('placed: a grid moves DOWN the column too — to sit directly after a later section, ahead of the section that follows it', async () => {
+ const h = newHarness(); delete h.store.row.formxml;
+ const three = (subgrid) => specFor({ subgrids: [subgrid], mutate: (s) => { s.forms[0].tabs[0].sections.push({ name: 'sec_third', label: 'Third', columns: 1, fields: ['new_extra'] }); } });
+ await build(h, three({ childEntity: 'new_task', after: 'sec_main' }));
+ assert.deepStrictEqual(layoutOf(await fetched(h))[0], [['sec_main', GRID_TASK, 'sec_more', 'sec_third']]);
+ const spec = three({ childEntity: 'new_task', after: 'sec_more' });
+ const { writes } = await build(h, spec);
+ assert.deepStrictEqual(writes.map((m) => [m.method, m.args[2], m.args[4]]), [['moveElement', '/tabs/0/columns/0/sections/1', { index: 2 }]]);
+ assert.deepStrictEqual(layoutOf(await fetched(h))[0], [['sec_main', 'sec_more', GRID_TASK, 'sec_third']]);
+ assert.strictEqual((await gridChecks(h, spec))[0].present, true);
+ assert.deepStrictEqual((await build(h, spec)).mutations, []);
+});
+
+test('placed: two grids before one section sit in front of it in declared order, the one declared last against the section — new, or rebuilt from the end', async () => {
+ const spec = specFor({ subgrids: [{ childEntity: 'new_task', before: 'sec_more' }, { childEntity: 'new_comment', before: 'sec_more' }] });
+ const created = newHarness(); delete created.store.row.formxml;
+ await build(created, spec);
+ assert.deepStrictEqual(layoutOf(await fetched(created))[0], [['sec_main', GRID_TASK, GRID_COMMENT, 'sec_more']]);
+ assert.ok((await gridChecks(created, spec)).every((c) => c.present));
+
+ const old = newHarness(); delete old.store.row.formxml;
+ await build(old, specFor({ subgrids: [{ childEntity: 'new_comment' }, { childEntity: 'new_task' }] }));
+ assert.deepStrictEqual(layoutOf(await fetched(old))[0], [['sec_main', 'sec_more', GRID_COMMENT, GRID_TASK]], 'what an earlier build left: both at the end, the other way round');
+ await build(old, spec);
+ assert.deepStrictEqual(layoutOf(await fetched(old))[0], [['sec_main', GRID_TASK, GRID_COMMENT, 'sec_more']]);
+ assert.ok((await gridChecks(old, spec)).every((c) => c.present));
+ assert.deepStrictEqual((await build(old, spec)).mutations, []);
+});
+
+test('converge: a grid moves to another tab or form-column when the spec moves its placement, and keeps its section', async () => {
+ const h = newHarness(); delete h.store.row.formxml;
+ await build(h, specFor({ subgrids: [{ childEntity: 'new_task', tab: 'tab_b' }] }));
+ const ids = idsByName(await fetched(h));
+ const toA = specFor({ subgrids: [{ childEntity: 'new_task', tab: 'tab_a' }] });
+ const { writes, warnings } = await build(h, toA);
+ assert.deepStrictEqual(writes.map((m) => [m.method, m.args[2], m.args[3], m.args[4]]), [['moveElement', '/tabs/1/columns/0/sections/1', '/tabs/0/columns/0/sections', { index: 2 }]]);
+ assert.match(warnings[0], /^form Main: moved the sub-grid for 'new_task' \(section 'section_grid_new_ticket_new_task'\) from tab 'tab_b' \(form-column 1\) to tab 'tab_a' \(form-column 1\), where subgrids\[\] places it\.$/);
+ assert.deepStrictEqual(layoutOf(await fetched(h)), [[['sec_main', 'sec_more', GRID_TASK]], [['sec_b']]]);
+ assert.strictEqual(idsByName(await fetched(h))[GRID_TASK], ids[GRID_TASK]);
+ assert.deepStrictEqual((await build(h, toA)).mutations, []);
+
+ // Between form-columns of one tab, then to the anchor's column.
+ const cols = newHarness(); delete cols.store.row.formxml;
+ await build(cols, specFor({ layout: 'columns', subgrids: [{ childEntity: 'new_task', tab: 'tab_a', column: 1 }] }));
+ const toFirst = specFor({ layout: 'columns', subgrids: [{ childEntity: 'new_task', column: 0 }] });
+ await build(cols, toFirst);
+ assert.deepStrictEqual(layoutOf(await fetched(cols)), [[['sec_left', GRID_TASK], ['sec_right']]]);
+ const toAnchor = specFor({ layout: 'columns', subgrids: [{ childEntity: 'new_task', after: 'sec_right' }] });
+ await build(cols, toAnchor);
+ assert.deepStrictEqual(layoutOf(await fetched(cols)), [[['sec_left'], ['sec_right', GRID_TASK]]]);
+ assert.deepStrictEqual((await build(cols, toAnchor)).mutations, []);
+ assert.ok((await gridChecks(cols, toAnchor)).every((c) => c.present));
+});
+
+test('converge: taking the placement out of the spec leaves the grid where it is — it is never moved for a spec that says nothing', async () => {
+ const h = newHarness(); delete h.store.row.formxml;
+ await build(h, specFor({ subgrids: [{ childEntity: 'new_task', after: 'sec_main' }] }));
+ const placed = await fetched(h);
+ assert.deepStrictEqual((await build(h, specFor({ subgrids: [{ childEntity: 'new_task' }] }))).mutations, []);
+ assert.deepStrictEqual(await fetched(h), placed);
+});
+
+test('converge: a grid the maker put in a section of their own is never moved, the build says so, and verify keeps failing until it is placed', async () => {
+ const h = newHarness();
+ const spec = specFor({ subgrids: [{ childEntity: 'new_task', after: 'sec_main' }] });
+ const tabs = compiledTabs(specFor());
+ tabs[0].columns[0].sections.push(ai.subgridSectionIntent({ subgridClassId: SUBGRID_CLASS_ID, targetEntity: 'new_task', relationshipName: TASK, viewId: VIEW_ID, label: 'My tasks', sectionName: 'maker_grid' }));
+ await seedForm(h, tabs);
+ const before = h.store.row.formxml;
+ const { built, mutations, warnings } = await build(h, spec);
+ assert.deepStrictEqual(layoutMutations(mutations), [], 'nothing was written');
+ assert.strictEqual(h.store.row.formxml, before);
+ assert.deepStrictEqual(layoutOf(await fetched(h))[0], [['sec_main', 'sec_more', 'maker_grid']]);
+ const note = /the sub-grid for 'new_task' sits in section 'maker_grid', which this build did not create, so it was left there\. Move that section in the maker, or delete it to let the build place a grid of its own\./;
+ assert.ok(built.skipped.layout.some((m) => note.test(m)), JSON.stringify(built.skipped.layout));
+ assert.ok(warnings.some((m) => note.test(m)));
+ const [check] = await gridChecks(h, spec);
+ assert.strictEqual(check.present, false, 'the grid is not where the spec places it, and verify says so');
+});
+
+test('converge: a grid in a section the maker made is left alone WITHOUT a report when it is already where the spec puts it', async () => {
+ // The report says "move that section in the maker" — advice for a grid that is not in place. One that already is has
+ // nothing to move, and a notice repeated on every rebuild is one the maker learns to ignore.
+ const makerGrid = () => ai.subgridSectionIntent({ subgridClassId: SUBGRID_CLASS_ID, targetEntity: 'new_task', relationshipName: TASK, viewId: VIEW_ID, label: 'My tasks', sectionName: 'maker_grid' });
+ for (const [label, subgrid, put] of [
+ ['directly after its anchor', { childEntity: 'new_task', after: 'sec_main' }, (tabs) => tabs[0].columns[0].sections.splice(1, 0, makerGrid())],
+ ['directly before its anchor', { childEntity: 'new_task', before: 'sec_more' }, (tabs) => tabs[0].columns[0].sections.splice(1, 0, makerGrid())],
+ ['in the tab it names', { childEntity: 'new_task', tab: 'tab_b' }, (tabs) => tabs[1].columns[0].sections.push(makerGrid())],
+ ['in the form-column it names', { childEntity: 'new_task', tab: 'tab_a', column: 0 }, (tabs) => tabs[0].columns[0].sections.push(makerGrid())],
+ ]) {
+ const h = newHarness();
+ const spec = specFor({ subgrids: [subgrid] });
+ const tabs = compiledTabs(specFor());
+ put(tabs);
+ await seedForm(h, tabs);
+ assert.strictEqual((await gridChecks(h, spec))[0].present, true, `${label}: the premise — verify finds the grid in place`);
+ const before = h.store.row.formxml;
+ for (const run of ['first', 'second']) {
+ const { built, mutations, warnings } = await build(h, spec);
+ assert.deepStrictEqual(layoutMutations(mutations), [], `${label}, ${run} build: nothing is written`);
+ assert.deepStrictEqual(built.skipped.layout, [], `${label}, ${run} build: nothing is reported`);
+ assert.deepStrictEqual(warnings, [], `${label}, ${run} build`);
+ }
+ assert.strictEqual(h.store.row.formxml, before);
+ }
+});
+
+test('converge: an anchor the deployed form does not have is reported, and the grid is added at the end of the first tab rather than lost', async () => {
+ const h = newHarness();
+ const spec = specFor({ layout: 'auto', subgrids: [{ childEntity: 'new_task', after: 'section_general' }] });
+ const tabs = compiledTabs(spec);
+ tabs[0].columns[0].sections[0].name = 'details'; // a form the maker built: no section carries the name the compiler gives an auto layout
+ await seedForm(h, tabs);
+ const { built, writes } = await build(h, spec);
+ assert.deepStrictEqual(writes.map((m) => [m.method, m.args[2], m.args.length]), [['addElement', '/tabs/0/columns/0/sections', 4]]);
+ assert.deepStrictEqual(layoutOf(await fetched(h)), [[['details', GRID_TASK]]]);
+ assert.ok(built.skipped.layout.some((m) => /the sub-grid for 'new_task' was not placed after section 'section_general' — the deployed form has no such section or tab to place it by, so it was added at the end of the first tab\. Adjust the layout in the maker\./.test(m)), JSON.stringify(built.skipped.layout));
+ const [check] = await gridChecks(h, spec);
+ assert.strictEqual(check.present, false);
+ assert.match(check.detail, /its anchor section 'section_general' is not on the deployed form, so where the grid sits cannot be proven/);
+ assert.deepStrictEqual((await build(h, spec)).writes, [], 'a grid that is on the form is not added again');
+});
+
+test('converge: an anchor matched by label under another name is the anchor, and the grid lands beside the section the build matched', async () => {
+ const h = newHarness();
+ const spec = specFor({ subgrids: [{ childEntity: 'new_task', after: 'sec_main' }] });
+ const tabs = compiledTabs(specFor());
+ tabs[0].columns[0].sections[0].name = 'renamed_in_designer';
+ await seedForm(h, tabs);
+ const { writes } = await build(h, spec);
+ assert.deepStrictEqual(writes.map((m) => [m.method, m.args[4]]), [['addElement', { position: { index: 1 } }]]);
+ assert.deepStrictEqual(layoutOf(await fetched(h))[0], [['renamed_in_designer', GRID_TASK, 'sec_more']]);
+ assert.strictEqual((await gridChecks(h, spec))[0].present, true);
+});
+
+// Adding or moving a section changes the index of every section after it, and the sweep of vacated sections that
+// follows the grids decides which section the layout claims by where each recorded target RESOLVES to — which only
+// the recorded index can tell apart when two sections share a name (a real one, and an emptied copy an older
+// build left in another tab). A target left pointing at the wrong index resolves to the first of the two.
+for (const how of ['added', 'moved in', 'moved out']) {
+ test(`converge: the sweep of an emptied same-named section still finds the section the layout claims after a grid was ${how}`, async () => {
+ const h = newHarness();
+ const placing = how === 'moved out' ? { childEntity: 'new_task', tab: 'tab_a' } : { childEntity: 'new_task', before: 'sec_more' };
+ const spec = specFor({ subgrids: [placing], mutate: (s) => { s.forms[0].tabs[0].sections.pop(); s.forms[0].tabs[0].sections[0].fields = ['new_name', 'new_code']; s.forms[0].tabs[1].sections[0] = { name: 'sec_more', label: 'More', columns: 1, fields: ['new_notes', 'new_area'] }; } });
+ const tabs = compiledTabs(spec);
+ const real = tabs[1].columns[0].sections[0];
+ const twin = clone(real); // the copy an older build left: the same name, in the first tab, still holding the fields
+ real.rows = [];
+ tabs[0].columns[0].sections.push(twin);
+ const engineGrid = ai.subgridSectionIntent({ subgridClassId: SUBGRID_CLASS_ID, targetEntity: 'new_task', relationshipName: TASK, viewId: VIEW_ID, label: 'Tasks' });
+ if (how === 'moved in') tabs[0].columns[0].sections.push(engineGrid);
+ if (how === 'moved out') tabs[1].columns[0].sections.unshift(engineGrid);
+ await seedForm(h, tabs);
+ const gridId = how === 'added' ? null : idsByName(await fetched(h))[GRID_TASK];
+
+ const { warnings } = await build(h, spec);
+ const form = await fetched(h);
+ const expected = how === 'moved out' ? [[['sec_main', GRID_TASK]], [['sec_more']]] : [[['sec_main']], [[GRID_TASK, 'sec_more']]];
+ assert.deepStrictEqual(layoutOf(form), expected, 'the emptied copy is reclaimed, not spared as if it were the claimed section');
+ assert.ok(warnings.some((w) => /removed the now-empty section 'sec_more'/.test(w)), JSON.stringify(warnings));
+ assert.strictEqual(sectionOf(form, 'sec_more').rows.reduce((n, r) => n + r.cells.length, 0), 2, 'the real section holds the fields');
+ if (gridId) assert.strictEqual(idsByName(form)[GRID_TASK], gridId, 'the grid is the same section');
+ assert.ok((await gridChecks(h, spec)).every((c) => c.present));
+ assert.deepStrictEqual((await build(h, spec)).mutations, [], 'settled');
+ });
+}
+
+test('converge: a field is still pruned from its section when a grid was added or moved in front of it', async () => {
+ for (const how of ['added', 'moved']) {
+ const h = newHarness();
+ const old = specFor({ mutate: (s) => { s.forms[0].tabs[0].sections[1].fields.push('new_extra'); } });
+ await seedForm(h, compiledTabs(old));
+ if (how === 'moved') {
+ const first = specFor({ subgrids: [{ childEntity: 'new_task' }], mutate: (s) => { s.forms[0].tabs[0].sections[1].fields.push('new_extra'); } });
+ await build(h, first); // the grid at the end, the stale field still on the form
+ assert.match(h.store.row.formxml, /new_extra/);
+ }
+ const spec = specFor({ subgrids: [{ childEntity: 'new_task', after: 'sec_main' }] }); // new_extra is no longer in the layout
+ await build(h, spec);
+ const form = await fetched(h);
+ assert.deepStrictEqual(layoutOf(form)[0], [['sec_main', GRID_TASK, 'sec_more']], how);
+ assert.ok(!h.store.row.formxml.includes('new_extra'), `${how}: the field is pruned from sec_more`);
+ assert.strictEqual(sectionOf(form, GRID_TASK).rows.length, 1, `${how}: the grid section was not the one pruned`);
+ assert.ok(h.store.row.formxml.includes('datafieldname="new_notes"') && h.store.row.formxml.includes('datafieldname="new_area"'), `${how}: sec_more keeps its other fields`);
+ assert.deepStrictEqual((await build(h, spec)).mutations, [], `${how}: settled`);
+ }
+});
+
+// --- a field the build ADDS is written to its own section, whatever a grid does to the sections' indices -------------
+
+// A field new to the form is held in the plan until every positioning step is done, and the sub-grids are placed in
+// between. A grid section added or moved in the middle of a column changes the index of every section behind it, so a
+// field remembered by index would be written into whichever section holds that index by then — the grid's — or into
+// none, which halts the forms phase. The field must land in the section it was meant for.
+
+// The form as it was deployed before `field` was on it: the compiled tabs with that field's cell taken out.
+const withoutField = (tabs, field) => {
+ for (const section of tabs.flatMap((t) => t.columns.flatMap((c) => c.sections))) {
+ for (const row of section.rows) row.cells = row.cells.filter((c) => !(c.control && c.control.fieldName === field));
+ section.rows = section.rows.filter((r) => r.cells.length);
+ }
+ return tabs;
+};
+const fieldsOf = (section) => cellsOf(section).map((c) => c.control && c.control.fieldName).filter(Boolean);
+
+for (const released of [false, true]) {
+ test(`pending field: a field new to an auto form is written to the form's own section when a grid is put before that section${released ? ' — on the form the released builds deployed' : ''}`, async () => {
+ const h = newHarness();
+ const spec = specFor({ layout: 'auto', notes: released, subgrids: [{ childEntity: 'new_task', before: 'section_general' }] });
+ const tabs = withoutField(compiledTabs(spec), 'new_extra');
+ if (released) {
+ const sections = tabs[0].columns[0].sections;
+ sections[sections.findIndex((s) => s.name === 'section_notes')] = releasedNotesHost();
+ sections.push(engineGridSection());
+ }
+ await seedForm(h, tabs);
+ assert.ok(!h.store.row.formxml.includes('new_extra'), 'the premise: the field is not on the form');
+
+ await build(h, spec);
+ const after = await fetched(h);
+ assert.deepStrictEqual(layoutOf(after), [[released ? [GRID_TASK, 'section_general', 'section_notes'] : [GRID_TASK, 'section_general']]]);
+ assert.deepStrictEqual(fieldsOf(sectionOf(after, GRID_TASK)), [], 'the grid section holds no field');
+ assert.strictEqual(cellsOf(sectionOf(after, GRID_TASK)).length, 1, 'only its grid');
+ assert.ok(fieldsOf(sectionOf(after, 'section_general')).includes('new_extra'), 'new_extra is in the section the form always had');
+ assert.deepStrictEqual((await build(h, spec)).mutations, [], 'settled: nothing is left to correct on a second build');
+ });
+}
+
+test('pending field: a field in a section the spec adds is written to that section when a grid is put in front of it', async () => {
+ const h = newHarness();
+ await seedForm(h, compiledTabs(specFor()));
+ const spec = specFor({ subgrids: [{ childEntity: 'new_task', after: 'sec_more' }], mutate: (s) => { s.forms[0].tabs[0].sections.push({ name: 'sec_new', label: 'New', columns: 1, fields: ['new_extra'] }); } });
+ await build(h, spec);
+ const after = await fetched(h);
+ assert.deepStrictEqual(layoutOf(after), [[['sec_main', 'sec_more', GRID_TASK, 'sec_new']], [['sec_b']]]);
+ assert.deepStrictEqual(fieldsOf(sectionOf(after, 'sec_new')), ['new_extra'], 'the new section holds its field');
+ assert.deepStrictEqual(fieldsOf(sectionOf(after, GRID_TASK)), [], 'the grid section holds none');
+ const topology = (await verifyForms(h, spec)).checks.find((c) => c.kind === 'form-topology');
+ assert.strictEqual(topology.present, true, topology.detail);
+ assert.ok((await gridChecks(h, spec)).every((c) => c.present));
+ assert.deepStrictEqual((await build(h, spec)).mutations, [], 'one build is enough');
+});
+
+// A section that already lists a field the form has is a weak test of this: the build moves a new field beside its
+// listed neighbour afterwards, which repairs a wrong landing. These give the FIRST field to a section with no
+// neighbour to go by — `sec_b`, which the layout declares empty and the spec now gives `new_extra`.
+for (const [how, first, next, expected] of [
+ ['is added in front of it', null, { before: 'sec_b' }, [[['sec_main', 'sec_more']], [[GRID_TASK, 'sec_b']]]],
+ ['leaves its form-column for another tab', { before: 'sec_b' }, { tab: 'tab_a' }, [[['sec_main', 'sec_more', GRID_TASK]], [['sec_b']]]],
+ ['moves down past it', { before: 'sec_b' }, { after: 'sec_b' }, [[['sec_main', 'sec_more']], [['sec_b', GRID_TASK]]]],
+ ['moves up from behind it', { after: 'sec_b' }, { before: 'sec_b' }, [[['sec_main', 'sec_more']], [[GRID_TASK, 'sec_b']]]],
+]) {
+ test(`pending field: the first field of a section is written to that section when the grid ${how} — the forms phase does not halt`, async () => {
+ const h = newHarness(); delete h.store.row.formxml;
+ await build(h, specFor({ subgrids: first ? [Object.assign({ childEntity: 'new_task' }, first)] : [] }));
+ const spec = specFor({ subgrids: [Object.assign({ childEntity: 'new_task' }, next)], mutate: (s) => { s.forms[0].tabs[1].sections[0].fields.push('new_extra'); } });
+ await build(h, spec);
+ const after = await fetched(h);
+ assert.deepStrictEqual(layoutOf(after), expected);
+ assert.deepStrictEqual(fieldsOf(sectionOf(after, 'sec_b')), ['new_extra']);
+ assert.deepStrictEqual(fieldsOf(sectionOf(after, GRID_TASK)), [], 'the grid section holds none');
+ assert.ok((await gridChecks(h, spec)).every((c) => c.present));
+ assert.deepStrictEqual((await build(h, spec)).mutations, [], 'settled');
+ });
+}
+
+test('pending field: the grid sits between two sections and moves to another tab while the section behind it gains a field — the build does not halt', async () => {
+ const h = newHarness(); delete h.store.row.formxml;
+ await build(h, specFor({ subgrids: [{ childEntity: 'new_task', after: 'sec_main' }] }));
+ assert.deepStrictEqual(layoutOf(await fetched(h))[0], [['sec_main', GRID_TASK, 'sec_more']], 'the premise: sec_main, the grid, sec_more');
+ const spec = specFor({ subgrids: [{ childEntity: 'new_task', tab: 'tab_b' }], mutate: (s) => { s.forms[0].tabs[0].sections[1].fields.push('new_extra'); } });
+ await build(h, spec);
+ const after = await fetched(h);
+ assert.deepStrictEqual(layoutOf(after), [[['sec_main', 'sec_more']], [['sec_b', GRID_TASK]]]);
+ assert.ok(fieldsOf(sectionOf(after, 'sec_more')).includes('new_extra'), 'the new field is in sec_more');
+ assert.deepStrictEqual(fieldsOf(sectionOf(after, GRID_TASK)), []);
+ assert.ok((await gridChecks(h, spec)).every((c) => c.present));
+ assert.deepStrictEqual((await build(h, spec)).mutations, [], 'settled');
+});
+
+test('pending field: with two sections of one name, the field goes to the one the layout claims — not the first of that name in the form', async () => {
+ // The copy an older build left behind (empty, in the first tab) shares the name of the real section; a grid placed
+ // before the real one shifts it, so a lookup by name alone would hand the field to the copy.
+ const h = newHarness();
+ const tabsOf = (fields) => [
+ { name: 'tab_a', label: 'A', sections: [{ name: 'sec_main', label: 'Main', columns: 2, fields: ['new_name', 'new_code'] }] },
+ { name: 'tab_b', label: 'B', sections: [{ name: 'sec_more', label: 'More', columns: 1, fields }] },
+ ];
+ const tabs = compiledTabs(specFor({ mutate: (s) => { s.forms[0].tabs = tabsOf([]); } }));
+ tabs[0].columns[0].sections.push({ name: 'sec_more', label: 'More', visible: true, showLabel: true, columns: 1, rows: [] });
+ await seedForm(h, tabs);
+ const spec = specFor({ subgrids: [{ childEntity: 'new_task', before: 'sec_more' }], mutate: (s) => { s.forms[0].tabs = tabsOf(['new_extra']); } });
+ await build(h, spec);
+ const form = await fetched(h);
+ assert.deepStrictEqual(layoutOf(form), [[['sec_main', 'sec_more']], [[GRID_TASK, 'sec_more']]], 'the copy stays where it was; the grid is ahead of the real section');
+ const [copy, real] = sectionsOf(form).filter((s) => s.name === 'sec_more');
+ assert.deepStrictEqual(fieldsOf(real), ['new_extra'], 'the real section holds the field');
+ assert.deepStrictEqual(fieldsOf(copy), [], 'the copy holds nothing');
+ assert.deepStrictEqual(fieldsOf(sectionOf(form, GRID_TASK)), []);
+ assert.deepStrictEqual((await build(h, spec)).mutations, [], 'settled');
+});
+
+test('pending field: a section that is gone by the time its field is written does not halt the build — the field goes to the first field section, and is reported', async () => {
+ const h = newHarness(); delete h.store.row.formxml;
+ await build(h, specFor({ subgrids: [{ childEntity: 'new_task', before: 'sec_b' }] })); // tab_b: the grid, then sec_b
+ const spec = specFor({ subgrids: [{ childEntity: 'new_task', tab: 'tab_a' }], mutate: (s) => { s.forms[0].tabs[1].sections[0].fields.push('new_extra'); } });
+ const run = await h.freshSdk();
+ const moveElement = run.sdk.moveElement.bind(run.sdk);
+ run.sdk.moveElement = async (...args) => {
+ const moved = await moveElement(...args);
+ await run.sdk.removeElement('form', h.formId, '/tabs/1/columns/0/sections/0'); // sec_b — first in its column once the grid has left
+ return moved;
+ };
+ const warnings = [];
+ const built = await runSdkBuild(spec, { sdk: run.sdk, apply: true, phases: ['forms'], warn: (m) => warnings.push(String(m)) });
+ assert.strictEqual(built.ok, true, JSON.stringify(built.error || built.halt || ''));
+ const after = await fetched(h);
+ assert.ok(!sectionOf(after, 'sec_b'), 'the premise: the section the field was queued for is gone');
+ assert.ok(fieldsOf(sectionOf(after, 'sec_main')).includes('new_extra'), 'the form\u2019s first field section took the field');
+ assert.deepStrictEqual(fieldsOf(sectionOf(after, GRID_TASK)), [], 'the grid section did not');
+ assert.ok(built.skipped.layout.some((m) => /'new_extra' was added to the first section of the form — the section the layout names for it was no longer there/.test(m)), JSON.stringify(built.skipped.layout));
+ assert.ok(warnings.some((m) => /'new_extra' was added to the first section of the form/.test(m)));
+});
+
+test('pending field: on the form the released builds deployed, a field in a section the spec adds is written to it when the grid moves in front of it', async () => {
+ const h = newHarness();
+ await seedReleased(h, releasedSpec({ childEntity: 'new_task' }));
+ const spec = releasedSpec({ childEntity: 'new_task', after: 'sec_money' });
+ spec.forms[0].tabs[0].sections.push({ name: 'sec_extra', label: 'Extra', columns: 1, fields: ['new_extra'] });
+ await build(h, spec);
+ const after = await fetched(h);
+ assert.deepStrictEqual(layoutOf(after), [[['sec_summary', 'sec_money', GRID_TASK, 'sec_extra', 'section_notes']]]);
+ assert.deepStrictEqual(fieldsOf(sectionOf(after, 'sec_extra')), ['new_extra']);
+ assert.deepStrictEqual(fieldsOf(sectionOf(after, GRID_TASK)), []);
+ assert.deepStrictEqual(fieldsOf(sectionOf(after, 'section_notes')), [], 'nor does the Notes section take it');
+ const verified = await verifyForms(h, spec);
+ assert.ok(verified.checks.filter((c) => ['form-topology', 'form-timeline', 'form-subgrid'].includes(c.kind)).every((c) => c.present), JSON.stringify(verified.missing));
+ assert.deepStrictEqual((await build(h, spec)).mutations, []);
+ const created = newHarness(); delete created.store.row.formxml;
+ await build(created, spec);
+ assert.deepStrictEqual(layoutOf(await fetched(created)), layoutOf(after), 'a rebuilt form and a new one agree');
+});
+
+test('converge: a move is ONE write, so an interrupted rebuild leaves the form as it was and a retry converges', async () => {
+ const h = newHarness(); delete h.store.row.formxml;
+ await build(h, specFor({ subgrids: [{ childEntity: 'new_task' }] }));
+ const spec = specFor({ subgrids: [{ childEntity: 'new_task', after: 'sec_main' }] });
+ const first = await h.freshSdk();
+ const before = clone(await first.sdk.fetchArtifact('form', h.formId));
+ const original = first.sdk.moveElement.bind(first.sdk);
+ let injected = false;
+ first.sdk.moveElement = async (...args) => { injected = true; throw new Error('injected write failure'); };
+ await assert.rejects(() => runSdkBuild(spec, { sdk: first.sdk, apply: true, phases: ['forms'] }), /injected write failure/);
+ assert.ok(injected, 'the fault was exercised');
+ assert.deepStrictEqual(clone(await first.sdk.getArtifact('form', h.formId)), before);
+ first.sdk.moveElement = original;
+ assert.strictEqual((await runSdkBuild(spec, { sdk: first.sdk, apply: true, phases: ['forms'] })).ok, true);
+ assert.deepStrictEqual(layoutOf(clone(await first.sdk.getArtifact('form', h.formId)))[0], [['sec_main', GRID_TASK, 'sec_more']]);
+});
diff --git a/plugins/model-apps/scripts/tests/form-subgrid-placement.test.js b/plugins/model-apps/scripts/tests/form-subgrid-placement.test.js
new file mode 100644
index 000000000..4a85d2e5d
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/form-subgrid-placement.test.js
@@ -0,0 +1,648 @@
+'use strict';
+// Where a form's sub-grid sections go — forms[].subgrids[].tab / column / after / before.
+//
+// The rules (lib/form-subgrid-placement.js), what the spec gate and the lint say about a placement, what `--verify`
+// reads off a deployed form, and how the wireframe and the plan show it. What the BUILD does with a placement —
+// where a new grid goes, how a rebuild moves an older one — is proven against the real SDK bundle in
+// form-subgrid-placement-real-bundle.test.js.
+const test = require('node:test');
+const assert = require('node:assert');
+const placement = require('../lib/form-subgrid-placement.js');
+const { validateAppSpec, formLayoutNames, subgridPlacementProblems, subgridRelationshipName } = require('../lib/app-spec.js');
+const { lintAppSpec } = require('../lib/spec-lint.js');
+const { compileFormIntent } = require('../lib/artifact-intent.js');
+const { verifySpec } = require('../lib/verify-spec.js');
+const { renderFormWireframe } = require('../lib/form-preview.js');
+const { renderAppSpecDoc } = require('../lib/app-spec-doc.js');
+
+const SUBGRID_CLASS = '{E7A81278-8635-4D9E-8D4D-59480B391C5B}';
+
+// --- the spec these tests place grids in -----------------------------------------------------------------
+
+const specWith = (subgrids, form = {}) => ({
+ $schemaVersion: '1.0',
+ solution: { uniqueName: 'Grids', displayName: 'Grids', publisherPrefix: 'new' },
+ app: { name: 'Grids', uniqueName: 'new_grids' },
+ entities: [
+ { schemaName: 'new_ticket', displayName: 'Ticket', pluralName: 'Tickets', primaryAttribute: { schemaName: 'new_name', displayName: 'Name' },
+ columns: [{ schemaName: 'new_code', displayName: 'Code', type: 'Text' }, { schemaName: 'new_notes', displayName: 'Notes', type: 'Memo' }, { schemaName: 'new_area', displayName: 'Area', type: 'Text' }] },
+ { schemaName: 'new_task', displayName: 'Task', pluralName: 'Tasks', primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns: [] },
+ { schemaName: 'new_comment', displayName: 'Comment', pluralName: 'Comments', primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns: [] },
+ ],
+ relationships: [
+ { type: 'OneToMany', referenced: 'new_ticket', referencing: 'new_task', lookup: { schemaName: 'new_TicketId', displayName: 'Ticket' } },
+ { type: 'OneToMany', referenced: 'new_ticket', referencing: 'new_comment', lookup: { schemaName: 'new_TicketId2', displayName: 'Ticket' } },
+ ],
+ forms: [Object.assign({ entity: 'new_ticket', name: 'Main', subgrids, tabs: [
+ { name: 'tab_a', label: 'A', sections: [
+ { name: 'sec_main', label: 'Main', columns: 2, fields: ['new_name', 'new_code'] },
+ { name: 'sec_more', label: 'More', columns: 1, fields: ['new_notes'] },
+ ] },
+ { name: 'tab_b', label: 'B', sections: [{ name: 'sec_b', label: 'B', columns: 1, fields: ['new_area'] }] },
+ ] }, form)],
+ appShell: { areas: [{ label: 'M', groups: [{ label: 'G', subAreas: [{ entity: 'new_ticket', title: 'Tickets' }] }] }] },
+});
+const twoColumnTab = () => ({ tabs: [{ name: 'tab_a', label: 'A', columns: [
+ { width: '50%', sections: [{ name: 'sec_left', label: 'Left', columns: 1, fields: ['new_name', 'new_code'] }] },
+ { width: '50%', sections: [{ name: 'sec_right', label: 'Right', columns: 1, fields: ['new_notes', 'new_area'] }] },
+] }] });
+const autoForm = (subgrids) => { const s = specWith(subgrids); delete s.forms[0].tabs; return s; };
+
+// --- the pure rules ---------------------------------------------------------------------------------------
+
+test('placement: placementOf reads the four keys, lower-cased, and ignores what is not a name or a whole number', () => {
+ assert.deepStrictEqual(placement.placementOf({ childEntity: 'new_task', tab: ' Tab_A ', column: 1, after: 'SEC_Main' }), { tab: 'tab_a', column: 1, after: 'sec_main' });
+ assert.deepStrictEqual(placement.placementOf({ childEntity: 'new_task', before: 'sec_more' }), { before: 'sec_more' });
+ // Nothing declared, or nothing usable: null — which is what keeps a spec without the keys on the original path.
+ assert.strictEqual(placement.placementOf({ childEntity: 'new_task', view: 'V', label: 'L' }), null);
+ assert.strictEqual(placement.placementOf({ childEntity: 'new_task', tab: '', after: 5, before: null, column: -1 }), null);
+ assert.strictEqual(placement.placementOf({ childEntity: 'new_task', column: 1.5 }), null);
+ assert.deepStrictEqual(placement.placementOf({ childEntity: 'new_task', column: 0 }), { column: 0 }, 'column 0 is a placement');
+ for (const bad of [null, undefined, 'x', 7, [], [{ tab: 'a' }]]) assert.strictEqual(placement.placementOf(bad), null);
+});
+
+const LAYOUT = [
+ { name: 'tab_a', columns: [{ sections: ['sec_main', 'sec_more'] }, { sections: ['sec_side'] }] },
+ { name: 'tab_b', columns: [{ sections: ['sec_b'] }] },
+];
+
+test('placement: resolvePlacement finds the tab, form-column and anchor a placement names', () => {
+ assert.deepStrictEqual(placement.resolvePlacement(LAYOUT, { after: 'sec_main' }), { ok: true, tabIndex: 0, columnIndex: 0, createColumn: 0, anchor: { name: 'sec_main', side: 'after' } });
+ assert.deepStrictEqual(placement.resolvePlacement(LAYOUT, { before: 'sec_side' }), { ok: true, tabIndex: 0, columnIndex: 1, createColumn: 1, anchor: { name: 'sec_side', side: 'before' } });
+ assert.deepStrictEqual(placement.resolvePlacement(LAYOUT, { after: 'sec_b', tab: 'tab_b', column: 0 }), { ok: true, tabIndex: 1, columnIndex: 0, createColumn: 0, anchor: { name: 'sec_b', side: 'after' } });
+ // A tab (and column) only: membership of the tab; the column is `undefined` — any of them — until one is named.
+ assert.deepStrictEqual(placement.resolvePlacement(LAYOUT, { tab: 'tab_b' }), { ok: true, tabIndex: 1, columnIndex: undefined, createColumn: 0, anchor: null });
+ assert.deepStrictEqual(placement.resolvePlacement(LAYOUT, { tab: 'tab_a', column: 1 }), { ok: true, tabIndex: 0, columnIndex: 1, createColumn: 1, anchor: null });
+ assert.deepStrictEqual(placement.resolvePlacement(LAYOUT, { column: 1 }), { ok: true, tabIndex: 0, columnIndex: 1, createColumn: 1, anchor: null }, 'the first tab when none is named');
+});
+
+test('placement: resolvePlacement says what is wrong as a code, for each way a placement can fail', () => {
+ const code = (p) => placement.resolvePlacement(LAYOUT, p).code;
+ assert.strictEqual(code({ after: 'sec_main', before: 'sec_more' }), 'both');
+ assert.strictEqual(code({ after: 'sec_nope' }), 'anchor');
+ assert.strictEqual(code({ tab: 'tab_nope' }), 'tab');
+ assert.strictEqual(code({ tab: 'tab_a', column: 2 }), 'column');
+ assert.strictEqual(code({ tab: 'tab_b', after: 'sec_main' }), 'anchor-tab');
+ assert.strictEqual(code({ column: 1, after: 'sec_main' }), 'anchor-column');
+ assert.strictEqual(placement.resolvePlacement(LAYOUT, { tab: 'tab_a', after: 'sec_main', column: 0 }).ok, true, 'a tab and column that agree with the anchor are fine');
+ assert.strictEqual(placement.resolvePlacement([], { tab: 'a' }).ok, false);
+});
+
+test('placement: columnSequence puts a grid right after / before its anchor and keeps grids that share one in declared order', () => {
+ const authored = ['a', 'b', 'c'];
+ const names = (seq) => seq.map((t) => (t.section !== undefined ? t.section : `#${t.grid}`));
+ assert.deepStrictEqual(names(placement.columnSequence(authored, [{ key: 'g1', after: 'a' }])), ['a', '#g1', 'b', 'c']);
+ assert.deepStrictEqual(names(placement.columnSequence(authored, [{ key: 'g1', before: 'a' }])), ['#g1', 'a', 'b', 'c']);
+ assert.deepStrictEqual(names(placement.columnSequence(authored, [{ key: 'g1', after: 'c' }])), ['a', 'b', 'c', '#g1']);
+ // Two grids after one section: the first declared is the first after it.
+ assert.deepStrictEqual(names(placement.columnSequence(authored, [{ key: 'g1', after: 'a' }, { key: 'g2', after: 'a' }])), ['a', '#g1', '#g2', 'b', 'c']);
+ // Two before one section: still declared order, both ahead of it.
+ assert.deepStrictEqual(names(placement.columnSequence(authored, [{ key: 'g1', before: 'b' }, { key: 'g2', before: 'b' }])), ['a', '#g1', '#g2', 'b', 'c']);
+ assert.deepStrictEqual(names(placement.columnSequence(authored, [{ key: 'g1', after: 'a' }, { key: 'g2', before: 'c' }, { key: 'g3', after: 'b' }])), ['a', '#g1', 'b', '#g3', '#g2', 'c']);
+ // An anchor this column does not hold (the spec gate refuses it) is not a reason to lose the grid.
+ assert.deepStrictEqual(names(placement.columnSequence(authored, [{ key: 'g1', after: 'zzz' }])), ['a', 'b', 'c', '#g1']);
+ assert.deepStrictEqual(names(placement.columnSequence(authored, [])), ['a', 'b', 'c']);
+});
+
+test('placement: neighbourOf names the token an anchored grid must sit directly beside — the nearest toward its anchor that is on the form', () => {
+ const seq = placement.columnSequence(['a', 'b', 'c'], [{ key: 'g1', after: 'a' }, { key: 'g2', after: 'a' }, { key: 'g3', before: 'c' }, { key: 'g4', before: 'c' }]);
+ const nameOf = (t) => (t.section !== undefined ? t.section : t.grid);
+ assert.deepStrictEqual(seq.map(nameOf), ['a', 'g1', 'g2', 'b', 'g3', 'g4', 'c']);
+ const near = (key, absent = []) => {
+ const hit = placement.neighbourOf(seq, key, (t) => !absent.includes(nameOf(t)));
+ return hit && `${nameOf(hit.token)}:${hit.side}`;
+ };
+ // An `after` grid sits behind the one declared before it, which sits behind the anchor…
+ assert.strictEqual(near('g1'), 'a:after');
+ assert.strictEqual(near('g2'), 'g1:after');
+ // …and a `before` grid in front of the one declared after it, which sits in front of the anchor.
+ assert.strictEqual(near('g4'), 'c:before');
+ assert.strictEqual(near('g3'), 'g4:before');
+ // A grid the form does not have is not a neighbour: the next one toward the anchor is.
+ assert.strictEqual(near('g2', ['g1']), 'a:after');
+ assert.strictEqual(near('g3', ['g4']), 'c:before');
+ // Nothing toward the anchor on the form — the anchor itself is missing — or a grid the sequence does not hold.
+ assert.strictEqual(near('g1', ['a']), null);
+ assert.strictEqual(near('g4', ['c']), null);
+ assert.strictEqual(near('g9'), null);
+ assert.strictEqual(placement.neighbourOf([], 'g1', () => true), null);
+});
+
+const gridControl = (rel, shape) => (shape === 'xml'
+ ? { classId: SUBGRID_CLASS, relationshipName: rel }
+ : { classId: SUBGRID_CLASS.replace(/[{}]/g, ''), parameters: { RelationshipName: rel } });
+const treeOf = (shape) => [{ columns: [{ sections: [
+ { name: 'sec_main', rows: [{ cells: [{ control: { classId: '{4273EDBD-AC1D-40D3-9FB2-095C621B552D}', fieldName: 'new_name' } }] }] },
+ { name: 'maker_grid', rows: [{ cells: [{ control: gridControl('new_ticket_new_task', shape) }] }] },
+ { name: 'section_grid_new_ticket_new_task', rows: [{ cells: [{ control: gridControl('NEW_Ticket_New_Task', shape) }] }] },
+ { name: 'section_grid_new_ticket_new_comment', rows: [{ cells: [{ control: gridControl('new_ticket_new_comment', shape) }] }] },
+] }] }];
+
+for (const shape of ['sdk', 'xml']) {
+ test(`placement: findGridSection finds the section holding a relationship's grid, preferring the engine's own (${shape} tree)`, () => {
+ const tabs = treeOf(shape);
+ const hit = placement.findGridSection(tabs, 'new_ticket_new_task');
+ assert.deepStrictEqual({ ti: hit.ti, ci: hit.ci, si: hit.si, engine: hit.engine }, { ti: 0, ci: 0, si: 2, engine: true }, 'the engine host wins over a maker section that holds the same relationship, whatever the case');
+ assert.strictEqual(placement.findGridSection(tabs, 'new_ticket_new_comment').si, 3);
+ assert.strictEqual(placement.findGridSection(tabs, 'new_ticket_new_other'), null);
+ // Only a section a maker made holds it: found, and said not to be the build's.
+ const onlyMaker = [{ columns: [{ sections: [tabs[0].columns[0].sections[1]] }] }];
+ const found = placement.findGridSection(onlyMaker, 'new_ticket_new_task');
+ assert.deepStrictEqual({ si: found.si, engine: found.engine }, { si: 0, engine: false });
+ // A control of another class that names the same parameter is not a grid.
+ const notAGrid = [{ columns: [{ sections: [{ name: 'x', rows: [{ cells: [{ control: Object.assign(gridControl('new_ticket_new_task', shape), { classId: '4273EDBD-AC1D-40D3-9FB2-095C621B552D' }) }] }] }] }] }];
+ assert.strictEqual(placement.findGridSection(notAGrid, 'new_ticket_new_task'), null);
+ });
+}
+
+test('placement: splitSubgrids separates the grids that say where they go from the rest, and drops a placement the layout cannot resolve', () => {
+ const layout = formLayoutNames(specWith([]).forms[0]);
+ const { placed, unplaced } = placement.splitSubgrids(layout, [
+ { childEntity: 'new_task', after: 'sec_main' },
+ { childEntity: 'new_comment' },
+ { childEntity: 'new_extra', tab: 'tab_nope' },
+ ]);
+ assert.deepStrictEqual(placed.map((p) => [p.index, p.sg.childEntity]), [[0, 'new_task']]);
+ assert.deepStrictEqual(unplaced.map((sg) => sg.childEntity), ['new_comment', 'new_extra']);
+});
+
+test('placement: columnItems draws a column in the order a build leaves it — anchored grids among the sections, the rest after the Notes section', () => {
+ const layout = [{ name: 'tab_a', columns: [{ sections: ['sec_main', 'sec_more'] }] }];
+ const compiled = [{ name: 'sec_main' }, { name: 'sec_more' }, { name: 'section_notes' }];
+ const placed = placement.splitSubgrids(layout, [
+ { childEntity: 'g_after_main', after: 'sec_main' },
+ { childEntity: 'g_tab_only', tab: 'tab_a' },
+ { childEntity: 'g_before_more', before: 'sec_more' },
+ { childEntity: 'g_unplaced' },
+ ]).placed;
+ const names = placement.columnItems(layout, 0, 0, compiled, placed).map((i) => (i.section ? i.section.name : i.subgrid.childEntity));
+ assert.deepStrictEqual(names, ['sec_main', 'g_after_main', 'g_before_more', 'sec_more', 'section_notes', 'g_tab_only']);
+ // A column nothing is placed in comes back as it is.
+ assert.deepStrictEqual(placement.columnItems(layout, 0, 1, [{ name: 'x' }], placed).map((i) => i.section.name), ['x']);
+});
+
+// The compiled column lists the sections the layout declares, in the layout's order, and then the Notes section the
+// compiler appends. A section is told from another by where it is in that list, not by its name: a layout may declare
+// a section named `section_notes` too — a natural name for a section of note fields — and a lookup by name would find
+// that one for both, dropping the Notes section the compiler added from the column, and with it the timeline a form
+// asks for.
+test('placement: columnItems tells the layout\u2019s sections from the compiler\u2019s by place, so an authored `section_notes` does not hide the Notes section', () => {
+ const layout = [{ name: 'tab_a', columns: [{ sections: ['sec_main', 'section_notes'] }] }];
+ const authoredNotes = { name: 'section_notes', which: 'authored' };
+ const compiled = [{ name: 'sec_main' }, authoredNotes, { name: 'section_notes', which: 'compiler' }];
+ const itemsFor = (subgrids) => placement.columnItems(layout, 0, 0, compiled, placement.splitSubgrids(layout, subgrids).placed);
+ const shown = (items) => items.map((i) => (i.subgrid ? `grid:${i.subgrid.childEntity}` : i.section.which || i.section.name));
+
+ assert.deepStrictEqual(shown(itemsFor([{ childEntity: 'g1', after: 'sec_main' }])), ['sec_main', 'grid:g1', 'authored', 'compiler']);
+ assert.deepStrictEqual(shown(itemsFor([{ childEntity: 'g1', after: 'section_notes' }])), ['sec_main', 'authored', 'grid:g1', 'compiler'], 'the grid goes after the layout\u2019s section, ahead of the compiler\u2019s');
+ assert.deepStrictEqual(shown(itemsFor([{ childEntity: 'g1', before: 'section_notes' }, { childEntity: 'g2', tab: 'tab_a' }])), ['sec_main', 'grid:g1', 'authored', 'compiler', 'grid:g2']);
+ // Each section is the very object the compiler made, and says whether the layout or the compiler wrote it.
+ const items = itemsFor([{ childEntity: 'g1', after: 'sec_main' }]);
+ assert.strictEqual(items[2].section, authoredNotes);
+ assert.deepStrictEqual(items.filter((i) => i.section).map((i) => i.engine), [false, false, true]);
+ assert.deepStrictEqual(placement.columnItems(layout, 0, 0, compiled, []).map((i) => i.engine), [false, false, true], 'a column nothing is placed in says so too');
+});
+
+test('placement: columnSequence says where each layout section is, which is how a compiled column is read by place', () => {
+ assert.deepStrictEqual(placement.columnSequence(['a', 'b'], [{ key: 'g', after: 'a' }]).map((t) => (t.section !== undefined ? [t.section, t.at] : ['grid', t.grid])), [['a', 0], ['grid', 'g'], ['b', 1]]);
+});
+
+test('placement: the names an auto layout is placed by are the ones the compiler gives it', () => {
+ // Pinned in both directions: placement.js writes the literals, artifact-intent.js (the compiler) writes the same ones.
+ const form = { entity: 'new_ticket', name: 'Main' };
+ const compiled = compileFormIntent(specWith([]), form, {});
+ assert.deepStrictEqual(compiled.tabs.map((t) => t.name), [placement.AUTO_TAB_NAME]);
+ assert.deepStrictEqual(compiled.tabs[0].columns[0].sections.map((s) => s.name).filter((n) => n !== 'section_notes'), [placement.AUTO_SECTION_NAME]);
+ assert.deepStrictEqual(formLayoutNames(form), [{ name: 'tab_general', columns: [{ sections: ['section_general'] }] }]);
+});
+
+test('placement: formLayoutNames names the tabs, form-columns and sections an explicit layout declares, lower-cased, generating the names the compiler would', () => {
+ const layout = formLayoutNames({ tabs: [
+ { name: 'Tab_A', columns: [{ sections: [{ name: 'Sec_One' }, {}] }, { sections: [{ name: 'sec_two' }] }] },
+ { label: 'Unnamed', sections: [{ label: 'x' }] },
+ ] });
+ assert.strictEqual(layout[0].name, 'tab_a');
+ assert.strictEqual(layout[0].columns.length, 2);
+ assert.strictEqual(layout[0].columns[0].sections[0], 'sec_one');
+ assert.match(layout[0].columns[0].sections[1], /^\S+$/, 'an unnamed section gets the generated name');
+ assert.deepStrictEqual(layout[0].columns[1].sections, ['sec_two']);
+ assert.match(layout[1].name, /^\S+$/, 'an unnamed tab gets the generated name');
+});
+
+// --- the spec gate and the lint -----------------------------------------------------------------------------
+
+const gate = (spec) => validateAppSpec(spec).errors.filter((e) => /subgrid/.test(e));
+const lint = (spec) => lintAppSpec(spec).errors.filter((e) => /subgrid/.test(e));
+
+test('spec gate: a valid placement is accepted — by validateAppSpec and the lint alike', () => {
+ const ok = [
+ [{ childEntity: 'new_task', after: 'sec_main' }],
+ [{ childEntity: 'new_task', before: 'sec_more' }],
+ [{ childEntity: 'new_task', tab: 'tab_b' }],
+ [{ childEntity: 'new_task', tab: 'tab_a', after: 'SEC_MAIN' }],
+ [{ childEntity: 'new_task', tab: 'tab_a', column: 0 }],
+ [{ childEntity: 'new_task', after: 'sec_main' }, { childEntity: 'new_comment', after: 'sec_main' }],
+ [{ childEntity: 'new_task' }],
+ ];
+ for (const subgrids of ok) {
+ const spec = specWith(subgrids);
+ assert.deepStrictEqual(validateAppSpec(spec).errors, [], JSON.stringify(subgrids));
+ assert.deepStrictEqual(lintAppSpec(spec).errors, [], JSON.stringify(subgrids));
+ }
+ const twoCols = specWith([{ childEntity: 'new_task', tab: 'tab_a', column: 1 }], twoColumnTab());
+ assert.deepStrictEqual(validateAppSpec(twoCols).errors, []);
+ const afterRight = specWith([{ childEntity: 'new_task', after: 'sec_right', column: 1 }], twoColumnTab());
+ assert.deepStrictEqual(validateAppSpec(afterRight).errors, []);
+ // An auto layout is one tab, `tab_general`, holding one section, `section_general`.
+ for (const sg of [{ after: 'section_general' }, { before: 'section_general' }, { tab: 'tab_general' }, { tab: 'tab_general', column: 0 }]) {
+ const spec = autoForm([Object.assign({ childEntity: 'new_task' }, sg)]);
+ assert.deepStrictEqual(validateAppSpec(spec).errors, [], JSON.stringify(sg));
+ assert.deepStrictEqual(lintAppSpec(spec).errors, [], JSON.stringify(sg));
+ }
+});
+
+const INVALID = [
+ ['an anchor section the form does not declare', { childEntity: 'new_task', after: 'sec_nope' }, /places the grid after section 'sec_nope', which this form does not declare \(its sections: sec_main, sec_more, sec_b\)/],
+ ['a before-anchor the form does not declare', { childEntity: 'new_task', before: 'sec_nope' }, /places the grid before section 'sec_nope', which this form does not declare/],
+ ['after and before together', { childEntity: 'new_task', after: 'sec_main', before: 'sec_more' }, /sets both 'after' and 'before' — give one/],
+ ['a tab the form does not declare', { childEntity: 'new_task', tab: 'tab_nope' }, /places the grid in tab 'tab_nope', which this form does not declare \(its tabs: tab_a, tab_b\)/],
+ ['a form-column the tab does not have', { childEntity: 'new_task', tab: 'tab_a', column: 3 }, /places the grid in column 3 of tab 'tab_a', which has 1 form-column\(s\) — count from 0/],
+ ['an anchor in another tab than the one named', { childEntity: 'new_task', tab: 'tab_b', after: 'sec_main' }, /after section 'sec_main', which is in tab 'tab_a', not in tab 'tab_b'/],
+ ['an anchor in another form-column than the one named', { childEntity: 'new_task', after: 'sec_main', column: 1 }, /after section 'sec_main', which is in form-column 0 of its tab, not 1/],
+ ['a tab that is not a string', { childEntity: 'new_task', tab: 5 }, /has tab 5 — it must be the name of a tab on this form, as a non-empty string/],
+ ['an anchor that is not a string', { childEntity: 'new_task', after: ['sec_main'] }, /has after \["sec_main"\] — it must be the name of a section on this form, as a non-empty string/],
+ ['an empty before-anchor', { childEntity: 'new_task', before: ' ' }, /has before " " — it must be the name of a section/],
+ ['a column that is not a whole number', { childEntity: 'new_task', tab: 'tab_a', column: 1.5 }, /has column 1.5 — it must be a whole number from 0/],
+ ['a negative column', { childEntity: 'new_task', tab: 'tab_a', column: -1 }, /has column -1 — it must be a whole number from 0/],
+];
+
+for (const [label, subgrid, message] of INVALID) {
+ test(`spec gate: ${label} is an error, and the lint says the same`, () => {
+ const spec = specWith([subgrid]);
+ const errors = gate(spec);
+ assert.strictEqual(errors.length, 1, JSON.stringify(errors));
+ assert.match(errors[0], /^form new_ticket: subgrid 'new_task' /);
+ assert.match(errors[0], message);
+ assert.deepStrictEqual(lint(spec), [`Form new_ticket ${errors[0].slice('form new_ticket: '.length)}`], 'the lint reports the same problem, worded for the same form');
+ assert.strictEqual(validateAppSpec(spec).ok, false);
+ });
+}
+
+test('spec gate: an auto layout is placed only by the names it has, and the message says so', () => {
+ const spec = autoForm([{ childEntity: 'new_task', after: 'sec_main' }]);
+ const [error] = gate(spec);
+ assert.match(error, /places the grid after section 'sec_main', which this form does not declare \(its sections: section_general\) \(an auto layout has the one tab 'tab_general' holding the one section 'section_general' — declare tabs\[\] for more\)/);
+ assert.match(gate(autoForm([{ childEntity: 'new_task', tab: 'tab_a' }]))[0], /tab 'tab_a', which this form does not declare \(its tabs: tab_general\) \(an auto layout/);
+});
+
+test('spec gate: a grid placed in the second form-column of its tab is judged against that form-column\'s sections', () => {
+ const spec = specWith([{ childEntity: 'new_task', after: 'sec_left', column: 1 }], twoColumnTab());
+ assert.match(gate(spec)[0], /after section 'sec_left', which is in form-column 0 of its tab, not 1/);
+});
+
+test('spec gate: every grid of a form is judged, each by its own entry', () => {
+ const spec = specWith([{ childEntity: 'new_task', after: 'sec_nope' }, { childEntity: 'new_comment', tab: 'tab_nope' }]);
+ const errors = gate(spec);
+ assert.strictEqual(errors.length, 2);
+ assert.match(errors[0], /subgrid 'new_task'/);
+ assert.match(errors[1], /subgrid 'new_comment'/);
+});
+
+// A form holds ONE grid per relationship: the build finds a grid by it, and an entry whose grid is already there adds
+// nothing. So of two entries for one relationship only one can say where the grid goes, and the other's placement could
+// never be honoured — silently, and `--verify` could not tell. Refused when an entry places the grid: those keys are new,
+// so no spec that built before is turned away. A repeat that places nothing is what specs have always been able to carry
+// (the build has always ignored the extra), so it is only a warning.
+const dupes = (spec) => validateAppSpec(spec).errors.filter((e) => /more than once/.test(e));
+const dupeWarnings = (spec) => validateAppSpec(spec).warnings.filter((w) => /more than once/.test(w));
+
+for (const [label, subgrids] of [
+ ['two placements that disagree', [{ childEntity: 'new_task', after: 'sec_main' }, { childEntity: 'new_task', after: 'sec_more' }]],
+ ['a placement and a plain repeat after it', [{ childEntity: 'new_task', after: 'sec_main' }, { childEntity: 'new_task' }]],
+ ['a plain entry and a placement after it', [{ childEntity: 'new_task' }, { childEntity: 'new_task', before: 'sec_more' }]],
+ ['the same placement twice', [{ childEntity: 'new_task', tab: 'tab_b' }, { childEntity: 'new_task', tab: 'tab_b' }]],
+ ['the same table spelled in another case', [{ childEntity: 'new_task', after: 'sec_main' }, { childEntity: 'NEW_Task', after: 'sec_more' }]],
+]) {
+ test(`spec gate: a relationship listed twice is an error when an entry places the grid — ${label} — and the lint says the same`, () => {
+ const spec = specWith(subgrids);
+ const errors = dupes(spec);
+ assert.strictEqual(errors.length, 1, JSON.stringify(validateAppSpec(spec).errors));
+ assert.match(errors[0], /^form new_ticket: subgrids lists the sub-grid for 'new_task' more than once \(subgrids\[0\], subgrids\[1\]\) — a form holds one grid per relationship, so only one entry can say where it goes; keep one$/);
+ assert.deepStrictEqual(lintAppSpec(spec).errors.filter((e) => /more than once/.test(e)), [`Form new_ticket ${errors[0].slice('form new_ticket: '.length)}`], 'the lint reports the same problem, worded for the same form');
+ assert.strictEqual(validateAppSpec(spec).ok, false);
+ assert.strictEqual(lintAppSpec(spec).ok, false);
+ assert.deepStrictEqual(dupeWarnings(spec), [], 'one message, not an error and a warning');
+ });
+}
+
+test('spec gate: a relationship listed twice with no placement is a warning — the spec built before, and the build has always ignored the extra entry', () => {
+ const spec = specWith([{ childEntity: 'new_task', view: 'Active' }, { childEntity: 'new_comment' }, { childEntity: 'new_task', label: 'Other' }]);
+ assert.deepStrictEqual(dupes(spec), []);
+ assert.deepStrictEqual(dupeWarnings(spec), ["form new_ticket: subgrids lists the sub-grid for 'new_task' more than once (subgrids[0], subgrids[2]) — a form holds one grid per relationship, so the build adds one and ignores the rest"]);
+ assert.strictEqual(validateAppSpec(spec).ok, true);
+ assert.deepStrictEqual(lintAppSpec(spec).warnings.filter((w) => /more than once/.test(w)), ["Form new_ticket subgrids lists the sub-grid for 'new_task' more than once (subgrids[0], subgrids[2]) — a form holds one grid per relationship, so the build adds one and ignores the rest"]);
+ assert.strictEqual(lintAppSpec(spec).ok, true);
+});
+
+test('spec gate: different tables, a table with no relationship, and a form that cannot host grids at all are not "listed twice"', () => {
+ assert.deepStrictEqual(dupes(specWith([{ childEntity: 'new_task', after: 'sec_main' }, { childEntity: 'new_comment', after: 'sec_main' }])), []);
+ const none = specWith([{ childEntity: 'new_ticket', after: 'sec_main' }, { childEntity: 'new_ticket', after: 'sec_more' }]); // no relationship from a ticket to a ticket
+ assert.deepStrictEqual(dupes(none), [], 'the missing relationship is its own error');
+ assert.ok(validateAppSpec(none).errors.some((e) => /no OneToMany or ManyToMany relationship/.test(e)));
+ const quick = specWith([{ childEntity: 'new_task', after: 'sec_main' }, { childEntity: 'new_task', after: 'sec_more' }], { formType: 'QuickCreate' });
+ assert.deepStrictEqual(dupes(quick), [], 'a QuickCreate form already fails for hosting a grid at all');
+ assert.deepStrictEqual(lintAppSpec(quick).errors.filter((e) => /more than once/.test(e)), []);
+});
+
+test('spec gate: a placement on a form that is not a Main form adds nothing to the error that form already gets for hosting a grid', () => {
+ const spec = specWith([{ childEntity: 'new_task', after: 'sec_nope', tab: 5 }], { formType: 'QuickCreate' });
+ const errors = validateAppSpec(spec).errors.filter((e) => /sub-?grid/i.test(e));
+ assert.strictEqual(errors.length, 1, JSON.stringify(errors));
+ assert.match(errors[0], /QuickCreate forms can't host sub-grids \(Main forms only\)/);
+ assert.doesNotMatch(errors[0], /sec_nope|has tab/);
+ const linted = lintAppSpec(spec).errors.filter((e) => /sub-?grid/i.test(e));
+ assert.strictEqual(linted.length, 1, JSON.stringify(linted));
+ assert.match(linted[0], /sub-grids are Main-form only/);
+});
+
+test('spec gate: a spec without placement keys is judged exactly as it was', () => {
+ const spec = specWith([{ childEntity: 'new_task', view: 'Tasks', label: 'Tasks' }, { childEntity: 'new_comment' }]);
+ assert.deepStrictEqual(validateAppSpec(spec).errors, []);
+ assert.deepStrictEqual(lintAppSpec(spec).errors, []);
+ assert.deepStrictEqual(validateAppSpec(spec).warnings, []);
+ assert.deepStrictEqual(subgridPlacementProblems(spec.forms[0], spec.forms[0].subgrids[0]), []);
+ assert.deepStrictEqual(subgridPlacementProblems(spec.forms[0], null), []);
+});
+
+test('spec gate: a key nothing reads on a sub-grid is a warning, naming the key it probably meant — in the gate and the lint alike', () => {
+ const spec = specWith([{ childEntity: 'new_task', afterSection: 'sec_main', View: 'Tasks', Column: 1, position: 'top' }]);
+ const hint = (key, meant) => `subgrid 'new_task' has the key '${key}', which nothing reads${meant ? ` — did you mean '${meant}'?` : ''} (the keys are childEntity, view, label, tab, column, after, before)`;
+ const expected = [hint('afterSection', 'after'), hint('View', 'view'), hint('Column', 'column'), hint('position')];
+ assert.deepStrictEqual(validateAppSpec(spec).warnings.filter((w) => /has the key/.test(w)), expected.map((m) => `form new_ticket: ${m}`));
+ assert.deepStrictEqual(lintAppSpec(spec).warnings.filter((w) => /has the key/.test(w)), expected.map((m) => `Form new_ticket ${m}`));
+ // A warning, never an error: entries written before the keys existed may carry extras the build never read.
+ assert.strictEqual(validateAppSpec(spec).ok, true);
+ assert.strictEqual(lintAppSpec(spec).ok, true);
+ // Every key the entry does read is silent.
+ const known = specWith([{ childEntity: 'new_task', view: 'V', label: 'L', tab: 'tab_a', column: 0, after: 'sec_main' }]);
+ assert.deepStrictEqual(validateAppSpec(known).warnings.filter((w) => /has the key/.test(w)), []);
+ assert.deepStrictEqual(lintAppSpec(known).warnings.filter((w) => /has the key/.test(w)), []);
+});
+
+test('spec gate: subgridRelationshipName names the 1:N a grid shows, and null when the two tables have none', () => {
+ const spec = specWith([]);
+ assert.strictEqual(subgridRelationshipName(spec, 'new_ticket', 'new_task'), 'new_ticket_new_task');
+ assert.strictEqual(subgridRelationshipName(spec, 'NEW_TICKET', 'New_Comment'), 'new_ticket_new_comment');
+ assert.strictEqual(subgridRelationshipName(spec, 'new_task', 'new_ticket'), null);
+});
+
+// --- --verify -----------------------------------------------------------------------------------------------
+
+// A deployed form as the read-back gives it: the sections of each form-column of each tab, each section holding a
+// bound field or a sub-grid. Only what verify reads: names, labels, the grid's class id and RelationshipName.
+const field = (name) => `<cell><control datafieldname="${name}" /></cell>`;
+const grid = (rel) => `<cell><control id="g" classid="${SUBGRID_CLASS}" disabled="false" isrequired="false"><parameters><TargetEntityType>x</TargetEntityType><RelationshipName>${rel}</RelationshipName></parameters></control></cell>`;
+const sectionXml = (name, cell, label) => `<section name="${name}"${label ? '' : ''}><labels><label description="${label || name}" languagecode="1033" /></labels><rows><row>${cell}</row></rows></section>`;
+const gridSection = (rel, name) => sectionXml(name || `section_grid_${rel}`, grid(rel), rel);
+const column = (...sections) => `<column width="100%"><sections>${sections.join('')}</sections></column>`;
+const tabXml = (name, ...columns) => `<tab name="${name}"><labels><label description="${name}" languagecode="1033" /></labels><columns>${columns.join('')}</columns></tab>`;
+const formXml = (...tabs) => `<form><tabs>${tabs.join('')}</tabs></form>`;
+const MAIN = sectionXml('sec_main', field('new_name') + field('new_code'), 'Main');
+const MORE = sectionXml('sec_more', field('new_notes'), 'More');
+const SEC_B = sectionXml('sec_b', field('new_area'), 'B');
+const TASK = 'new_ticket_new_task';
+const COMMENT = 'new_ticket_new_comment';
+
+const readerFor = (xml) => ({
+ findTable: async () => ({ logicalName: 'new_ticket' }),
+ findColumns: async () => [{ logicalName: 'new_name' }, { logicalName: 'new_code' }, { logicalName: 'new_notes' }, { logicalName: 'new_area' }],
+ sitemapXml: async () => '',
+ queryRecords: async (set) => (set === 'systemform' ? [{ formid: 'f1', name: 'Main', objecttypecode: 'new_ticket', type: 2, isdefault: true }] : []),
+ formTopology: async () => xml,
+});
+const gridChecks = async (spec, xml) => (await verifySpec(spec, readerFor(xml))).checks.filter((c) => c.kind === 'form-subgrid');
+
+test('verify: a grid directly after its anchor passes; the same grid anywhere else fails and says where it is', async () => {
+ const spec = specWith([{ childEntity: 'new_task', after: 'sec_main' }]);
+ const right = await gridChecks(spec, formXml(tabXml('tab_a', column(MAIN, gridSection(TASK), MORE)), tabXml('tab_b', column(SEC_B))));
+ assert.deepStrictEqual(right.map((c) => [c.name, c.present, c.detail]), [['new_ticket.Main: sub-grid new_task', true, '']]);
+
+ const atEnd = await gridChecks(spec, formXml(tabXml('tab_a', column(MAIN, MORE, gridSection(TASK))), tabXml('tab_b', column(SEC_B))));
+ assert.strictEqual(atEnd[0].present, false);
+ assert.match(atEnd[0].detail, /deployed where the spec does not place it — the grid is not directly after section 'sec_main' in tab 'tab_a' form-column 1: 'sec_more' sits between them/);
+
+ const otherTab = await gridChecks(spec, formXml(tabXml('tab_a', column(MAIN, MORE)), tabXml('tab_b', column(SEC_B, gridSection(TASK)))));
+ assert.strictEqual(otherTab[0].present, false);
+ assert.match(otherTab[0].detail, /the grid is in tab 'tab_b' form-column 1, but the spec places it after section 'sec_main', in tab 'tab_a' form-column 1/);
+
+ const above = await gridChecks(spec, formXml(tabXml('tab_a', column(gridSection(TASK), MAIN, MORE)), tabXml('tab_b', column(SEC_B))));
+ assert.match(above[0].detail, /the grid is above section 'sec_main' in tab 'tab_a' form-column 1, but the spec places it directly after it/);
+});
+
+// "Directly" means nothing sits between the grid and its anchor — not the Notes section a build appends to the end of
+// the first tab, and not a section a maker added. A form an earlier version built has the grid BEHIND the Notes
+// section, which is not where a fresh build puts it.
+test('verify: a section between a grid and its anchor — the Notes section, or a maker\u2019s own — is a grid not placed', async () => {
+ const spec = specWith([{ childEntity: 'new_task', after: 'sec_more' }]);
+ const notes = sectionXml('section_notes', `<cell><control id="notescontrol" classid="{06375649-C143-495E-A496-C962E5B4488E}" /></cell>`, 'Notes');
+ const behindNotes = await gridChecks(spec, formXml(tabXml('tab_a', column(MAIN, MORE, notes, gridSection(TASK))), tabXml('tab_b', column(SEC_B))));
+ assert.strictEqual(behindNotes[0].present, false);
+ assert.match(behindNotes[0].detail, /the grid is not directly after section 'sec_more' in tab 'tab_a' form-column 1: 'section_notes' sits between them/);
+ const beforeNotes = await gridChecks(spec, formXml(tabXml('tab_a', column(MAIN, MORE, gridSection(TASK), notes)), tabXml('tab_b', column(SEC_B))));
+ assert.strictEqual(beforeNotes[0].present, true, beforeNotes[0].detail);
+
+ const maker = sectionXml('maker_section', field('new_area'), 'Maker');
+ const two = await gridChecks(spec, formXml(tabXml('tab_a', column(MAIN, MORE, maker, notes, gridSection(TASK))), tabXml('tab_b', column(SEC_B))));
+ assert.match(two[0].detail, /'maker_section', 'section_notes' sit between them/);
+
+ const before = specWith([{ childEntity: 'new_task', before: 'sec_more' }]);
+ const notDirectly = await gridChecks(before, formXml(tabXml('tab_a', column(MAIN, gridSection(TASK), maker, MORE)), tabXml('tab_b', column(SEC_B))));
+ assert.match(notDirectly[0].detail, /the grid is not directly before section 'sec_more' in tab 'tab_a' form-column 1: 'maker_section' sits between them/);
+ const below = await gridChecks(before, formXml(tabXml('tab_a', column(MAIN, MORE, gridSection(TASK))), tabXml('tab_b', column(SEC_B))));
+ assert.match(below[0].detail, /the grid is below section 'sec_more' in tab 'tab_a' form-column 1, but the spec places it directly before it/);
+});
+
+test('verify: a grid the build would move says to run a FULL build; one in a section a maker made says what the maker has to do', async () => {
+ const spec = specWith([{ childEntity: 'new_task', after: 'sec_main' }]);
+ const engine = (await gridChecks(spec, formXml(tabXml('tab_a', column(MAIN, MORE, gridSection(TASK))), tabXml('tab_b', column(SEC_B)))))[0];
+ assert.strictEqual(engine.present, false);
+ // --changed-only skips a spec that has not changed, so a form an older build left never reaches the fix by it.
+ assert.match(engine.detail, /— run a full build of the spec \(not --changed-only, which skips a spec that has not changed\) to move it$/);
+
+ const maker = (await gridChecks(spec, formXml(tabXml('tab_a', column(MAIN, MORE, gridSection(TASK, 'maker_grid'))), tabXml('tab_b', column(SEC_B)))))[0];
+ assert.strictEqual(maker.present, false);
+ assert.match(maker.detail, /— it sits in a section a build did not create, so a build leaves it there — move that section in the maker, or delete it to let a build place a grid of its own$/);
+ assert.doesNotMatch(maker.detail, /full build/, 'a full build would not move it, so it is not what the maker is told to do');
+});
+
+test('verify: a grid that is not on the form at all is reported by the relationship it should show', async () => {
+ const spec = specWith([{ childEntity: 'new_task', after: 'sec_main' }]);
+ const [check] = await gridChecks(spec, formXml(tabXml('tab_a', column(MAIN, MORE)), tabXml('tab_b', column(SEC_B))));
+ assert.strictEqual(check.present, false);
+ assert.match(check.detail, /the grid for relationship new_ticket_new_task is not on the deployed form/);
+});
+
+// The spec gate refuses a relationship listed twice with a placement, but verify is also a library: a spec that reached it
+// without the gate must not pass an entry the build could not honour. The grid sits where the FIRST entry puts it.
+test('verify: a relationship listed twice fails for the entry after the first, whatever the form holds — never a second pass', async () => {
+ const spec = specWith([{ childEntity: 'new_task', after: 'sec_main' }, { childEntity: 'new_task', after: 'sec_more' }]);
+ const checks = await gridChecks(spec, formXml(tabXml('tab_a', column(MAIN, gridSection(TASK), MORE)), tabXml('tab_b', column(SEC_B))));
+ assert.deepStrictEqual(checks.map((c) => [c.name, c.present]), [['new_ticket.Main: sub-grid new_task', true], ['new_ticket.Main: sub-grid new_task', false]]);
+ assert.match(checks[1].detail, /^the sub-grid for new_ticket_new_task is listed more than once, and a form holds one grid per relationship — only the first entry's placement is checked$/);
+ const elsewhere = await gridChecks(spec, formXml(tabXml('tab_a', column(MAIN, MORE, gridSection(TASK))), tabXml('tab_b', column(SEC_B))));
+ assert.deepStrictEqual(elsewhere.map((c) => c.present), [false, false]);
+});
+
+test('verify: before-anchors, shared anchors and several grids are each checked to sit directly beside what the spec names', async () => {
+ const spec = specWith([{ childEntity: 'new_task', after: 'sec_main' }, { childEntity: 'new_comment', after: 'sec_main' }, { childEntity: 'new_extra_none', tab: 'tab_b' }]);
+ // new_extra_none has no relationship, so it is never placed and never judged.
+ const inOrder = await gridChecks(spec, formXml(tabXml('tab_a', column(MAIN, gridSection(TASK), gridSection(COMMENT), MORE)), tabXml('tab_b', column(SEC_B))));
+ assert.deepStrictEqual(inOrder.map((c) => c.present), [true, true]);
+ const swapped = await gridChecks(spec, formXml(tabXml('tab_a', column(MAIN, gridSection(COMMENT), gridSection(TASK), MORE)), tabXml('tab_b', column(SEC_B))));
+ assert.deepStrictEqual(swapped.map((c) => c.present), [false, false], 'a grid declared later that sits ahead of the one declared before it, and the one it now keeps from the anchor');
+ assert.match(swapped[0].detail, /the grid is not directly after section 'sec_main' in tab 'tab_a' form-column 1: 'section_grid_new_ticket_new_comment' sits between them/);
+ assert.match(swapped[1].detail, /the grid is above sub-grid 'new_task' in tab 'tab_a' form-column 1, but the spec places it directly after it/);
+ // A grid declared later sits against the one declared before it, so a section between them is a problem too.
+ const apart = await gridChecks(spec, formXml(tabXml('tab_a', column(MAIN, gridSection(TASK), MORE, gridSection(COMMENT))), tabXml('tab_b', column(SEC_B))));
+ assert.deepStrictEqual(apart.map((c) => c.present), [true, false]);
+ assert.match(apart[1].detail, /the grid is not directly after sub-grid 'new_task' in tab 'tab_a' form-column 1: 'sec_more' sits between them/);
+
+ const before = specWith([{ childEntity: 'new_task', before: 'sec_main' }]);
+ assert.strictEqual((await gridChecks(before, formXml(tabXml('tab_a', column(gridSection(TASK), MAIN, MORE)), tabXml('tab_b', column(SEC_B)))))[0].present, true);
+ assert.strictEqual((await gridChecks(before, formXml(tabXml('tab_a', column(MAIN, gridSection(TASK), MORE)), tabXml('tab_b', column(SEC_B)))))[0].present, false);
+
+ // Two grids before one section: the one declared last sits against it, the one declared first in front of that.
+ const both = specWith([{ childEntity: 'new_task', before: 'sec_more' }, { childEntity: 'new_comment', before: 'sec_more' }]);
+ assert.deepStrictEqual((await gridChecks(both, formXml(tabXml('tab_a', column(MAIN, gridSection(TASK), gridSection(COMMENT), MORE)), tabXml('tab_b', column(SEC_B))))).map((c) => c.present), [true, true]);
+ assert.deepStrictEqual((await gridChecks(both, formXml(tabXml('tab_a', column(MAIN, gridSection(COMMENT), gridSection(TASK), MORE)), tabXml('tab_b', column(SEC_B))))).map((c) => c.present), [false, false]);
+});
+
+test('verify: a tab-only placement is a question of which tab (and form-column) holds the grid, not of its place in it', async () => {
+ const spec = specWith([{ childEntity: 'new_task', tab: 'tab_b' }]);
+ assert.strictEqual((await gridChecks(spec, formXml(tabXml('tab_a', column(MAIN, MORE)), tabXml('tab_b', column(gridSection(TASK), SEC_B)))))[0].present, true, 'anywhere in the tab');
+ const wrong = (await gridChecks(spec, formXml(tabXml('tab_a', column(MAIN, MORE, gridSection(TASK))), tabXml('tab_b', column(SEC_B)))))[0];
+ assert.strictEqual(wrong.present, false);
+ assert.match(wrong.detail, /the grid is in tab 'tab_a', but the spec places it in tab 'tab_b'/);
+
+ const twoCols = specWith([{ childEntity: 'new_task', tab: 'tab_a', column: 1 }], twoColumnTab());
+ const left = sectionXml('sec_left', field('new_name') + field('new_code'), 'Left');
+ const right = sectionXml('sec_right', field('new_notes') + field('new_area'), 'Right');
+ assert.strictEqual((await gridChecks(twoCols, formXml(tabXml('tab_a', column(left), column(right, gridSection(TASK))))))[0].present, true);
+ const inFirst = (await gridChecks(twoCols, formXml(tabXml('tab_a', column(left, gridSection(TASK)), column(right)))))[0];
+ assert.strictEqual(inFirst.present, false);
+ assert.match(inFirst.detail, /the grid is in form-column 1 of tab 'tab_a', but the spec places it in form-column 2/);
+});
+
+test('verify: an anchor the deployed form no longer has makes the placement unprovable — a failure, not a skip', async () => {
+ const spec = specWith([{ childEntity: 'new_task', after: 'sec_main' }]);
+ const [check] = await gridChecks(spec, formXml(tabXml('tab_a', column(MORE, gridSection(TASK))), tabXml('tab_b', column(SEC_B))));
+ assert.strictEqual(check.present, false);
+ assert.match(check.detail, /its anchor section 'sec_main' is not on the deployed form, so where the grid sits cannot be proven/);
+});
+
+test('verify: an anchor the build matched by label under another name is the anchor, as it is for every other placement', async () => {
+ const spec = specWith([{ childEntity: 'new_task', after: 'sec_main' }]);
+ const renamed = sectionXml('renamed_in_designer', field('new_name') + field('new_code'), 'Main');
+ const [check] = await gridChecks(spec, formXml(tabXml('tab_a', column(renamed, gridSection(TASK), MORE)), tabXml('tab_b', column(SEC_B))));
+ assert.strictEqual(check.present, true, check.detail);
+});
+
+test('verify: an auto layout is checked by the names the compiler gives it', async () => {
+ const spec = autoForm([{ childEntity: 'new_task', before: 'section_general' }]);
+ const general = sectionXml('section_general', field('new_name') + field('new_code'), 'Details');
+ const good = await gridChecks(spec, formXml(tabXml('tab_general', column(gridSection(TASK), general))));
+ assert.deepStrictEqual(good.map((c) => c.present), [true]);
+ const bad = await gridChecks(spec, formXml(tabXml('tab_general', column(general, gridSection(TASK)))));
+ assert.strictEqual(bad[0].present, false);
+ const missing = await gridChecks(spec, formXml(tabXml('tab_general', column(sectionXml('details', field('new_name'), 'Details'), gridSection(TASK)))));
+ assert.match(missing[0].detail, /its anchor section 'section_general' is not on the deployed form/);
+});
+
+test('verify: a spec whose grids place nothing gets no placement check, and a grid a maker moved is not held to a place the spec never named', async () => {
+ const spec = specWith([{ childEntity: 'new_task' }, { childEntity: 'new_comment', label: 'Comments' }]);
+ const xml = formXml(tabXml('tab_a', column(MAIN, gridSection(COMMENT), MORE)), tabXml('tab_b', column(SEC_B, gridSection(TASK))));
+ assert.deepStrictEqual(await gridChecks(spec, xml), []);
+});
+
+test('verify: a relationship name read from the FormXML is read as text, whatever its case or surrounding space', async () => {
+ const spec = specWith([{ childEntity: 'new_task', after: 'sec_main' }]);
+ const cell = `<cell><control id="g" classid="${SUBGRID_CLASS.toLowerCase()}"><parameters><relationshipname>\n NEW_Ticket_New_Task\n</relationshipname></parameters></control></cell>`;
+ const [check] = await gridChecks(spec, formXml(tabXml('tab_a', column(MAIN, sectionXml('section_grid_new_ticket_new_task', cell, 'Tasks'), MORE)), tabXml('tab_b', column(SEC_B))));
+ assert.strictEqual(check.present, true, check.detail);
+});
+
+// --- the wireframe and the plan -----------------------------------------------------------------------------
+
+const PREVIEW_SPEC = () => specWith([{ childEntity: 'new_task', after: 'sec_main' }, { childEntity: 'new_comment', tab: 'tab_b' }, { childEntity: 'new_other', label: 'Others' }], { notes: true });
+const PREVIEW_LINES = (spec) => renderFormWireframe(spec, spec.forms[0]).split('\n').map((l) => l.replace(/^│ /, '').replace(/ ?[┄]*\s*│$/, '').trimEnd());
+
+test('wireframe: a grid that says where it goes is drawn there, among the sections; the others stay in the Sub-grids block', () => {
+ const spec = PREVIEW_SPEC();
+ spec.entities.push({ schemaName: 'new_other', displayName: 'Other', primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns: [] });
+ const text = renderFormWireframe(spec, spec.forms[0]);
+ const at = (needle) => { const i = text.indexOf(needle); assert.ok(i >= 0, `${needle} is drawn`); return i; };
+ // tab A: Main, then the grid placed after it, then More, then the Notes section — in the order a build leaves them.
+ assert.ok(at('Main ┄') < at('▦ new_task') && at('▦ new_task') < at('More ┄') && at('More ┄') < at('Notes / Timeline'));
+ assert.match(text, /▦ new_task ┄+ │\n│ +\(sub-grid {2}→ {2}new_task\)/);
+ // tab B: the grid that names only the tab is at the end of that tab.
+ assert.ok(at('▾ B') < at('▦ new_comment') && at('B ┄') < at('▦ new_comment'));
+ // The grid that says nothing stays where the wireframe always listed it, after the last tab.
+ assert.ok(at('▦ new_comment') < at('▦ Sub-grids') && at('▦ Sub-grids') < at('• Others'));
+ assert.doesNotMatch(text, /• new_task|• new_comment/, 'a placed grid is not listed twice');
+ assert.match(text, /• Others {2}→ {2}new_other/);
+});
+
+test('wireframe: a form whose grids place nothing is drawn exactly as before — one block after the last tab', () => {
+ const spec = specWith([{ childEntity: 'new_task', label: 'Tasks' }]);
+ const lines = PREVIEW_LINES(spec);
+ assert.ok(lines.some((l) => /▦ Sub-grids/.test(l)));
+ assert.ok(lines.some((l) => /• Tasks {2}→ {2}new_task/.test(l)));
+ assert.ok(!lines.some((l) => /\(sub-grid/.test(l)));
+});
+
+test('wireframe: a placement the layout cannot resolve is left in the Sub-grids block, as the build leaves it', () => {
+ const spec = specWith([{ childEntity: 'new_task', after: 'sec_nope' }]);
+ const text = renderFormWireframe(spec, spec.forms[0]);
+ assert.match(text, /▦ Sub-grids/);
+ assert.match(text, /• new_task {2}→ {2}new_task/);
+});
+
+test('wireframe: an auto layout draws a grid before or after its one section', () => {
+ const spec = autoForm([{ childEntity: 'new_task', before: 'section_general' }, { childEntity: 'new_comment', after: 'section_general' }]);
+ const text = renderFormWireframe(spec, spec.forms[0]);
+ assert.ok(text.indexOf('▦ new_task') < text.indexOf('(no heading)') && text.indexOf('(no heading)') < text.indexOf('▦ new_comment'), text);
+ assert.doesNotMatch(text, /▦ Sub-grids/);
+});
+
+// A layout may declare a section named `section_notes` — a natural name for a section of note fields — and the compiler
+// adds its own Notes section under the same name. The wireframe tells them apart by place in the column, not by name:
+// the layout's section is drawn with its fields and the compiler's is the one Notes / Timeline block, whether or not a
+// grid is placed in that column.
+test('wireframe: a layout section named section_notes is drawn with its fields, and the Notes section the form asks for is still there — with or without a placed grid', () => {
+ const withNotes = (subgrids) => specWith(subgrids, { notes: true, tabs: [{ name: 'tab_a', label: 'A', sections: [
+ { name: 'sec_main', label: 'Main', columns: 1, fields: ['new_name'] },
+ { name: 'section_notes', label: 'Note fields', columns: 1, fields: ['new_notes'] },
+ ] }] });
+ const without = renderFormWireframe(withNotes([]), withNotes([]).forms[0]);
+ const placed = withNotes([{ childEntity: 'new_task', after: 'sec_main' }]);
+ const text = renderFormWireframe(placed, placed.forms[0]);
+ for (const [which, wire] of [['no grid placed', without], ['a grid placed in the column', text]]) {
+ assert.strictEqual((wire.match(/Notes \/ Timeline/g) || []).length, 1, `${which}: one Notes / Timeline block — the compiler's`);
+ assert.match(wire, /Note fields ┄/, `${which}: the layout's section is drawn under its own heading`);
+ assert.match(wire, /Notes {2}/, `${which}: …with its field`);
+ assert.ok(wire.indexOf('Note fields') < wire.indexOf('Notes / Timeline'), `${which}: ahead of the Notes section, where a build puts it`);
+ }
+ assert.ok(text.indexOf('Main ┄') < text.indexOf('▦ new_task') && text.indexOf('▦ new_task') < text.indexOf('Note fields'), 'the grid is drawn after sec_main');
+});
+
+test('plan: the Forms table shows where a grid is placed, and nothing for a grid that says nothing', () => {
+ const spec = specWith([
+ { childEntity: 'new_task', after: 'sec_main' },
+ { childEntity: 'new_comment', tab: 'tab_b', column: 0 },
+ ]);
+ assert.match(renderAppSpecDoc(spec), /\| Main \| new_ticket \| Main \| explicit \(2 tabs\) \| new_task \(after sec_main\), new_comment \(tab tab_b, column 0\) \|/);
+ const plain = specWith([{ childEntity: 'new_task' }, { childEntity: 'new_comment' }]);
+ assert.match(renderAppSpecDoc(plain), /\| explicit \(2 tabs\) \| new_task, new_comment \|/);
+ const odd = specWith([{ childEntity: 'new_task', tab: 7, after: ['x'], before: 'a|b' }]);
+ assert.match(renderAppSpecDoc(odd), /\| new_task \(before a\\\|b\) \|/, 'a value that is not a name is skipped, and a pipe cannot break the table');
+});
diff --git a/plugins/model-apps/scripts/tests/form-timeline-real-bundle.test.js b/plugins/model-apps/scripts/tests/form-timeline-real-bundle.test.js
new file mode 100644
index 000000000..398d5b858
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/form-timeline-real-bundle.test.js
@@ -0,0 +1,897 @@
+'use strict';
+// REAL BUNDLE: the Notes timeline in the shape Dynamics renders (GitHub #680) — what the vendored SDK
+// serializes for a new host, how a rebuild repairs a host an older build wrote, and what `--verify` says.
+// The mock-SDK suites prove the engine's decisions; these prove the SDK really writes and re-reads the shape.
+const test = require('node:test');
+const assert = require('node:assert');
+const ai = require('../lib/artifact-intent.js');
+const { runSdkBuild } = require('../lib/sdk-build.js');
+const { renderFormWireframe } = require('../lib/form-preview.js');
+const { createHarness, seedForm, verifyForms, sectionXml, collapseEmptyRows, clone, NOTES_CLASS_ID, DEFAULT_ATTRIBUTES } = require('./helpers/form-store-harness.js');
+
+const PLATFORM_CONTROL = '<control id="notescontrol" classid="{06375649-C143-495E-A496-C962E5B4488E}" disabled="false" isrequired="false" />';
+
+function specFor({ layout = 'explicit', notes = true } = {}) {
+ return {
+ $schemaVersion: '1.0',
+ solution: { uniqueName: 'Timeline', displayName: 'Timeline', publisherPrefix: 'new' },
+ app: { name: 'Timeline', uniqueName: 'new_timeline' },
+ entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', pluralName: 'Tickets', existing: true,
+ primaryAttribute: { schemaName: 'new_name', displayName: 'Name' },
+ columns: [
+ { schemaName: 'new_code', displayName: 'Code', type: 'Text' },
+ { schemaName: 'new_notes', displayName: 'Notes', type: 'Memo' },
+ { schemaName: 'new_area', displayName: 'Area', type: 'Text' },
+ ] }],
+ forms: [layout === 'explicit'
+ ? { entity: 'new_ticket', name: 'Main', notes, tabs: [{ name: 'tab_a', label: 'A', sections: [
+ { name: 'sec_main', label: 'Main', columns: 2, fields: ['new_name', 'new_code'] },
+ { name: 'sec_more', label: 'More', columns: 1, fields: ['new_notes', 'new_area'] },
+ ] }] }
+ : { entity: 'new_ticket', name: 'Main', notes }],
+ };
+}
+
+// What every build before this change wrote for the Notes section: the timeline as an ordinary unbound control
+// (the SDK mints its id) in a one-row cell, with nothing under it.
+const oldNotesSection = () => ({
+ name: 'section_notes', label: 'Notes', visible: true, showLabel: true, columns: 1,
+ rows: [{ cells: [{ control: { classId: NOTES_CLASS_ID, fieldName: null, label: 'Notes', showLabel: false, parameters: {} } }] }],
+});
+
+// The compiled form with its Notes section swapped for `host` — a form an older build, or a maker, left behind.
+function compiledTabs(spec, host) {
+ const tabs = ai.compileFormIntent(spec, spec.forms[0], { notesClassId: NOTES_CLASS_ID }).tabs;
+ const sections = tabs[0].columns[0].sections;
+ const at = sections.findIndex((s) => s.name === 'section_notes');
+ if (host === null) sections.splice(at, 1);
+ else if (host) sections[at] = host;
+ return tabs;
+}
+
+const sectionsOf = (form) => form.tabs.flatMap((t) => t.columns.flatMap((c) => c.sections));
+const sectionOf = (form, name) => sectionsOf(form).find((s) => s.name === name);
+const cellsOf = (section) => section.rows.flatMap((r) => r.cells);
+const controlIds = (xml) => [...String(xml).matchAll(/<control\b[^>]*\bid="([^"]*)"/g)].map((m) => m[1]);
+const attrsOf = (tag) => Object.fromEntries([...tag.matchAll(/([\w-]+)="([^"]*)"/g)].map((m) => [m[1], m[2]]));
+const layoutMutations = (mutations) => mutations.filter((m) => ['addElement', 'updateElement', 'moveElement', 'removeElement'].includes(m.method));
+
+const harnesses = [];
+const newHarness = (options) => { const h = createHarness(options); harnesses.push(h); return h; };
+test.after(() => { for (const h of harnesses) h.cleanup(); });
+
+// --- (a) a new host ---------------------------------------------------------------------------------------
+
+test('timeline: a NEW Notes host is serialized as notescontrol in a 23-row cell with auto=false, followed by 22 empty rows', async () => {
+ const h = newHarness();
+ const spec = specFor();
+ await seedForm(h, compiledTabs(spec));
+ const xml = h.store.row.formxml;
+ const host = sectionXml(xml, 'section_notes');
+
+ // The control: the platform's fixed id and class id, nothing else generated about it.
+ assert.ok(host.includes(PLATFORM_CONTROL), `the timeline control is exactly ${PLATFORM_CONTROL}; got ${host.slice(0, 700)}`);
+ // The cell: tall, `auto="false"`, labelled "Notes" with its label hidden — the attributes of the platform's own cell.
+ const cellTag = /<cell\b[^>]*>/.exec(host)[0];
+ const { id, ...cellAttrs } = attrsOf(cellTag);
+ assert.deepStrictEqual(cellAttrs, { showlabel: 'false', colspan: '1', rowspan: '23', auto: 'false' });
+ assert.match(id, /^[0-9a-f-]{36}$/, 'the cell keeps a generated identity');
+ assert.match(host, /<labels><label description="Notes" languagecode="1033" \/><\/labels><control /, 'the cell carries the "Notes" label');
+ // The section: still ours — `section_notes`, labelled "Notes" — holding the host row then the 22 rows it spans.
+ assert.match(host, /^<section id="[0-9a-f-]{36}" name="section_notes" showlabel="true" visible="true" columns="1"><labels><label description="Notes" languagecode="1033" \/><\/labels><rows>/);
+ assert.match(collapseEmptyRows(host), /<\/cell><\/row><row \/>×22<\/rows><\/section>$/, 'exactly 22 empty rows follow the host row, and nothing else');
+ assert.strictEqual((host.match(/<row\b/g) || []).length, 23);
+ // …and no duplicate control id anywhere on the form.
+ const ids = controlIds(xml);
+ assert.strictEqual(ids.filter((x) => x === 'notescontrol').length, 1, 'exactly one notescontrol');
+ assert.strictEqual(new Set(ids).size, ids.length, `control ids are unique: ${ids.join(', ')}`);
+ // The field sections around it are as before: the host is the LAST section of the first tab's column.
+ assert.ok(xml.indexOf('name="sec_more"') < xml.indexOf('name="section_notes"'));
+});
+
+test('timeline: the engine\u2019s own create path writes the same host (runSdkBuild over a table with no form yet)', async () => {
+ for (const layout of ['explicit', 'auto']) {
+ const h = newHarness();
+ delete h.store.row.formxml; // no form on the table: the build has to create it
+ const spec = specFor({ layout });
+ const { sdk } = await h.freshSdk();
+ const built = await runSdkBuild(spec, { sdk, apply: true, phases: ['forms'] });
+ assert.strictEqual(built.ok, true, `${layout}: ${JSON.stringify(built.error || built.halt || '')}`);
+ assert.ok(h.store.row.formxml, `${layout}: the build created the form`);
+ const host = collapseEmptyRows(sectionXml(h.store.row.formxml, 'section_notes'));
+ assert.ok(host.includes(PLATFORM_CONTROL), `${layout}: ${host.slice(0, 600)}`);
+ assert.match(host, /rowspan="23"[^>]*auto="false"|auto="false"[^>]*rowspan="23"/);
+ assert.match(host, /<row \/>×22<\/rows><\/section>$/);
+ const verified = await verifyForms(h, spec);
+ assert.strictEqual(verified.checks.find((c) => c.kind === 'form-timeline').present, true, `${layout}: ${JSON.stringify(verified.missing)}`);
+ }
+});
+
+test('timeline: hasNotes on the table asks for it too, and a form that does not ask has no Notes section', async () => {
+ const withTable = specFor({ notes: false });
+ withTable.entities[0].hasNotes = true;
+ const asked = ai.compileFormIntent(withTable, withTable.forms[0], { notesClassId: NOTES_CLASS_ID });
+ assert.strictEqual(asked.__notes, true);
+ assert.ok(asked.tabs[0].columns[0].sections.some((s) => s.name === 'section_notes' && s.rows.length === 23));
+ const plain = ai.compileFormIntent(specFor({ notes: false }), specFor({ notes: false }).forms[0], { notesClassId: NOTES_CLASS_ID });
+ assert.strictEqual(plain.__notes, false);
+ assert.ok(!plain.tabs[0].columns[0].sections.some((s) => s.name === 'section_notes'));
+});
+
+// --- (b) converge an existing form -------------------------------------------------------------------------
+
+for (const layout of ['explicit', 'auto']) {
+ test(`timeline: a rebuild repairs an OLD-shape host in place (${layout} layout), and a second rebuild changes nothing`, async () => {
+ const h = newHarness();
+ const spec = specFor({ layout });
+ await seedForm(h, compiledTabs(spec, oldNotesSection()));
+ const before = clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+ const hostBefore = sectionOf(before, 'section_notes');
+ const timelineBefore = cellsOf(hostBefore)[0];
+ // The premise: the host really is the old shape — a generated id, a one-row cell, no rows under it.
+ assert.notStrictEqual(timelineBefore.control.id, 'notescontrol');
+ assert.match(timelineBefore.control.id, /^[0-9a-f-]{36}$/);
+ assert.strictEqual(timelineBefore.rowspan, 1);
+ assert.strictEqual(hostBefore.rows.length, 1);
+ assert.ok(!h.store.row.formxml.includes('notescontrol'));
+
+ // --verify says so BEFORE the repair: the fix is not applied.
+ const unrepaired = await verifyForms(h, spec);
+ const failing = unrepaired.checks.find((c) => c.kind === 'form-timeline');
+ assert.strictEqual(failing.present, false);
+ assert.match(failing.detail, /does not render: the control id is '[0-9a-f-]{36}', not 'notescontrol' and its cell spans 1 row — run a full build of the spec \(not --changed-only, which skips a spec that has not changed\) to repair it in place/);
+ assert.strictEqual(unrepaired.ok, false);
+
+ const first = await h.freshSdk();
+ const warnings = [];
+ const built = await runSdkBuild(spec, { sdk: first.sdk, apply: true, phases: ['forms'], warn: (m) => warnings.push(String(m)) });
+ assert.strictEqual(built.ok, true);
+ assert.ok(warnings.some((w) => /repaired the Notes section's timeline in place .*'notescontrol'.*23-row cell and 22 empty row/.test(w)), `the repair is reported; got ${JSON.stringify(warnings)}`);
+ const writes = layoutMutations(first.mutations);
+ assert.strictEqual(writes.length, 1, `one atomic write; got ${JSON.stringify(writes.map((m) => [m.method, m.args[2]]))}`);
+ assert.strictEqual(writes[0].method, 'updateElement');
+ assert.match(writes[0].args[2], /\/sections\/\d+\/rows$/, 'the host\u2019s rows are replaced whole');
+
+ const after = clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+ const hostAfter = sectionOf(after, 'section_notes');
+ const timelineAfter = cellsOf(hostAfter)[0];
+ // Same section, same position, same cell and control identity — only the shape changed.
+ assert.strictEqual(hostAfter.id, hostBefore.id);
+ assert.deepStrictEqual(sectionsOf(after).map((s) => s.name), sectionsOf(before).map((s) => s.name), 'every section keeps its place');
+ assert.strictEqual(timelineAfter.id, timelineBefore.id, 'the cell is the same cell');
+ assert.strictEqual(timelineAfter.control.id, 'notescontrol');
+ assert.strictEqual(timelineAfter.rowspan, 23);
+ assert.strictEqual(hostAfter.rows.length, 23);
+ assert.ok(hostAfter.rows.slice(1).every((r) => r.cells.length === 0));
+ assert.strictEqual(timelineAfter.control.classId, timelineBefore.control.classId);
+ for (const section of sectionsOf(before)) {
+ if (section.name === 'section_notes') continue;
+ assert.deepStrictEqual(sectionOf(after, section.name), section, `${section.name} is untouched`);
+ }
+ // What the server holds.
+ const xml = h.store.row.formxml;
+ const host = sectionXml(xml, 'section_notes');
+ assert.ok(host.includes(PLATFORM_CONTROL));
+ // The repaired cell keeps the attributes it was written with (here its `visible="true"`) and gains the platform's.
+ const repairedCell = attrsOf(/<cell\b[^>]*>/.exec(host)[0]);
+ assert.deepStrictEqual({ showlabel: repairedCell.showlabel, colspan: repairedCell.colspan, rowspan: repairedCell.rowspan, auto: repairedCell.auto },
+ { showlabel: 'false', colspan: '1', rowspan: '23', auto: 'false' });
+ assert.match(collapseEmptyRows(host), /<\/cell><\/row><row \/>×22<\/rows><\/section>$/);
+ assert.ok(host.includes(`id="${timelineBefore.id}"`), 'the cell id survives the serialize');
+ const ids = controlIds(xml);
+ assert.strictEqual(new Set(ids).size, ids.length, 'control ids stay unique');
+
+ const repaired = await verifyForms(h, spec);
+ assert.strictEqual(repaired.checks.find((c) => c.kind === 'form-timeline').present, true, JSON.stringify(repaired.missing));
+ assert.strictEqual(repaired.ok, true, JSON.stringify(repaired.missing));
+
+ // Idempotent: nothing left to repair, so nothing is written and the form is the same bytes.
+ const second = await h.freshSdk();
+ const xmlBefore = h.store.row.formxml;
+ const again = await runSdkBuild(spec, { sdk: second.sdk, apply: true, phases: ['forms'] });
+ assert.strictEqual(again.ok, true);
+ assert.deepStrictEqual(second.mutations, [], 'a rebuild of an already-correct form mutates nothing');
+ assert.strictEqual(h.store.row.formxml, xmlBefore);
+ });
+}
+
+test('timeline: a host the maker already sized keeps its span; only what it lacks is written', async () => {
+ const h = newHarness();
+ const spec = specFor();
+ const sized = oldNotesSection();
+ sized.rows[0].cells[0].rowspan = 8;
+ for (let i = 0; i < 7; i += 1) sized.rows.push({ cells: [] });
+ await seedForm(h, compiledTabs(spec, sized));
+ const { sdk } = await h.freshSdk();
+ await runSdkBuild(spec, { sdk, apply: true, phases: ['forms'] });
+ const after = clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+ const host = sectionOf(after, 'section_notes');
+ assert.strictEqual(cellsOf(host)[0].control.id, 'notescontrol', 'the id is repaired');
+ assert.strictEqual(cellsOf(host)[0].rowspan, 8, 'the span the maker chose is respected');
+ assert.strictEqual(host.rows.length, 8, 'and no rows are added beyond what it spans');
+});
+
+// --- any height: the platform's forms differ, and a maker can resize the timeline -----------------------------
+
+// The Notes host as the platform or a maker leaves it: a timeline cell `rowspan` rows tall under `notescontrol`
+// with `below` rows after its own, an `auto` attribute only when given, `colspan` wide in a section of `columns`.
+function tallNotesSection({ rowspan, below = rowspan - 1, auto, colspan = 1, columns = 1 }) {
+ const host = ai.notesSectionIntent(NOTES_CLASS_ID);
+ host.columns = columns;
+ const cell = host.rows[0].cells[0];
+ cell.rowspan = rowspan;
+ cell.colspan = colspan;
+ cell.bag = { a: [['showlabel', 'false'], ['colspan', String(colspan)], ['rowspan', String(rowspan)], ...(auto === undefined ? [] : [['auto', auto]])], c: [] };
+ host.rows = [host.rows[0], ...Array.from({ length: below }, () => ({ cells: [] }))];
+ return host;
+}
+const cellTagOf = (xml) => /<cell\b[^>]*>/.exec(sectionXml(xml, 'section_notes'))[0];
+
+// What the platform's own forms carry: Account's timeline is 20 rows tall with no `auto`, Contact's 5 rows tall and
+// two columns wide with `auto="false"`, the reported form's 23 — each followed by exactly the rows it spans.
+const PLATFORM_HEIGHTS = [
+ { label: '20 rows, no auto (as on Account)', host: { rowspan: 20 } },
+ { label: '5 rows, 2 columns wide, auto=false (as on Contact)', host: { rowspan: 5, auto: 'false', colspan: 2, columns: 2 } },
+ { label: '23 rows, auto=false (as written for a new host)', host: { rowspan: 23, auto: 'false' } },
+ { label: '2 rows', host: { rowspan: 2 } },
+];
+
+for (const layout of ['explicit', 'auto']) {
+ for (const { label, host } of PLATFORM_HEIGHTS) {
+ test(`timeline: a host of ${label} is already in shape (${layout} layout) — verify passes and a rebuild writes nothing`, async () => {
+ const h = newHarness();
+ const spec = specFor({ layout });
+ await seedForm(h, compiledTabs(spec, tallNotesSection(host)));
+ const xml = h.store.row.formxml;
+ const before = clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+ assert.strictEqual(sectionOf(before, 'section_notes').rows.length, host.rowspan, 'the premise: exactly the rows the cell spans');
+
+ const verified = (await verifyForms(h, spec)).checks.find((c) => c.kind === 'form-timeline');
+ assert.strictEqual(verified.present, true, verified.detail);
+
+ const run = await h.freshSdk();
+ assert.strictEqual((await runSdkBuild(spec, { sdk: run.sdk, apply: true, phases: ['forms'] })).ok, true);
+ assert.deepStrictEqual(layoutMutations(run.mutations), [], 'nothing about the host is rewritten — not its height, its width or its auto');
+ assert.strictEqual(h.store.row.formxml, xml);
+ assert.deepStrictEqual(clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId)), before);
+ });
+ }
+}
+
+test('timeline: a host that only lacks rows is given them to ITS height, and the build writes no auto for it', async () => {
+ for (const layout of ['explicit', 'auto']) {
+ const h = newHarness();
+ const spec = specFor({ layout });
+ await seedForm(h, compiledTabs(spec, tallNotesSection({ rowspan: 8, below: 3 })));
+ assert.ok(!cellTagOf(h.store.row.formxml).includes('auto='), 'the premise: a cell with no auto attribute');
+
+ const unbacked = (await verifyForms(h, spec)).checks.find((c) => c.kind === 'form-timeline');
+ assert.strictEqual(unbacked.present, false, `${layout}: the engine's own host with a span its rows do not back is a fix not applied`);
+ assert.match(unbacked.detail, /the deployed form's timeline does not render: its cell spans 8 rows but only 3 row\(s\) follow it — run a full build of the spec \(not --changed-only, which skips a spec that has not changed\) to repair it in place/);
+
+ const run = await h.freshSdk();
+ const warnings = [];
+ assert.strictEqual((await runSdkBuild(spec, { sdk: run.sdk, apply: true, phases: ['forms'], warn: (m) => warnings.push(String(m)) })).ok, true);
+ const writes = layoutMutations(run.mutations);
+ assert.deepStrictEqual(writes.map((m) => [m.method, /\/sections\/\d+\/rows$/.test(m.args[2])]), [['updateElement', true]], `${layout}: one write of the host's rows`);
+ assert.ok(warnings.some((w) => /a 8-row cell and 7 empty row\(s\) under it/.test(w)), JSON.stringify(warnings));
+ const host = sectionOf(clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId)), 'section_notes');
+ assert.deepStrictEqual([cellsOf(host)[0].rowspan, host.rows.length], [8, 8], 'its own height, backed');
+ assert.ok(!cellTagOf(h.store.row.formxml).includes('auto='), `${layout}: no auto was added to a cell that only needed rows`);
+ assert.strictEqual((await verifyForms(h, spec)).checks.find((c) => c.kind === 'form-timeline').present, true);
+ const again = await h.freshSdk();
+ assert.strictEqual((await runSdkBuild(spec, { sdk: again.sdk, apply: true, phases: ['forms'] })).ok, true);
+ assert.deepStrictEqual(again.mutations, []);
+ }
+});
+
+test('timeline: a maker\u2019s own timeline is judged by its id and span — rows the build cannot add to it are not a failure — and is left as it is', async () => {
+ const h = newHarness();
+ const spec = specFor();
+ const tabs = compiledTabs(spec, null);
+ const own = tallNotesSection({ rowspan: 8, below: 0 });
+ own.name = 'maker_timeline';
+ tabs[0].columns[0].sections.push(own);
+ await seedForm(h, tabs);
+ const before = h.store.row.formxml;
+ assert.strictEqual((await verifyForms(h, spec)).checks.find((c) => c.kind === 'form-timeline').present, true);
+ const run = await h.freshSdk();
+ assert.strictEqual((await runSdkBuild(spec, { sdk: run.sdk, apply: true, phases: ['forms'] })).ok, true);
+ assert.deepStrictEqual(layoutMutations(run.mutations), []);
+ assert.strictEqual(h.store.row.formxml, before);
+});
+
+test('timeline: a host a maker widened WITH its timeline keeps its width, and one whose timeline still fits one column is narrowed as before', async () => {
+ const h = newHarness();
+ const spec = specFor();
+ const wideTimeline = tallNotesSection({ rowspan: 5, auto: 'false', colspan: 2, columns: 2 });
+ await seedForm(h, compiledTabs(spec, wideTimeline));
+ const run = await h.freshSdk();
+ assert.strictEqual((await runSdkBuild(spec, { sdk: run.sdk, apply: true, phases: ['forms'] })).ok, true);
+ const host = sectionOf(clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId)), 'section_notes');
+ assert.deepStrictEqual([host.columns, cellsOf(host)[0].colspan], [2, 2], 'a cell is never left wider than its section');
+ assert.deepStrictEqual(layoutMutations(run.mutations), []);
+
+ // Widened in the maker with the timeline still one column wide: the engine\u2019s own width wins, as it always did.
+ const narrow = newHarness();
+ await seedForm(narrow, compiledTabs(spec, tallNotesSection({ rowspan: 23, auto: 'false', colspan: 1, columns: 2 })));
+ const second = await narrow.freshSdk();
+ assert.strictEqual((await runSdkBuild(spec, { sdk: second.sdk, apply: true, phases: ['forms'] })).ok, true);
+ assert.strictEqual(sectionOf(clone(await (await narrow.freshSdk()).sdk.fetchArtifact('form', narrow.formId)), 'section_notes').columns, 1);
+});
+
+test('timeline: a rebuild writes the repair in ONE edit, so an interrupted write leaves the old host and a retry converges', async () => {
+ const h = newHarness();
+ const spec = specFor();
+ await seedForm(h, compiledTabs(spec, oldNotesSection()));
+ const first = await h.freshSdk();
+ const before = clone(await first.sdk.fetchArtifact('form', h.formId));
+ const original = first.sdk.updateElement.bind(first.sdk);
+ let injected = false;
+ first.sdk.updateElement = async (...args) => {
+ if (args[0] === 'form' && /\/rows$/.test(args[2])) { injected = true; throw new Error('injected write failure'); }
+ return original(...args);
+ };
+ await assert.rejects(() => runSdkBuild(spec, { sdk: first.sdk, apply: true, phases: ['forms'] }), /injected write failure/);
+ assert.ok(injected, 'the fault was actually exercised');
+ assert.deepStrictEqual(clone(await first.sdk.getArtifact('form', h.formId)), before, 'a failed write leaves the form as it was — never half a host');
+ const retry = await h.freshSdk(first.dir);
+ await retry.sdk.fetchArtifact('form', h.formId);
+ assert.strictEqual((await runSdkBuild(spec, { sdk: retry.sdk, apply: true, phases: ['forms'] })).ok, true);
+ const host = sectionOf(await retry.sdk.getArtifact('form', h.formId), 'section_notes');
+ assert.strictEqual(host.rows.length, 23);
+ assert.strictEqual(cellsOf(host)[0].control.id, 'notescontrol');
+});
+
+// --- never touch what is not the engine's; never mint a second `notescontrol` --------------------------------
+
+// A timeline a maker added — the platform's own shape, under a section of their own name.
+const makerTimelineSection = () => ({ name: 'maker_timeline', label: 'Timeline', visible: true, showLabel: false, columns: 1, rows: ai.notesSectionIntent(NOTES_CLASS_ID).rows });
+
+for (const layout of ['explicit', 'auto']) {
+ test(`timeline: a maker's own timeline is never touched, and no second notescontrol is created (${layout} layout)`, async () => {
+ const h = newHarness();
+ const spec = specFor({ layout });
+ const tabs = compiledTabs(spec, null); // no engine host
+ tabs[0].columns[0].sections.push(makerTimelineSection());
+ await seedForm(h, tabs);
+ const before = clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+ const xmlBefore = h.store.row.formxml;
+
+ const first = await h.freshSdk();
+ const warnings = [];
+ const built = await runSdkBuild(spec, { sdk: first.sdk, apply: true, phases: ['forms'], warn: (m) => warnings.push(String(m)) });
+ assert.strictEqual(built.ok, true);
+ const after = clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+ assert.deepStrictEqual(sectionsOf(after).map((s) => s.name), sectionsOf(before).map((s) => s.name), 'no Notes section was added beside it');
+ assert.deepStrictEqual(sectionOf(after, 'maker_timeline'), sectionOf(before, 'maker_timeline'), 'the maker\u2019s timeline is byte-for-byte what it was');
+ assert.strictEqual(controlIds(h.store.row.formxml).filter((x) => x === 'notescontrol').length, 1, 'still exactly one notescontrol');
+ assert.ok(built.skipped.layout.some((m) => /no Notes section was added — a control on this form already uses the id 'notescontrol'/.test(m)),
+ `the declined add is reported on the result; got ${JSON.stringify(built.skipped.layout)}`);
+ assert.ok(warnings.some((m) => /no Notes section was added/.test(m)));
+ assert.strictEqual(h.store.row.formxml, xmlBefore, 'nothing was written');
+ // The form carries a timeline that renders, so verify is satisfied by it.
+ const verified = await verifyForms(h, spec);
+ assert.strictEqual(verified.checks.find((c) => c.kind === 'form-timeline').present, true);
+ });
+}
+
+test('timeline: an old host is left as it is, and reported, when another control already holds the id notescontrol', async () => {
+ const h = newHarness();
+ const spec = specFor();
+ const tabs = compiledTabs(spec, oldNotesSection());
+ tabs[0].columns[0].sections.push(makerTimelineSection());
+ await seedForm(h, tabs);
+ const before = clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+ const xmlBefore = h.store.row.formxml;
+ const { sdk, mutations } = await h.freshSdk();
+ const built = await runSdkBuild(spec, { sdk, apply: true, phases: ['forms'] });
+ assert.strictEqual(built.ok, true);
+ assert.deepStrictEqual(layoutMutations(mutations), [], 'no write: the id cannot be renamed, so nothing is half-applied');
+ assert.deepStrictEqual(clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId)), before);
+ assert.strictEqual(h.store.row.formxml, xmlBefore);
+ assert.ok(built.skipped.layout.some((m) => /Notes section's timeline was left as it is — its control id cannot become 'notescontrol'/.test(m)), JSON.stringify(built.skipped.layout));
+ assert.ok(built.skipped.layout.some((m) => /Remove or rename one of the two in the maker, then run a full build of the spec \(not --changed-only, which skips a spec that has not changed\)\./.test(m)), 'the report says what to do, and that it takes a full build');
+ assert.strictEqual(controlIds(h.store.row.formxml).filter((x) => x === 'notescontrol').length, 1);
+});
+
+test('timeline: a host a maker added a field to is not repaired — it is reported, and verify keeps failing until it is replaced', async () => {
+ const h = newHarness();
+ const spec = specFor();
+ spec.forms[0].prune = false; // the maker's field is not in the layout: without this the build would prune it first
+ const host = oldNotesSection();
+ host.rows.push({ cells: [ai.fieldCellIntent('new_extra')] });
+ await seedForm(h, compiledTabs(spec, host));
+ const before = clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+ const { sdk, mutations } = await h.freshSdk();
+ const built = await runSdkBuild(spec, { sdk, apply: true, phases: ['forms'] });
+ assert.deepStrictEqual(layoutMutations(mutations).filter((m) => /section_notes|\/sections\/\d+\/rows$/.test(JSON.stringify(m.args[2]))), [], 'the host is not written');
+ assert.deepStrictEqual(sectionOf(clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId)), 'section_notes'), sectionOf(before, 'section_notes'));
+ assert.ok(built.skipped.layout.some((m) => /Notes section's timeline was left as it is — the section also holds other controls/.test(m)), JSON.stringify(built.skipped.layout));
+ assert.ok(built.skipped.layout.some((m) => /Move them out of it, or delete the section, in the maker, then run a full build of the spec \(not --changed-only, which skips a spec that has not changed\) to get a timeline that renders\./.test(m)), 'the report says what to do, and that it takes a full build');
+ const verified = await verifyForms(h, spec);
+ const check = verified.checks.find((c) => c.kind === 'form-timeline');
+ assert.strictEqual(check.present, false, 'the fix was not applied, and verify says so');
+ // …and says what a build will NOT do about it, rather than sending the maker to build again — and which control it is.
+ assert.match(check.detail, /the Notes section also holds the field 'new_extra', which a build does not remove, so the build leaves the section as it is; move it out of it, or delete the section, in the maker, then run a full build of the spec/);
+ assert.doesNotMatch(check.detail, /repair it in place/);
+});
+
+// The repair rewrites only the host's own rows, so it waits for every step that can take another control out of the
+// host — the prune of a field the layout dropped, the move of one a `fieldOptions` anchor places elsewhere — and runs
+// when the host is as clean as this build will leave it. Run first, it would refuse a host that the same build is about
+// to empty, and `--verify` would fail until a second build.
+test('timeline: a field the layout dropped is pruned out of the old Notes section first, so the SAME build repairs the timeline', async () => {
+ const h = newHarness();
+ const spec = specFor(); // an explicit layout: prune is on, and new_extra is not in it
+ const host = oldNotesSection();
+ host.rows.push({ cells: [ai.fieldCellIntent('new_extra')] });
+ await seedForm(h, compiledTabs(spec, host));
+ assert.ok(h.store.row.formxml.includes('new_extra'), 'the premise: the stray field is on the form, in the Notes section');
+ const before = clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+ const hostBefore = sectionOf(before, 'section_notes');
+ const first = await h.freshSdk();
+ const built = await runSdkBuild(spec, { sdk: first.sdk, apply: true, phases: ['forms'] });
+ assert.strictEqual(built.ok, true);
+ assert.deepStrictEqual(built.skipped.layout.filter((m) => /Notes section/.test(m)), [], 'the repair was not refused');
+ const after = clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+ assert.ok(!h.store.row.formxml.includes('new_extra'), 'the stray field was pruned');
+ const repaired = sectionOf(after, 'section_notes');
+ assert.strictEqual(repaired.id, hostBefore.id, 'the same section');
+ assert.strictEqual(cellsOf(repaired)[0].id, cellsOf(hostBefore)[0].id, 'the same cell');
+ assert.deepStrictEqual([cellsOf(repaired).length, cellsOf(repaired)[0].control.id, cellsOf(repaired)[0].rowspan, repaired.rows.length], [1, 'notescontrol', 23, 23]);
+ assert.strictEqual((await verifyForms(h, spec)).checks.find((c) => c.kind === 'form-timeline').present, true, 'verify passes after ONE build');
+ const second = await h.freshSdk();
+ assert.strictEqual((await runSdkBuild(spec, { sdk: second.sdk, apply: true, phases: ['forms'] })).ok, true);
+ assert.deepStrictEqual(second.mutations, [], 'and a second build has nothing to do');
+});
+
+for (const layout of ['explicit', 'auto']) {
+ test(`timeline: a field a \`fieldOptions\` anchor moves out of the old Notes section does not stop the same build repairing it (${layout} layout)`, async () => {
+ const h = newHarness();
+ const spec = specFor({ layout });
+ if (layout === 'explicit') spec.forms[0].prune = false; // the field is the maker's, so it stays — placed after new_area by the anchor
+ spec.forms[0].fieldOptions = { new_extra: { after: 'new_area' } };
+ const host = oldNotesSection();
+ host.rows.push({ cells: [ai.fieldCellIntent('new_extra')] });
+ await seedForm(h, compiledTabs(spec, host));
+ const first = await h.freshSdk();
+ const built = await runSdkBuild(spec, { sdk: first.sdk, apply: true, phases: ['forms'] });
+ assert.strictEqual(built.ok, true);
+ assert.deepStrictEqual(built.skipped.layout.filter((m) => /Notes section/.test(m)), [], 'the repair was not refused');
+ const after = clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+ const fields = cellsOf(sectionOf(after, layout === 'explicit' ? 'sec_more' : 'section_general')).map((c) => c.control.fieldName);
+ assert.strictEqual(fields[fields.indexOf('new_area') + 1], 'new_extra', `the anchor placed it right after new_area: ${fields.join(', ')}`);
+ const repaired = sectionOf(after, 'section_notes');
+ assert.deepStrictEqual([cellsOf(repaired).length, cellsOf(repaired)[0].control.id, repaired.rows.length], [1, 'notescontrol', 23]);
+ assert.strictEqual((await verifyForms(h, spec)).checks.find((c) => c.kind === 'form-timeline').present, true);
+ });
+}
+
+test('timeline: a field the layout declares in another section is moved out of the old Notes section, and the same build repairs it', async () => {
+ const h = newHarness();
+ const spec = specFor();
+ spec.forms[0].tabs[0].sections[1].fields.push('new_extra'); // declared in sec_more, but the form has it in the Notes section
+ const host = oldNotesSection();
+ host.rows.push({ cells: [ai.fieldCellIntent('new_extra')] });
+ const tabs = compiledTabs(spec, host);
+ const more = tabs[0].columns[0].sections.find((s) => s.name === 'sec_more');
+ more.rows = more.rows.filter((r) => !r.cells.some((c) => c.control.fieldName === 'new_extra'));
+ await seedForm(h, tabs);
+ const first = await h.freshSdk();
+ const built = await runSdkBuild(spec, { sdk: first.sdk, apply: true, phases: ['forms'] });
+ assert.strictEqual(built.ok, true);
+ const after = clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+ assert.ok(cellsOf(sectionOf(after, 'sec_more')).some((c) => c.control.fieldName === 'new_extra'), 'the field is in its own section');
+ assert.deepStrictEqual(built.skipped.layout.filter((m) => /Notes section/.test(m)), []);
+ assert.strictEqual(cellsOf(sectionOf(after, 'section_notes'))[0].control.id, 'notescontrol');
+ assert.strictEqual((await verifyForms(h, spec)).checks.find((c) => c.kind === 'form-timeline').present, true);
+});
+
+// `--verify` runs on the form as it is published, BEFORE the build's field passes have taken out of the old Notes section the
+// fields the spec prunes or places elsewhere, and a build judges what the section still holds only after them. So verify has
+// to predict those passes: judging the published form as it stands would tell the maker to move by hand a field the build
+// moves or removes itself, when one plain build repairs the timeline. Each case seeds the old Notes section holding the
+// given fields, asks verify, builds and asks again — the advice has to be what the build then does.
+const MOVED_BY_ANCHOR = /\(fieldOptions places it after 'new_area', so it is moved there\) out of the Notes section$/;
+const holdsAndKeeps = (what) => new RegExp(`the Notes section also holds ${what}, which a build does not remove, so the build leaves the section as it is; move (?:it|them) out of it, or delete the section, in the maker, then run a full build of the spec`);
+// A field the form has more than once is one verify does not predict (a build acts on one of its cells, and which one is not the
+// published order): it says it cannot tell, and neither promises the repair nor sends the maker to do the build's work.
+const WHICH_CELL = 'a build acts on one cell of such a field, and which one depends on how it arranges the form';
+const IF_LEFT = 'If its report says the timeline was left as it is, move (?:that cell|those cells) out of the section in the maker and run a full build again';
+// Where the advice is not "a full build repairs it" — the section holds something that stays, or another control holds the id — what
+// it cannot tell is whether the build takes the field out first.
+const cannotTell = (what) => new RegExp(`verify cannot tell whether the build (?:also )?takes ${what} out of the Notes section first — ${WHICH_CELL}\\. ${IF_LEFT}`);
+// Where a full build would repair the timeline but for what verify cannot tell, the advice says what the build does unless it leaves the
+// field — a condition, not a promise.
+const mayLeave = (what) => new RegExp(`; the build repairs the timeline in place unless it leaves ${what} in the Notes section, and verify cannot tell whether it does — ${WHICH_CELL}\\. ${IF_LEFT}`);
+const anchored = (spec, anchors, over = {}) => { Object.assign(spec.forms[0], over, { fieldOptions: anchors }); return spec; };
+const withoutPrune = (spec) => Object.assign(spec.forms[0], { prune: false }) && spec;
+const WEB_RESOURCE_CELL = { control: { classId: '9FDF5F91-88B1-47F4-AD53-C11EFBB3E0D8', fieldName: null, label: 'Web resource', showLabel: false, parameters: {} } };
+// Two fields anchored one after the other: the build places new_other beside new_area first, and new_extra beside it once it is there.
+const CHAIN = { new_other: { after: 'new_area' }, new_extra: { after: 'new_other' } };
+const CHAIN_MOVED = /the field 'new_other' \(fieldOptions places it after 'new_area', so it is moved there\) and the field 'new_extra' \(fieldOptions places it after 'new_other', so it is moved there\) out of the Notes section$/;
+// Three: every link is moved out, whichever order the spec lists them in and the form holds them.
+const CHAIN3 = { new_third: { after: 'new_extra' }, new_extra: CHAIN.new_extra, new_other: CHAIN.new_other };
+const CHAIN3_MOVED = /the field 'new_third' \(fieldOptions places it after 'new_extra', so it is moved there\), the field 'new_other' \(fieldOptions places it after 'new_area', so it is moved there\) and the field 'new_extra' \(fieldOptions places it after 'new_other', so it is moved there\) out of the Notes section$/;
+
+const verifyBeforeBuild = [
+ // What the build takes out of the section: verify says so, and the SAME build repairs the timeline.
+ { name: 'a field the layout does not list, with prune on', spec: () => specFor(),
+ repairs: /\(your layout does not list it, so it is removed\) out of the Notes section, and removing a field needs --allow-destructive$/ },
+ // Moved beside its anchor and then pruned, in that order: the removal is what the maker is told, because that is what ends up happening.
+ { name: 'a field the layout does not list that a fieldOptions anchor also places', spec: () => anchored(specFor(), { new_extra: { after: 'new_area' } }),
+ repairs: /\(your layout does not list it, so it is removed\) out of the Notes section, and removing a field needs --allow-destructive$/ },
+ { name: 'a field the layout declares in another section', spec: () => { const s = specFor(); s.forms[0].tabs[0].sections[1].fields.push('new_extra'); return s; },
+ repairs: /\(your layout places it in section 'sec_more', so it is moved there\) out of the Notes section$/ },
+ { name: 'a field a fieldOptions anchor moves, on an explicit layout with prune off', spec: () => anchored(specFor(), { new_extra: { after: 'new_area' } }, { prune: false }), repairs: MOVED_BY_ANCHOR },
+ { name: 'a field a fieldOptions anchor moves, on an auto layout', spec: () => anchored(specFor({ layout: 'auto' }), { new_extra: { after: 'new_area' } }), repairs: MOVED_BY_ANCHOR },
+ { name: 'a field whose anchor the layout places but the form does not have yet', spec: () => anchored(specFor(), { new_extra: { after: 'new_code' } }, { prune: false }), formWithout: ['new_code'], repairs: /fieldOptions places it after 'new_code'/ },
+ { name: 'a field anchored to a field that is itself moved out of the section', hostFields: ['new_other', 'new_extra'],
+ spec: () => { const s = specFor(); s.forms[0].tabs[0].sections[1].fields.push('new_other'); return anchored(s, { new_extra: { after: 'new_other' } }, { prune: false }); },
+ repairs: /the field 'new_other' \(your layout places it in section 'sec_more', so it is moved there\) and the field 'new_extra' \(fieldOptions places it after 'new_other', so it is moved there\) out of the Notes section$/ },
+ // An anchor that is itself anchored is moved out first (dependency order), and the field anchored to it follows — however the spec lists them.
+ { name: 'a chain of anchors that both sit in the section, on an auto layout', hostFields: ['new_other', 'new_extra'], spec: () => anchored(specFor({ layout: 'auto' }), CHAIN), repairs: CHAIN_MOVED },
+ { name: 'a chain of anchors that both sit in the section, on an explicit layout with prune off', hostFields: ['new_other', 'new_extra'], spec: () => anchored(specFor(), CHAIN, { prune: false }), repairs: CHAIN_MOVED },
+ { name: 'a chain of anchors the spec lists last link first', hostFields: ['new_other', 'new_extra'],
+ spec: () => anchored(specFor({ layout: 'auto' }), { new_extra: CHAIN.new_extra, new_other: CHAIN.new_other }), repairs: CHAIN_MOVED },
+ // One inspector answers for every cell of the section, and the walks for a chain's cells overlap: with three links the walk for the
+ // first cell passes through the links the next questions start from.
+ { name: 'a chain of three anchors that all sit in the section, the spec listing the last link first', hostFields: ['new_third', 'new_other', 'new_extra'],
+ spec: () => anchored(specFor({ layout: 'auto' }), CHAIN3), repairs: CHAIN3_MOVED },
+ // What the build leaves where it is: the maker moves it, verify says which control it is, and the build refuses as told.
+ { name: 'a field an explicit layout with prune off does not mention', spec: () => withoutPrune(specFor()), stays: holdsAndKeeps("the field 'new_extra'") },
+ { name: 'a field an auto layout does not mention', spec: () => specFor({ layout: 'auto' }), stays: holdsAndKeeps("the field 'new_extra'") },
+ { name: 'a field anchored to a column neither the form nor the layout has', spec: () => anchored(specFor(), { new_extra: { after: 'new_unlisted' } }, { prune: false }), stays: holdsAndKeeps("the field 'new_extra'") },
+ { name: 'a field anchored to another field that stays in the same section', hostFields: ['new_extra', 'new_other'],
+ spec: () => anchored(specFor(), { new_extra: { after: 'new_other' } }, { prune: false }), stays: holdsAndKeeps("the field 'new_extra' and the field 'new_other'") },
+ { name: 'a chain of anchors whose first link has no anchor of its own', hostFields: ['new_other', 'new_extra'],
+ spec: () => anchored(specFor({ layout: 'auto' }), { new_extra: { after: 'new_other' } }), stays: holdsAndKeeps("the field 'new_other' and the field 'new_extra'") },
+ // Both at once: the field goes, the maker's own control does not — so the maker is told about that one only, and what the build does first.
+ { name: 'a field the build prunes and a control of the maker\u2019s own', hostCells: [WEB_RESOURCE_CELL], spec: () => specFor(),
+ stays: holdsAndKeeps('1 other control'), staysFirst: /the build first takes the field 'new_extra' \(your layout does not list it, so it is removed\) out of the Notes section, and removing a field needs --allow-destructive$/ },
+ // A field the form has twice, one cell of it in the section: which cell a build acts on is not the published order, so verify says
+ // it cannot tell — here the layout's own section comes first and the build leaves the section's cell (and reports it).
+ { name: 'a field the section holds a second time, the layout having placed its first cell', hostFields: ['new_code'], alsoElsewhere: true, spec: () => specFor(),
+ cannotTell: mayLeave("the field 'new_code' \\(it is on the form more than once\\)") },
+];
+
+for (const c of verifyBeforeBuild) {
+ test(`timeline: verify before the build and the build itself agree about ${c.name}`, async () => {
+ const hostFields = c.hostFields || ['new_extra'];
+ const h = newHarness({ attributes: { ...DEFAULT_ATTRIBUTES, new_other: 'String', new_third: 'String' } });
+ const spec = c.spec();
+ const host = oldNotesSection();
+ for (const field of hostFields) host.rows.push({ cells: [ai.fieldCellIntent(field)] });
+ for (const cell of c.hostCells || []) host.rows.push({ cells: [clone(cell)] });
+ const tabs = compiledTabs(spec, host);
+ // The form holds these fields in the Notes section alone (except the case that says otherwise).
+ const onlyInHost = c.alsoElsewhere ? [] : hostFields.concat(c.formWithout || []);
+ for (const section of tabs[0].columns[0].sections) {
+ if (section.name !== 'section_notes') section.rows = section.rows.filter((r) => !r.cells.some((cell) => onlyInHost.includes(cell.control.fieldName)));
+ }
+ await seedForm(h, tabs);
+ const timelineCheck = async () => (await verifyForms(h, spec)).checks.find((k) => k.kind === 'form-timeline');
+
+ // BEFORE the build.
+ const before = await timelineCheck();
+ assert.strictEqual(before.present, false);
+ assert.match(before.detail, /^the deployed form's timeline does not render: the control id is '[0-9a-f-]{36}', not 'notescontrol' and its cell spans 1 row — /);
+ if (c.repairs) {
+ assert.match(before.detail, /— run a full build of the spec \(not --changed-only, which skips a spec that has not changed\) to repair it in place; the build first takes /);
+ assert.match(before.detail, c.repairs);
+ assert.doesNotMatch(before.detail, /move (?:it|them) out of it|leaves? (?:it|the section) as it is|cannot tell/, 'the maker is not sent to do what the build does');
+ } else if (c.cannotTell) {
+ assert.match(before.detail, c.cannotTell);
+ assert.doesNotMatch(before.detail, /which a build does not remove|so the build leaves the section as it is|the build first takes|to repair it in place/, 'no promise of a repair and no certain refusal');
+ } else {
+ assert.match(before.detail, c.stays);
+ assert.doesNotMatch(before.detail, /repair it in place|cannot tell/);
+ if (c.staysFirst) assert.match(before.detail, c.staysFirst);
+ else assert.doesNotMatch(before.detail, /the build first takes/);
+ }
+
+ // THE BUILD — with no preflight, as a build with --allow-destructive is.
+ const first = await h.freshSdk();
+ const built = await runSdkBuild(spec, { sdk: first.sdk, apply: true, phases: ['forms'] });
+ assert.strictEqual(built.ok, true);
+ const refusals = built.skipped.layout.filter((m) => /Notes section's timeline was left as it is/.test(m));
+ const after = await timelineCheck();
+ if (c.repairs) {
+ assert.deepStrictEqual(refusals, [], 'the build repaired the timeline in one run');
+ assert.strictEqual(after.present, true, `verify passes after ONE build; got ${after.detail}`);
+ } else if (c.cannotTell) {
+ assert.strictEqual(refusals.length, 1, JSON.stringify(built.skipped.layout));
+ assert.strictEqual(after.present, false, 'nothing was repaired, so verify still fails');
+ assert.match(after.detail, c.cannotTell, 'and still says it cannot tell which cell a build acts on');
+ } else {
+ assert.strictEqual(refusals.length, 1, JSON.stringify(built.skipped.layout));
+ assert.match(refusals[0], /the section also holds other controls/);
+ assert.strictEqual(after.present, false, 'nothing was repaired, so verify still fails');
+ assert.match(after.detail, c.stays, 'and still says what to move');
+ assert.doesNotMatch(after.detail, /the build first takes/, 'what the build took out is gone');
+ }
+ });
+}
+
+// A field the published form holds in more than one cell is one verify does not predict: a build acts on ONE cell of a field in
+// each pass, the first it finds once the topology pass has reordered the sections — and that is not the published order. Each case
+// seeds a form whose published order differs from the build's (or whose field the prune removes one cell at a time), then asks
+// verify, builds and asks again: whichever way the build goes, what verify said has to have been true.
+// Verify, then the build (with no preflight, as a build with --allow-destructive is), then verify again, on the form `h` holds.
+async function verifyBuildVerify(h, spec) {
+ const timeline = async () => (await verifyForms(h, spec)).checks.find((k) => k.kind === 'form-timeline');
+ const before = await timeline();
+ const run = await h.freshSdk();
+ const warnings = [];
+ const built = await runSdkBuild(spec, { sdk: run.sdk, apply: true, phases: ['forms'], warn: (m) => warnings.push(String(m)) });
+ assert.strictEqual(built.ok, true, JSON.stringify(built.error || built.halt || ''));
+ const refusals = built.skipped.layout.filter((m) => /Notes section's timeline was left as it is/.test(m));
+ return { before, built, warnings, refusals, after: await timeline() };
+}
+// The old Notes section holding a cell of each of `fields`.
+const hostHolding = (...fields) => { const host = oldNotesSection(); for (const f of fields) host.rows.push({ cells: [ai.fieldCellIntent(f)] }); return host; };
+const columnOf = (tabs, tab = 0) => tabs[tab].columns[0];
+const namedIn = (column, ...names) => names.map((n) => column.sections.find((s) => s.name === n));
+const TWICE = "the field 'new_code' \\(it is on the form more than once\\)";
+
+test('timeline: a field the build orders ahead of the Notes section is the cell it acts on — verify, which sees the published order, does not promise the repair', async () => {
+ // new_code is declared in sec_main, which the form publishes AFTER the Notes section, with a cell of new_code in each. The
+ // build puts sec_main back in the layout's order first, so ITS cell is the one it finds first and the Notes section's stays.
+ const h = newHarness();
+ const spec = specFor();
+ spec.forms[0].tabs[0].sections = [
+ { name: 'sec_main', label: 'Main', columns: 2, fields: ['new_name', 'new_code'] },
+ { name: 'sec_more', label: 'More', columns: 1, fields: ['new_notes'] },
+ { name: 'sec_tail', label: 'Tail', columns: 1, fields: ['new_area'] },
+ ];
+ const tabs = compiledTabs(spec, hostHolding('new_code'));
+ columnOf(tabs).sections = namedIn(columnOf(tabs), 'sec_more', 'sec_tail', 'section_notes', 'sec_main');
+ await seedForm(h, tabs);
+ const { before, built, warnings, refusals, after } = await verifyBuildVerify(h, spec);
+
+ assert.strictEqual(before.present, false);
+ assert.match(before.detail, mayLeave(TWICE));
+ assert.doesNotMatch(before.detail, /the build first takes|which a build does not remove|to repair it in place/, 'neither the promise of a repair nor the certain refusal');
+ // What the build does: it reorders the sections, finds sec_main's cell first, leaves the section's, and says so.
+ assert.ok(warnings.some((m) => /moved \d+ section\(s\) in tab 'tab_a'.*to put them in the layout's order/.test(m)), JSON.stringify(warnings));
+ assert.strictEqual(refusals.length, 1, JSON.stringify(built.skipped.layout));
+ assert.strictEqual(after.present, false);
+ assert.match(after.detail, mayLeave(TWICE), 'and verify, asked again, still says it cannot tell — the cell is still there to be moved out');
+});
+
+test('timeline: a section the build moves to another tab takes its cell of a field with it — verify does not send the maker to do what the build then does', async () => {
+ // sec_code is declared in tab_b but published ahead of the Notes section in tab_a; the Notes section holds a second cell of new_code.
+ // The build moves sec_code to tab_b first, so the Notes section's cell is the one it finds first — and moves into sec_code.
+ const h = newHarness();
+ const spec = specFor();
+ spec.forms[0].tabs = [
+ { name: 'tab_a', label: 'A', sections: [{ name: 'sec_main', label: 'Main', columns: 2, fields: ['new_name'] }, { name: 'sec_more', label: 'More', columns: 1, fields: ['new_notes', 'new_area'] }] },
+ { name: 'tab_b', label: 'B', sections: [{ name: 'sec_code', label: 'Code', columns: 1, fields: ['new_code'] }] },
+ ];
+ const tabs = compiledTabs(spec, hostHolding('new_code'));
+ columnOf(tabs).sections.unshift(columnOf(tabs, 1).sections.shift());
+ await seedForm(h, tabs);
+ const { before, built, warnings, refusals, after } = await verifyBuildVerify(h, spec);
+
+ assert.match(before.detail, mayLeave(TWICE));
+ assert.doesNotMatch(before.detail, /which a build does not remove|so the build leaves the section as it is|to repair it in place/, 'the maker is not sent to move what the build moves');
+ assert.ok(warnings.some((m) => /moved section 'sec_code' from tab 'tab_a'.*to tab 'tab_b'/.test(m)), JSON.stringify(warnings));
+ assert.deepStrictEqual(refusals, [], JSON.stringify(built.skipped.layout));
+ assert.strictEqual(after.present, true, `verify passes after ONE build; got ${after.detail}`);
+ const form = clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+ assert.deepStrictEqual(cellsOf(sectionOf(form, 'sec_code')).map((c) => c.control.fieldName), ['new_code', 'new_code'], 'both cells of the field are in the section the layout declares');
+ assert.ok(!cellsOf(sectionOf(form, 'section_notes')).some((c) => c.control.fieldName), 'and none is left in the Notes section');
+});
+
+test('timeline: a pruned field the form has twice is removed one cell per run — verify cannot tell the first run, and is exact once one cell is left', async () => {
+ // new_extra is in sec_main (the first cell) and in the Notes section, and the layout does not list it. The prune removes one cell
+ // of a field per run, so the Notes section's survives the first build and the timeline is not repaired until the second.
+ const h = newHarness();
+ const spec = specFor();
+ const tabs = compiledTabs(spec, hostHolding('new_extra'));
+ sectionOf({ tabs }, 'sec_main').rows.push({ cells: [ai.fieldCellIntent('new_extra')] });
+ await seedForm(h, tabs);
+ const one = await verifyBuildVerify(h, spec);
+
+ assert.match(one.before.detail, mayLeave("the field 'new_extra' \\(it is on the form more than once\\)"));
+ assert.match(one.before.detail, /run a full build again \(removing a field needs --allow-destructive\)$/, 'a removal, which needs the flag');
+ assert.doesNotMatch(one.before.detail, /which a build does not remove/, 'a build does remove it — one cell a run');
+ assert.strictEqual(one.refusals.length, 1, 'the first build prunes the cell in sec_main and leaves the timeline');
+ assert.ok(!cellsOf(sectionOf(clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId)), 'sec_main')).some((c) => c.control.fieldName === 'new_extra'));
+ // With ONE cell left the field is predicted, and the build then does exactly that.
+ assert.strictEqual(one.after.present, false);
+ assert.match(one.after.detail, /to repair it in place; the build first takes the field 'new_extra' \(your layout does not list it, so it is removed\) out of the Notes section, and removing a field needs --allow-destructive$/);
+ assert.doesNotMatch(one.after.detail, /cannot tell|which a build does not remove/);
+ const two = await verifyBuildVerify(h, spec);
+ assert.deepStrictEqual(two.refusals, [], 'the second build repairs the timeline');
+ assert.strictEqual(two.after.present, true);
+});
+
+test('timeline: a field that no pass touches stays whichever cell a build acts on, so verify says so plainly — and names the second cell of a field the section holds twice', async () => {
+ const h = newHarness();
+ const spec = withoutPrune(specFor());
+ const tabs = compiledTabs(spec, hostHolding('new_extra', 'new_extra'));
+ sectionOf({ tabs }, 'sec_main').rows.push({ cells: [ai.fieldCellIntent('new_extra')] });
+ await seedForm(h, tabs);
+ const { before, refusals, after } = await verifyBuildVerify(h, spec);
+ const advice = /the Notes section also holds the field 'new_extra' and a second cell of the field 'new_extra', which a build does not remove, so the build leaves the section as it is; move them out of it, or delete the section, in the maker, then run a full build of the spec/;
+ assert.match(before.detail, advice);
+ assert.doesNotMatch(before.detail, /cannot tell|repair it in place/);
+ assert.strictEqual(refusals.length, 1);
+ assert.match(after.detail, advice, 'and the build leaves the form as it was');
+});
+
+test('timeline: an anchored field the form has twice is not predicted on an auto layout either — the build moves the cell it finds first, and verify says it cannot tell', async () => {
+ const h = newHarness();
+ const spec = anchored(specFor({ layout: 'auto' }), { new_extra: { after: 'new_area' } });
+ const tabs = compiledTabs(spec, hostHolding('new_extra'));
+ sectionOf({ tabs }, 'section_general').rows.push({ cells: [ai.fieldCellIntent('new_extra')] });
+ await seedForm(h, tabs);
+ const { before, refusals, after } = await verifyBuildVerify(h, spec);
+ assert.match(before.detail, mayLeave("the field 'new_extra' \\(it is on the form more than once\\)"));
+ assert.doesNotMatch(before.detail, /the build first takes|which a build does not remove|to repair it in place/);
+ // The build moves the first cell (section_general's) beside new_area and leaves the Notes section's, which it reports.
+ assert.strictEqual(refusals.length, 1);
+ assert.match(after.detail, mayLeave("the field 'new_extra' \\(it is on the form more than once\\)"));
+});
+
+test('timeline: an anchor the form has twice, one cell of it in the Notes section, is not relied on — verify says it cannot tell where the build finds it', async () => {
+ // new_code is in the Notes section (published first) and in section_general; new_extra, in the Notes section, is anchored to it.
+ // The build finds the anchor's first cell in the Notes section, where it places nothing, and the anchor's own cell stays there
+ // anyway — so the section is left whatever happens to new_extra, which verify says it cannot tell.
+ const h = newHarness();
+ const spec = anchored(specFor({ layout: 'auto' }), { new_extra: { after: 'new_code' } });
+ const tabs = compiledTabs(spec, hostHolding('new_code', 'new_extra'));
+ columnOf(tabs).sections = namedIn(columnOf(tabs), 'section_notes', 'section_general');
+ await seedForm(h, tabs);
+ const { before, refusals, after } = await verifyBuildVerify(h, spec);
+ assert.match(before.detail, /the Notes section also holds the field 'new_code', which a build does not remove, so the build leaves the section as it is; move it out of it, or delete the section, in the maker, then run a full build of the spec/);
+ assert.match(before.detail, cannotTell("the field 'new_extra' \\(its anchor 'new_code' is on the form more than once\\)"));
+ assert.doesNotMatch(before.detail, /repair it in place|the build first takes/);
+ assert.strictEqual(refusals.length, 1);
+ assert.strictEqual(after.present, false);
+});
+
+test('timeline: a chain of anchors that reaches a field the form has twice names THAT field — the anchor between has one cell, and the build moves it', async () => {
+ // new_extra is anchored after new_other, which is anchored after new_area; the form has new_area twice (section_general and the Notes
+ // section) and new_other once. Verify cannot tell where the build finds new_area, so it cannot tell for either field — but the reason
+ // it gives for new_extra must not call new_other, which has one cell, a field the form has more than once.
+ const h = newHarness({ attributes: { ...DEFAULT_ATTRIBUTES, new_other: 'String' } });
+ const spec = anchored(specFor({ layout: 'auto' }), { new_extra: { after: 'new_other' }, new_other: { after: 'new_area' } });
+ await seedForm(h, compiledTabs(spec, hostHolding('new_other', 'new_extra', 'new_area')));
+ const cellsOfField = (form, field) => sectionsOf(form).flatMap(cellsOf).filter((c) => c.control && c.control.fieldName === field).length;
+ const published = clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+ assert.deepStrictEqual([cellsOfField(published, 'new_other'), cellsOfField(published, 'new_area')], [1, 2], 'the premise: only new_area is on the form twice');
+ const { before, refusals, after } = await verifyBuildVerify(h, spec);
+
+ assert.match(before.detail, holdsAndKeeps("the field 'new_area'"));
+ assert.match(before.detail, cannotTell("the field 'new_other' \\(its anchor 'new_area' is on the form more than once\\) and the field 'new_extra' \\(its anchor 'new_other' follows 'new_area', which is on the form more than once\\)"));
+ assert.doesNotMatch(before.detail, /its anchor 'new_other' is on the form more than once/);
+ // What the build does: both fields go beside new_area; the section keeps the cell of new_area (which no rule moves) and is left, and said so.
+ const form = clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+ assert.deepStrictEqual(cellsOf(sectionOf(form, 'section_notes')).map((c) => c.control.fieldName).filter(Boolean), ['new_area']);
+ assert.strictEqual(refusals.length, 1);
+ assert.strictEqual(after.present, false);
+});
+
+test('timeline: a taken notescontrol id and a field the form has twice — verify names the id and still says it cannot tell, and freeing the id alone does not repair the timeline', async () => {
+ // new_code is in sec_main and in the old Notes section; sec_more holds a control of the maker's that already uses the id. Which cell
+ // of new_code a build acts on is not the published order, so whether the section is clear once the id is free is what verify cannot
+ // tell — and were that dropped while the id is named, freeing the id would look like the whole repair.
+ const spec = specFor();
+ const h = newHarness();
+ const tabs = compiledTabs(spec, hostHolding('new_code'));
+ sectionOf({ tabs }, 'sec_more').rows.push({ cells: [{ control: { ...WEB_RESOURCE_CELL.control, id: 'notescontrol' } }] });
+ await seedForm(h, tabs);
+ const taken = await verifyBuildVerify(h, spec);
+ assert.match(taken.before.detail, /another control on the form already uses the id 'notescontrol', so a build cannot give this timeline that id; remove or rename one of the two in the maker, then run a full build of the spec \(not --changed-only, which skips a spec that has not changed\)/);
+ assert.match(taken.before.detail, cannotTell(TWICE));
+ assert.doesNotMatch(taken.before.detail, /repair it in place|the build first takes/);
+ assert.strictEqual(taken.refusals.length, 1, JSON.stringify(taken.built.skipped.layout));
+ assert.strictEqual(taken.after.present, false);
+ assert.match(taken.after.detail, cannotTell(TWICE));
+ // The maker frees the id — the same form without that control — and ONE full build still leaves the timeline: the note was needed.
+ const freed = newHarness();
+ await seedForm(freed, compiledTabs(spec, hostHolding('new_code')));
+ const next = await verifyBuildVerify(freed, spec);
+ assert.match(next.before.detail, mayLeave(TWICE));
+ assert.strictEqual(next.refusals.length, 1, JSON.stringify(next.built.skipped.layout));
+ assert.strictEqual(next.after.present, false);
+});
+
+test('timeline: an auto layout that never had Notes gets the host when the spec asks for it, once', async () => {
+ const h = newHarness();
+ const spec = specFor({ layout: 'auto' });
+ await seedForm(h, compiledTabs(spec, null));
+ assert.ok(!h.store.row.formxml.includes('section_notes'));
+ const first = await h.freshSdk();
+ const warnings = [];
+ assert.strictEqual((await runSdkBuild(spec, { sdk: first.sdk, apply: true, phases: ['forms'], warn: (m) => warnings.push(String(m)) })).ok, true);
+ assert.ok(warnings.some((w) => /added the Notes section \(timeline\)/.test(w)));
+ const host = collapseEmptyRows(sectionXml(h.store.row.formxml, 'section_notes'));
+ assert.ok(host.includes(PLATFORM_CONTROL));
+ assert.match(host, /<row \/>×22<\/rows><\/section>$/);
+ const second = await h.freshSdk();
+ assert.strictEqual((await runSdkBuild(spec, { sdk: second.sdk, apply: true, phases: ['forms'] })).ok, true);
+ assert.deepStrictEqual(second.mutations, [], 'the second build adds no second host');
+ assert.strictEqual((h.store.row.formxml.match(/name="section_notes"/g) || []).length, 1);
+});
+
+// --- (c) the consumers of form topology accept the new shape ------------------------------------------------
+
+test('timeline: verify finds no timeline, an old one and a platform one — and asks nothing of a form that did not ask', async () => {
+ const spec = specFor({ layout: 'auto' });
+ const h = newHarness();
+ await seedForm(h, compiledTabs(spec, null));
+ const none = (await verifyForms(h, spec)).checks.find((c) => c.kind === 'form-timeline');
+ assert.strictEqual(none.present, false);
+ assert.match(none.detail, /asks for the Notes timeline, but the deployed form has no timeline control — run a full build of the spec \(not --changed-only, which skips a spec that has not changed\) to add it/);
+
+ const quiet = specFor({ layout: 'auto', notes: false });
+ assert.strictEqual((await verifyForms(h, quiet)).checks.some((c) => c.kind === 'form-timeline'), false, 'a form that did not ask is not checked');
+ const quickCreate = specFor({ layout: 'auto' });
+ quickCreate.forms[0].formType = 'QuickCreate';
+ assert.strictEqual((await verifyForms(h, quickCreate)).checks.some((c) => c.kind === 'form-timeline'), false, 'a QuickCreate form hosts no timeline');
+});
+
+test('timeline: a field with no declared section is never placed into the Notes host, even when the host comes first', async () => {
+ const h = newHarness();
+ // An auto layout whose form a maker reordered so the Notes host is the first section.
+ const spec = specFor({ layout: 'auto' });
+ const tabs = compiledTabs(spec);
+ const sections = tabs[0].columns[0].sections;
+ sections.unshift(sections.pop());
+ const general = sections.find((s) => s.name === 'section_general');
+ general.rows = general.rows.filter((r) => !r.cells.some((c) => c.control.fieldName === 'new_area')); // new_area is missing from the form
+ await seedForm(h, tabs);
+ const { sdk } = await h.freshSdk();
+ assert.strictEqual((await runSdkBuild(spec, { sdk, apply: true, phases: ['forms'] })).ok, true);
+ const after = clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+ assert.ok(cellsOf(sectionOf(after, 'section_general')).some((c) => c.control.fieldName === 'new_area'), 'new_area lands in the field section');
+ assert.deepStrictEqual(cellsOf(sectionOf(after, 'section_notes')).map((c) => c.control.fieldName), [null], 'the host still holds only its timeline');
+ assert.strictEqual(sectionOf(after, 'section_notes').rows.length, 23, 'and its spacer rows');
+});
+
+test('timeline: fieldOptions.after never anchors a placement inside the Notes host, so no field lands among its spacer rows', async () => {
+ const h = newHarness();
+ const spec = specFor();
+ spec.forms[0].prune = false;
+ spec.forms[0].fieldOptions = { new_area: { after: 'new_extra' } };
+ spec.entities[0].columns.push({ schemaName: 'new_extra', displayName: 'Extra', type: 'Text' });
+ // new_extra sits in the host (a maker put it there); new_area is in the field section and is asked to follow it.
+ const host = ai.notesSectionIntent(NOTES_CLASS_ID);
+ host.rows.push({ cells: [ai.fieldCellIntent('new_extra')] });
+ await seedForm(h, compiledTabs(spec, host));
+ const before = clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+ const { sdk } = await h.freshSdk();
+ const built = await runSdkBuild(spec, { sdk, apply: true, phases: ['forms'] });
+ assert.strictEqual(built.ok, true);
+ const after = clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId));
+ assert.deepStrictEqual(sectionOf(after, 'section_notes'), sectionOf(before, 'section_notes'), 'the host is exactly as it was');
+ assert.ok(built.skipped.layout.some((m) => /placement of 'new_area' after 'new_extra' was skipped - the anchor sits in a section the build owns/.test(m)), JSON.stringify(built.skipped.layout));
+});
+
+test('timeline: a host a maker widened is not re-flowed, so its spacer rows survive the rebuild that narrows the grid', async () => {
+ const h = newHarness();
+ const spec = specFor();
+ const wide = ai.notesSectionIntent(NOTES_CLASS_ID);
+ wide.columns = 2;
+ await seedForm(h, compiledTabs(spec, wide));
+ const { sdk, mutations } = await h.freshSdk();
+ assert.strictEqual((await runSdkBuild(spec, { sdk, apply: true, phases: ['forms'] })).ok, true);
+ const host = sectionOf(clone(await (await h.freshSdk()).sdk.fetchArtifact('form', h.formId)), 'section_notes');
+ assert.strictEqual(host.columns, 1, 'the engine\u2019s own grid width is converged as before');
+ assert.strictEqual(host.rows.length, 23, 'the 22 rows its cell spans are kept');
+ assert.strictEqual(cellsOf(host)[0].rowspan, 23);
+ // Kept — not deleted by a re-flow and written back by the timeline repair that follows: the only write is the width.
+ assert.deepStrictEqual(layoutMutations(mutations).map((m) => [m.method, m.args[3]]), [['updateElement', { columns: 1 }]]);
+});
+
+test('timeline: the form wireframe shows one Notes / Timeline block and nothing for the 22 rows it spans', () => {
+ const spec = specFor({ layout: 'auto' });
+ const wire = renderFormWireframe(spec, spec.forms[0]);
+ assert.strictEqual((wire.match(/Notes \/ Timeline/g) || []).length, 1);
+ const without = renderFormWireframe(specFor({ layout: 'auto', notes: false }), specFor({ layout: 'auto', notes: false }).forms[0]);
+ assert.strictEqual(wire.split('\n').length - without.split('\n').length, 2, 'the block is a rule and one description line');
+});
diff --git a/plugins/model-apps/scripts/tests/form-timeline.test.js b/plugins/model-apps/scripts/tests/form-timeline.test.js
new file mode 100644
index 000000000..d7c4a50fd
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/form-timeline.test.js
@@ -0,0 +1,669 @@
+'use strict';
+// The timeline's shape (lib/form-timeline.js): what the compiler writes, what a deployed timeline lacks, and
+// what the build and verify read it by — and verify's model of what a build does with the other cells of a
+// Notes host (notesHostInspector). Pure — the real-bundle tests prove the SDK serializes it, and that the model
+// agrees with a real build.
+const test = require('node:test');
+const assert = require('node:assert');
+const {
+ TIMELINE_CLASS_ID, TIMELINE_CONTROL_ID, TIMELINE_ROWSPAN, TIMELINE_AUTO,
+ isTimelineControl, timelineCellIntent, timelineRowsIntent, wantsTimeline,
+ timelineInSection, timelinesOf, controlIdTaken, timelineRepairPlan, timelineProblem,
+ timelineRefusal, timelineVerifyProblem,
+} = require('../lib/form-timeline.js');
+const { rowOccupancy, strandedRows } = require('../lib/form-occupancy.js');
+// verify's model of what a build does with the other cells of a Notes host (see the last tests here).
+const { notesHostInspector } = require('../lib/verify-spec.js');
+
+// The shape an older build wrote: a control with a generated id in a one-row cell.
+const oldHost = (over = {}) => ({
+ name: 'section_notes', columns: 1,
+ rows: [{ cells: [Object.assign({ rowspan: 1, control: { id: '9d6a0e0a-1b6c-4c4b-8f30-0a1f9a1d3c11', classId: TIMELINE_CLASS_ID.toLowerCase(), fieldName: null } }, over)] }],
+});
+const platformHost = () => ({
+ name: 'section_notes', columns: 1,
+ rows: timelineRowsIntent(TIMELINE_CLASS_ID),
+});
+// A host as the platform or a maker leaves it: a timeline cell `rowspan` rows tall under `notescontrol`, with
+// `below` rows after its own (N-1 by default) and an `auto` attribute only when given.
+const tallHost = ({ rowspan, below = rowspan - 1, auto, colspan = 1 }) => {
+ const cell = { rowspan, colspan, control: { id: 'notescontrol', classId: TIMELINE_CLASS_ID, fieldName: null } };
+ if (auto !== undefined) cell.bag = { a: [['auto', auto]], c: [] };
+ return { name: 'section_notes', columns: colspan, rows: [{ cells: [cell] }, ...Array.from({ length: below }, () => ({ cells: [] }))] };
+};
+
+test('timeline: the platform shape is control id notescontrol, a 23-row cell with auto=false, and 22 empty rows', () => {
+ assert.strictEqual(TIMELINE_CONTROL_ID, 'notescontrol');
+ assert.strictEqual(TIMELINE_ROWSPAN, 23);
+ const cell = timelineCellIntent(TIMELINE_CLASS_ID);
+ assert.strictEqual(cell.control.id, 'notescontrol');
+ assert.strictEqual(cell.control.classId, TIMELINE_CLASS_ID);
+ assert.strictEqual(cell.control.fieldName, null);
+ assert.strictEqual(cell.control.showLabel, false);
+ assert.strictEqual(cell.control.label, 'Notes');
+ assert.strictEqual(cell.rowspan, 23);
+ assert.deepStrictEqual(cell.bag.a.find((p) => p[0] === 'auto'), ['auto', 'false']);
+ // The platform spells these out and the SDK would omit them as defaults, so they are in the bag too.
+ assert.deepStrictEqual(cell.bag.a.find((p) => p[0] === 'showlabel'), ['showlabel', 'false']);
+ assert.deepStrictEqual(cell.bag.a.find((p) => p[0] === 'rowspan'), ['rowspan', '23']);
+ const rows = timelineRowsIntent(TIMELINE_CLASS_ID);
+ assert.strictEqual(rows.length, 23);
+ assert.strictEqual(rows[0].cells.length, 1);
+ assert.deepStrictEqual(rows.slice(1), Array.from({ length: 22 }, () => ({ cells: [] })), '22 empty spacer rows');
+ assert.notStrictEqual(rows[1], rows[2], 'each spacer row is its own object (the SDK mints identity per node)');
+});
+
+test('timeline: a 23-row span over 22 spacer rows occupies one column of a one-column section, and no spacer is stranded', () => {
+ const rows = platformHost().rows;
+ const occupancy = rowOccupancy(rows);
+ assert.strictEqual(occupancy.length, 23);
+ assert.ok(occupancy.every((o) => o.used <= 1), 'no row overflows the one-column section');
+ assert.deepStrictEqual(occupancy.slice(1).map((o) => o.reserved), Array(22).fill(1), 'every spacer row is reserved by the span above');
+ // The empty-row prune keeps a row a span still reserves: asked about the whole span, it removes nothing.
+ assert.deepStrictEqual(strandedRows(rows, 0, 23), []);
+ assert.deepStrictEqual(strandedRows(rows, 5, 1), []);
+ // …and it does remove them once nothing reserves them, so the guard is the span and not the empty row.
+ assert.deepStrictEqual(strandedRows(rows.slice(1), 0, 22), Array.from({ length: 22 }, (_, i) => 21 - i));
+});
+
+test('timeline: only an unbound control of the timeline class is a timeline, whichever way the class id is written', () => {
+ for (const classId of [TIMELINE_CLASS_ID, TIMELINE_CLASS_ID.toLowerCase(), `{${TIMELINE_CLASS_ID}}`, `{${TIMELINE_CLASS_ID.toLowerCase()}}`]) {
+ assert.strictEqual(isTimelineControl({ classId, fieldName: null }), true, classId);
+ assert.strictEqual(isTimelineControl({ classId }), true, `${classId} without a field name (published FormXML)`);
+ }
+ assert.strictEqual(isTimelineControl({ classId: TIMELINE_CLASS_ID, fieldName: 'new_name' }), false, 'a bound control is a field');
+ assert.strictEqual(isTimelineControl({ classId: 'E7A81278-8635-4D9E-8D4D-59480B391C5B' }), false);
+ assert.strictEqual(isTimelineControl(null), false);
+});
+
+test('timeline: a form asks for the timeline through notes:true or its table\u2019s hasNotes, on a Main form only', () => {
+ const spec = { entities: [{ schemaName: 'new_a', hasNotes: true }, { schemaName: 'new_b' }] };
+ assert.strictEqual(wantsTimeline(spec, { entity: 'new_b', notes: true }), true);
+ assert.strictEqual(wantsTimeline(spec, { entity: 'NEW_A' }), true, 'hasNotes on the table, matched ignoring case');
+ assert.strictEqual(wantsTimeline(spec, { entity: 'new_b' }), false);
+ assert.strictEqual(wantsTimeline(spec, { entity: 'new_b', notes: 'yes' }), false, 'only a boolean true asks');
+ for (const formType of ['QuickCreate', 'QuickView']) assert.strictEqual(wantsTimeline(spec, { entity: 'new_a', formType, notes: true }), false, formType);
+ assert.strictEqual(wantsTimeline(spec, { entity: 'new_a', formType: 'Main' }), true);
+ assert.strictEqual(wantsTimeline(spec, { entity: 'new_unknown' }), false, 'a form of an undeclared table has no hasNotes to read');
+});
+
+test('timeline: it is found in the SDK tree and in the published-FormXML parse alike, with where it sits', () => {
+ const sdkShape = platformHost();
+ const found = timelineInSection(sdkShape);
+ assert.deepStrictEqual([found.rowIndex, found.cellIndex, found.rowspan, found.rowsBelow, found.onlyCell, found.id, found.auto], [0, 0, 23, 22, true, 'notescontrol', 'false']);
+ // verify's parse of `<cell colspan="1" rowspan="23" auto="false"><control id="notescontrol" classid="{…}" />` + 22 `<row />`
+ const parsed = { rows: [{ cells: [{ colspan: 1, rowspan: 23, auto: 'false', control: { id: 'notescontrol', classId: `{${TIMELINE_CLASS_ID}}` } }] }, ...Array.from({ length: 22 }, () => ({ cells: [] }))] };
+ const again = timelineInSection(parsed);
+ assert.deepStrictEqual([again.rowspan, again.rowsBelow, again.id, again.auto], [23, 22, 'notescontrol', 'false']);
+ assert.strictEqual(timelineInSection({ rows: [{ cells: [{ control: { fieldName: 'new_name' } }] }] }), null);
+ assert.strictEqual(timelineInSection({}), null);
+ // A host a maker added a field to is not "only" the timeline.
+ const mixed = oldHost();
+ mixed.rows.push({ cells: [{ control: { fieldName: 'new_x' } }] });
+ assert.strictEqual(timelineInSection(mixed).onlyCell, false);
+ // The first timeline in reading order is the one reported, wherever it is.
+ const form = { tabs: [{ columns: [{ sections: [{ rows: [] }, platformHost()] }, { sections: [oldHost()] }] }] };
+ assert.deepStrictEqual(timelinesOf(form.tabs).map((t) => [t.ti, t.ci, t.si]), [[0, 0, 1], [0, 1, 0]]);
+});
+
+test('timeline repair plan: an old host lacks the id, the span, the rows under it and auto — a platform host lacks nothing', () => {
+ assert.deepStrictEqual(timelineRepairPlan(timelineInSection(oldHost())), { id: 'notescontrol', rowspan: 23, addRows: 22, auto: 'false' });
+ assert.deepStrictEqual(timelineRepairPlan(timelineInSection(platformHost())), {});
+ // Only what is missing is planned: a maker who fixed the id by hand keeps it.
+ const idOnly = oldHost();
+ idOnly.rows[0].cells[0].control.id = 'notescontrol';
+ assert.deepStrictEqual(timelineRepairPlan(timelineInSection(idOnly)), { rowspan: 23, addRows: 22, auto: 'false' });
+});
+
+test('timeline repair plan: a span the maker already set above one row is respected; only the rows that back it are added', () => {
+ const sized = oldHost({ rowspan: 8 });
+ sized.rows[0].cells[0].control.id = 'notescontrol';
+ sized.rows[0].cells[0].bag = { a: [['auto', 'false']], c: [] };
+ assert.deepStrictEqual(timelineRepairPlan(timelineInSection(sized)), { addRows: 7 }, 'kept at 8, with the 7 rows it spans');
+ for (let i = 0; i < 7; i += 1) sized.rows.push({ cells: [] });
+ assert.deepStrictEqual(timelineRepairPlan(timelineInSection(sized)), {}, 'a host the maker sized is already in shape');
+ const partial = platformHost();
+ partial.rows.length = 10;
+ assert.deepStrictEqual(timelineRepairPlan(timelineInSection(partial)), { addRows: 13 }, 'rows a maker deleted are put back');
+});
+
+// Platform forms do not share one height: the timeline on Account, Contact and others is a cell of 20, 5, 23 rows,
+// each followed by exactly the rows it spans, and a maker can resize it in the designer. `auto="false"` is on some
+// and absent on others, and the cell is one column wide or two. None of that is a defect to repair.
+test('timeline repair plan: a cell of any height with the rows it spans is in shape — whatever its auto and its width', () => {
+ for (const host of [
+ tallHost({ rowspan: 20 }), // no `auto`, as on the Account form
+ tallHost({ rowspan: 5, auto: 'false', colspan: 2 }), // as on the Contact form
+ tallHost({ rowspan: 23, auto: 'false' }),
+ tallHost({ rowspan: 2 }),
+ tallHost({ rowspan: 40, auto: 'true' }),
+ ]) {
+ const found = timelineInSection(host);
+ assert.deepStrictEqual(timelineRepairPlan(found), {}, `${found.rowspan} rows, auto ${found.auto}`);
+ assert.strictEqual(timelineProblem(found), '');
+ assert.strictEqual(timelineProblem(found, { host: true }), '', 'the engine\u2019s own host included');
+ }
+ // Rows a resize left behind are not the build's to delete.
+ assert.deepStrictEqual(timelineRepairPlan(timelineInSection(tallHost({ rowspan: 5, below: 22 }))), {});
+});
+
+test('timeline repair plan: a cell that only lacks rows is given those rows — to ITS height, not the platform\u2019s — and auto is not written for it', () => {
+ assert.deepStrictEqual(timelineRepairPlan(timelineInSection(tallHost({ rowspan: 5, below: 1 }))), { addRows: 3 });
+ assert.deepStrictEqual(timelineRepairPlan(timelineInSection(tallHost({ rowspan: 20, below: 0, auto: 'false' }))), { addRows: 19 });
+ // `auto` comes with converting a cell an older build wrote (a new id or a new span), never by itself.
+ const wrongId = tallHost({ rowspan: 8 });
+ wrongId.rows[0].cells[0].control.id = '9d6a0e0a-1b6c-4c4b-8f30-0a1f9a1d3c11';
+ assert.deepStrictEqual(timelineRepairPlan(timelineInSection(wrongId)), { id: 'notescontrol', auto: 'false' });
+ assert.deepStrictEqual(timelineRepairPlan(timelineInSection(tallHost({ rowspan: 8, auto: 'true' }))), {}, 'a value a maker set is not overwritten while nothing else needs writing');
+});
+
+test('timeline problem: a generated id and a one-row cell are why it does not render; the spacer rows and auto are not the verdict', () => {
+ assert.strictEqual(timelineProblem(timelineInSection(platformHost())), '');
+ assert.match(timelineProblem(timelineInSection(oldHost())), /control id is '9d6a0e0a-1b6c-4c4b-8f30-0a1f9a1d3c11', not 'notescontrol' and its cell spans 1 row/);
+ const noId = timelineInSection({ rows: [{ cells: [{ rowspan: 23, control: { classId: TIMELINE_CLASS_ID } }] }] });
+ assert.match(timelineProblem(noId), /control id is '\(none\)'/);
+ const bareButTall = platformHost();
+ bareButTall.rows.length = 1;
+ delete bareButTall.rows[0].cells[0].bag;
+ assert.strictEqual(timelineProblem(timelineInSection(bareButTall)), '', 'the verdict is the id and the span, which a maker\u2019s own timeline also has');
+ assert.strictEqual(TIMELINE_AUTO, 'false');
+});
+
+test('timeline problem: the engine\u2019s own host is judged by its rows too — the build converges them — and a maker\u2019s timeline is not', () => {
+ const unbacked = timelineInSection(tallHost({ rowspan: 20, below: 3 }));
+ assert.strictEqual(timelineProblem(unbacked), '', 'a timeline a maker added: the id and the span');
+ assert.strictEqual(timelineProblem(unbacked, { host: true }), 'its cell spans 20 rows but only 3 row(s) follow it');
+ assert.strictEqual(timelineProblem(timelineInSection(tallHost({ rowspan: 20, below: 19 })), { host: true }), '');
+ assert.strictEqual(timelineProblem(timelineInSection(tallHost({ rowspan: 5, below: 30 })), { host: true }), '', 'more rows than the span needs is not a problem');
+ // Both reasons are said when both hold.
+ const both = tallHost({ rowspan: 1 });
+ both.rows[0].cells[0].control.id = 'generated';
+ assert.match(timelineProblem(timelineInSection(both), { host: true }), /^the control id is 'generated', not 'notescontrol' and its cell spans 1 row$/);
+});
+
+test('timeline control id: a second `notescontrol` is detected wherever it is, and the control itself is excepted', () => {
+ const host = platformHost();
+ const other = { rows: [{ cells: [{ control: { id: 'NotesControl', classId: 'x' } }] }] };
+ const tabs = [{ columns: [{ sections: [host, other] }] }];
+ assert.strictEqual(controlIdTaken(tabs, 'notescontrol'), true);
+ assert.strictEqual(controlIdTaken(tabs, 'notescontrol', host.rows[0].cells[0].control), true, 'the other one still counts');
+ assert.strictEqual(controlIdTaken([{ columns: [{ sections: [host] }] }], 'notescontrol', host.rows[0].cells[0].control), false, 'a control is not a duplicate of itself');
+ assert.strictEqual(controlIdTaken([], 'notescontrol'), false);
+});
+
+// --- why a build declines to repair a host, and what --verify says to do about it ---------------------------------
+
+// The published form's tabs, holding the given sections in one form-column. `isHost` is what verify asks of a section:
+// whether it is the engine's own Notes host (the section the compiler names `section_notes`).
+const formTabs = (...sections) => [{ columns: [{ sections }] }];
+const isHost = (section) => section.name === 'section_notes';
+const makerControl = (id) => ({ name: 'maker_section', rows: [{ cells: [{ control: { id, classId: '{9fdf5f91-88b1-47f4-ad53-c11efbb3e0d8}' } }] }] });
+const hostWith = (...more) => { const host = oldHost(); for (const cell of more) host.rows.push({ cells: [cell] }); return host; };
+
+test('timeline refusal: a host the build can repair has none — an old one, a short one, a host already in shape', () => {
+ for (const host of [oldHost(), tallHost({ rowspan: 20, below: 3 }), platformHost()]) {
+ const tabs = formTabs(host);
+ assert.strictEqual(timelineRefusal(tabs, timelineInSection(host)), null);
+ }
+});
+
+test('timeline refusal: a host that also holds another control is refused — and its other control is why, not the id', () => {
+ const host = hostWith({ control: { fieldName: 'new_x' } });
+ assert.strictEqual(timelineRefusal(formTabs(host), timelineInSection(host)), 'other-controls');
+ // A host already in shape needs nothing, so it is never refused for what else it holds.
+ const inShape = platformHost();
+ inShape.rows.push({ cells: [{ control: { fieldName: 'new_x' } }] });
+ assert.strictEqual(timelineRefusal(formTabs(inShape), timelineInSection(inShape)), null);
+ // Both reasons at once: the build tests the section's other controls first, so it is the one reported.
+ const both = hostWith({ control: { fieldName: 'new_x' } });
+ assert.strictEqual(timelineRefusal(formTabs(both, makerControl('notescontrol')), timelineInSection(both)), 'other-controls');
+});
+
+test('timeline refusal: an old host whose id another control already holds is refused — a host that has the id itself is not', () => {
+ const host = oldHost();
+ assert.strictEqual(timelineRefusal(formTabs(host, makerControl('notescontrol')), timelineInSection(host)), 'id-taken');
+ assert.strictEqual(timelineRefusal(formTabs(host, makerControl('NotesControl')), timelineInSection(host)), 'id-taken', 'ids compared ignoring case');
+ assert.strictEqual(timelineRefusal(formTabs(host, makerControl('something_else')), timelineInSection(host)), null);
+ // The host's own id is not "taken": only a second control by that id is.
+ const idRight = oldHost();
+ idRight.rows[0].cells[0].control.id = 'notescontrol';
+ assert.strictEqual(timelineRefusal(formTabs(idRight), timelineInSection(idRight)), null);
+});
+
+const FULL_BUILD = /run a full build of the spec \(not --changed-only, which skips a spec that has not changed\)/;
+
+test('timeline verify: a form that carries a timeline that renders has nothing to report — whoever added it', () => {
+ assert.strictEqual(timelineVerifyProblem(formTabs(platformHost()), isHost), '');
+ assert.strictEqual(timelineVerifyProblem(formTabs(tallHost({ rowspan: 5 })), isHost), '');
+ // A timeline a maker added, in a section of their own, is as good as the engine's.
+ const own = tallHost({ rowspan: 8 });
+ own.name = 'maker_timeline';
+ assert.strictEqual(timelineVerifyProblem(formTabs(oldHost(), own), isHost), '', 'one that renders is enough, whatever else is on the form');
+});
+
+test('timeline verify: an old host the build can repair says to run a FULL build — --changed-only skips a spec that has not changed', () => {
+ const problem = timelineVerifyProblem(formTabs(oldHost()), isHost);
+ assert.match(problem, /^the deployed form's timeline does not render: the control id is '9d6a0e0a-1b6c-4c4b-8f30-0a1f9a1d3c11', not 'notescontrol' and its cell spans 1 row — /);
+ assert.match(problem, FULL_BUILD);
+ assert.match(problem, /to repair it in place$/);
+});
+
+test('timeline verify: a host the build declines to repair says why, and does not promise a repair it will not make', () => {
+ const crowded = timelineVerifyProblem(formTabs(hostWith({ control: { fieldName: 'new_x' } })), isHost);
+ assert.match(crowded, /^the deployed form's timeline does not render: /);
+ assert.match(crowded, /the Notes section also holds other controls, so a build leaves it as it is; move them out of it, or delete the section, in the maker, then run a full build/);
+ assert.match(crowded, FULL_BUILD);
+ assert.doesNotMatch(crowded, /repair it in place/);
+
+ const taken = timelineVerifyProblem(formTabs(oldHost(), makerControl('notescontrol')), isHost);
+ assert.match(taken, /another control on the form already uses the id 'notescontrol', so a build cannot give this timeline that id; remove or rename one of the two in the maker, then run a full build/);
+ assert.match(taken, FULL_BUILD);
+ assert.doesNotMatch(taken, /repair it in place/);
+});
+
+test('timeline verify: the engine\u2019s own host is the one reported when a maker\u2019s timeline does not render either', () => {
+ const own = tallHost({ rowspan: 1 });
+ own.name = 'maker_timeline';
+ own.rows[0].cells[0].control.id = 'maker_notes';
+ const problem = timelineVerifyProblem(formTabs(own, oldHost()), isHost);
+ assert.match(problem, /control id is '9d6a0e0a-1b6c-4c4b-8f30-0a1f9a1d3c11'/, 'the host, which the build repairs');
+ assert.doesNotMatch(problem, /maker_notes/);
+});
+
+test('timeline verify: a timeline the maker added that does not render is left alone by the build — it adds its own Notes section beside it, unless the id is taken', () => {
+ const own = tallHost({ rowspan: 1 });
+ own.name = 'maker_timeline';
+ own.rows[0].cells[0].control.id = 'maker_notes';
+ const free = timelineVerifyProblem(formTabs(own), isHost);
+ assert.match(free, /^the deployed form's timeline does not render: the control id is 'maker_notes', not 'notescontrol' and its cell spans 1 row — it is a timeline the build did not add, so a build leaves it as it is; run a full build/);
+ assert.match(free, FULL_BUILD);
+ assert.match(free, /to add the Notes section beside it$/);
+
+ // The same timeline holding the id, in a one-row cell: no second `notescontrol` is made, so a full build is no remedy.
+ const holder = tallHost({ rowspan: 1 });
+ holder.name = 'maker_timeline';
+ const blocked = timelineVerifyProblem(formTabs(holder), isHost);
+ assert.match(blocked, /^the deployed form's timeline does not render: its cell spans 1 row — it is a timeline the build did not add, so a build leaves it as it is, and adds no Notes section while a control uses the id 'notescontrol'; fix it in the maker \(the id 'notescontrol' and a cell spanning more than one row\) or delete it, then run a full build/);
+});
+
+test('timeline verify: a form with no timeline is told to run a full build to add one — unless another control holds the id a timeline needs', () => {
+ const none = timelineVerifyProblem(formTabs({ name: 'section_general', rows: [{ cells: [{ control: { fieldName: 'new_name' } }] }] }), isHost);
+ assert.match(none, /^the spec asks for the Notes timeline, but the deployed form has no timeline control — run a full build of the spec/);
+ assert.match(none, FULL_BUILD);
+ assert.match(none, /to add it$/);
+ assert.match(timelineVerifyProblem([], isHost), /has no timeline control — run a full build/, 'a form with no tabs at all');
+
+ const blocked = timelineVerifyProblem(formTabs(makerControl('notescontrol')), isHost);
+ assert.match(blocked, /^the spec asks for the Notes timeline, but the deployed form has no timeline control, and another control already uses the id 'notescontrol' that a timeline needs, so a build adds none — remove or rename that control in the maker, then run a full build/);
+ assert.doesNotMatch(blocked, /to add it/);
+});
+
+// --- what a build does with the host's OTHER cells before it judges the section ----------------------------------------
+
+test('timeline: the cells a section holds besides its timeline are reported with it — spacer rows are not cells', () => {
+ assert.deepStrictEqual(timelineInSection(platformHost()).others, []);
+ assert.deepStrictEqual(timelineInSection(oldHost()).others, []);
+ const field = { control: { fieldName: 'new_x' } };
+ const web = { control: { classId: '{9fdf5f91-88b1-47f4-ad53-c11efbb3e0d8}' } };
+ const host = hostWith(field, web);
+ host.rows.push({ cells: [] });
+ const found = timelineInSection(host);
+ assert.strictEqual(found.others.length, 2);
+ assert.strictEqual(found.others[0], field, 'the very cells of the tree, so a caller can tell which is which');
+ assert.strictEqual(found.others[1], web);
+ assert.strictEqual(found.onlyCell, false);
+});
+
+test('timeline refusal: a cell the build takes out first is no obstacle — one that stays still is, and so is an id another control holds', () => {
+ const stray = { control: { fieldName: 'new_x' } };
+ const kept = { control: { fieldName: 'new_y' } };
+ const one = hostWith(stray);
+ const oneFound = timelineInSection(one);
+ assert.strictEqual(timelineRefusal(formTabs(one), oneFound), 'other-controls', 'judged as published, every other cell counts');
+ assert.strictEqual(timelineRefusal(formTabs(one), oneFound, { leaving: [stray] }), null);
+ assert.strictEqual(timelineRefusal(formTabs(one), oneFound, { leaving: [{ control: { fieldName: 'new_x' } }] }), 'other-controls', 'a cell is itself, not whatever looks like it');
+ const two = hostWith(stray, kept);
+ assert.strictEqual(timelineRefusal(formTabs(two), timelineInSection(two), { leaving: [stray] }), 'other-controls', 'the one that stays refuses');
+ assert.strictEqual(timelineRefusal(formTabs(two), timelineInSection(two), { leaving: [stray, kept] }), null);
+ // The id is its own reason: a cell leaving frees nothing another control holds.
+ assert.strictEqual(timelineRefusal(formTabs(one, makerControl('notescontrol')), oneFound, { leaving: [stray] }), 'id-taken');
+});
+
+test('timeline verify: a field the build takes out of the host first is not left to the maker — the advice is to build, and says what the build does first', () => {
+ const tabs = formTabs(hostWith({ control: { fieldName: 'new_x' } }));
+ const removed = timelineVerifyProblem(tabs, isHost, { inspect: () => ({ name: "the field 'new_x'", goes: 'your layout does not list it, so it is removed', destructive: true }) });
+ assert.match(removed, /^the deployed form's timeline does not render: .* — run a full build of the spec \(not --changed-only, which skips a spec that has not changed\) to repair it in place; the build first takes the field 'new_x' \(your layout does not list it, so it is removed\) out of the Notes section, and removing a field needs --allow-destructive$/);
+ assert.doesNotMatch(removed, /move (?:it|them) out|as it is/);
+ // A move is not a removal: nothing there needs the flag.
+ const moved = timelineVerifyProblem(tabs, isHost, { inspect: () => ({ name: "the field 'new_x'", goes: "your layout places it in section 'sec_more', so it is moved there" }) });
+ assert.match(moved, /to repair it in place; the build first takes the field 'new_x' \(your layout places it in section 'sec_more', so it is moved there\) out of the Notes section$/);
+ assert.doesNotMatch(moved, /--allow-destructive/);
+ // A cell it cannot name is still said to go.
+ assert.match(timelineVerifyProblem(tabs, isHost, { inspect: () => ({ goes: 'it is moved' }) }), /the build first takes a control \(it is moved\) out of the Notes section$/);
+ // Several are each named, and the flag is for the removal among them.
+ const cells = [{ control: { fieldName: 'new_a' } }, { control: { fieldName: 'new_b' } }, { control: { fieldName: 'new_c' } }];
+ const verdicts = new Map([
+ [cells[0], { name: "the field 'new_a'", goes: 'moved' }],
+ [cells[1], { name: "the field 'new_b'", goes: 'removed', destructive: true }],
+ [cells[2], { name: "the field 'new_c'", goes: 'moved too' }],
+ ]);
+ const several = timelineVerifyProblem(formTabs(hostWith(...cells)), isHost, { inspect: (cell) => verdicts.get(cell) });
+ assert.match(several, /; the build first takes the field 'new_a' \(moved\), the field 'new_b' \(removed\) and the field 'new_c' \(moved too\) out of the Notes section, and removing a field needs --allow-destructive$/);
+});
+
+test('timeline verify: a host that still holds what the build leaves is told which control to move, and what the build takes out first', () => {
+ const leaves = { control: { fieldName: 'new_a' } };
+ const keeps = { control: { fieldName: 'new_b' } };
+ const web = { control: { classId: '{9fdf5f91-88b1-47f4-ad53-c11efbb3e0d8}' } };
+ const verdicts = new Map([
+ [leaves, { name: "the field 'new_a'", goes: 'your layout does not list it, so it is removed', destructive: true }],
+ [keeps, { name: "the field 'new_b'" }],
+ ]);
+ const inspect = (cell) => verdicts.get(cell); // nothing for a cell it knows nothing about
+ const one = timelineVerifyProblem(formTabs(hostWith(leaves, keeps)), isHost, { inspect });
+ assert.match(one, / — the Notes section also holds the field 'new_b', which a build does not remove, so the build leaves the section as it is; move it out of it, or delete the section, in the maker, then run a full build of the spec \(not --changed-only, which skips a spec that has not changed\); the build first takes the field 'new_a' \(your layout does not list it, so it is removed\) out of the Notes section, and removing a field needs --allow-destructive$/);
+ assert.doesNotMatch(one, /repair it in place/);
+ // What it cannot name is counted.
+ assert.match(timelineVerifyProblem(formTabs(hostWith(keeps, web)), isHost, { inspect }), /also holds the field 'new_b' and 1 other control, which a build does not remove, so the build leaves the section as it is; move them out of it, or delete the section/);
+ const unnamed = timelineVerifyProblem(formTabs(hostWith(web, { control: { classId: '{e7a81278-8635-4d9e-8d4d-59480b391c5b}' } })), isHost, { inspect });
+ assert.match(unnamed, /also holds 2 other controls, which a build does not remove, so the build leaves the section as it is; move them out of it/);
+ assert.doesNotMatch(unnamed, /the build first takes/);
+ assert.match(timelineVerifyProblem(formTabs(hostWith(web)), isHost, { inspect: () => undefined }), /also holds 1 other control, which a build does not remove, so the build leaves the section as it is; move it out of it/, 'no verdict is a control that stays');
+});
+
+test('timeline verify: a cell verify cannot predict is neither promised to go nor left to the maker — it says it cannot tell, and what to do if the build leaves it', () => {
+ const field = { control: { fieldName: 'new_x' } };
+ const twice = { name: "the field 'new_x'", unsure: 'it is on the form more than once' };
+ const problem = timelineVerifyProblem(formTabs(hostWith(field)), isHost, { inspect: () => twice });
+ assert.match(problem, /^the deployed form's timeline does not render: .* — run a full build of the spec \(not --changed-only, which skips a spec that has not changed\); the build repairs the timeline in place unless it leaves the field 'new_x' \(it is on the form more than once\) in the Notes section, and verify cannot tell whether it does — a build acts on one cell of such a field, and which one depends on how it arranges the form\. If its report says the timeline was left as it is, move that cell out of the section in the maker and run a full build again$/);
+ // It is not a control that stays (the build may well take it out), and it is not one the build takes out either — and the repair
+ // is not promised: whether it happens is exactly what verify cannot tell.
+ assert.doesNotMatch(problem, /which a build does not remove|so the build leaves the section as it is|the build first takes|to repair it in place/);
+ // A removal it might be says what that needs.
+ assert.match(timelineVerifyProblem(formTabs(hostWith(field)), isHost, { inspect: () => Object.assign({ destructive: true }, twice) }), /run a full build again \(removing a field needs --allow-destructive\)$/);
+ // The same field held twice is named once, and the cells are plural.
+ const two = timelineVerifyProblem(formTabs(hostWith(field, { control: { fieldName: 'new_x' } })), isHost, { inspect: () => twice });
+ assert.match(two, /unless it leaves the field 'new_x' \(it is on the form more than once\) in the Notes section, and verify cannot tell whether it does/);
+ assert.strictEqual(two.split("the field 'new_x'").length - 1, 1, 'named once');
+ assert.match(two, /move those cells out of the section in the maker/);
+ // A cell it cannot name is still said to be one it cannot tell about.
+ assert.match(timelineVerifyProblem(formTabs(hostWith(field)), isHost, { inspect: () => ({ unsure: 'it is a mystery' }) }), /unless it leaves a control \(it is a mystery\) in the Notes section, and verify cannot tell whether it does/);
+ // Different fields are each named, with their own reason — as alternatives: the repair fails if the build leaves either.
+ const verdicts = new Map();
+ const cells = [{ control: { fieldName: 'new_a' } }, { control: { fieldName: 'new_b' } }];
+ verdicts.set(cells[0], { name: "the field 'new_a'", unsure: 'it is on the form more than once' });
+ verdicts.set(cells[1], { name: "the field 'new_b'", unsure: "its anchor 'new_z' is on the form more than once" });
+ assert.match(timelineVerifyProblem(formTabs(hostWith(...cells)), isHost, { inspect: (cell) => verdicts.get(cell) }), /unless it leaves the field 'new_a' \(it is on the form more than once\) or the field 'new_b' \(its anchor 'new_z' is on the form more than once\) in the Notes section, and verify cannot tell whether it does/);
+});
+
+test('timeline verify: a taken id does not hide what verify cannot tell — freeing the id leaves the cell to the build, and the advice says so', () => {
+ const field = { control: { fieldName: 'new_x' } };
+ const twice = { name: "the field 'new_x'", unsure: 'it is on the form more than once' };
+ const taken = (inspect, ...cells) => timelineVerifyProblem(formTabs(hostWith(...(cells.length ? cells : [field])), makerControl('notescontrol')), isHost, { inspect });
+ const problem = taken(() => twice);
+ assert.match(problem, /^the deployed form's timeline does not render: .* — another control on the form already uses the id 'notescontrol', so a build cannot give this timeline that id; remove or rename one of the two in the maker, then run a full build of the spec \(not --changed-only, which skips a spec that has not changed\); verify cannot tell whether the build takes the field 'new_x' \(it is on the form more than once\) out of the Notes section first — a build acts on one cell of such a field, and which one depends on how it arranges the form\. If its report says the timeline was left as it is, move that cell out of the section in the maker and run a full build again$/);
+ assert.doesNotMatch(problem, /repair it in place|which a build does not remove|so the build leaves the section as it is/);
+ // A removal it might be says what that needs.
+ assert.match(taken(() => Object.assign({ destructive: true }, twice)), /run a full build again \(removing a field needs --allow-destructive\)$/);
+ // What a build takes out first is not said while the id is the reason, so what it cannot tell is not something it "also" takes out.
+ const goes = { control: { fieldName: 'new_a' } };
+ const verdicts = new Map([[goes, { name: "the field 'new_a'", goes: 'moved' }], [field, twice]]);
+ const mixed = taken((cell) => verdicts.get(cell), goes, field);
+ assert.match(mixed, /then run a full build of the spec \(not --changed-only, which skips a spec that has not changed\); verify cannot tell whether the build takes the field 'new_x' \(it is on the form more than once\) out of the Notes section first/);
+ assert.doesNotMatch(mixed, /the build first takes|also takes|the field 'new_a'/);
+ // Nothing it cannot tell, nothing more to say: the id is the whole advice.
+ assert.doesNotMatch(taken(() => ({ name: "the field 'new_x'", goes: 'moved' })), /cannot tell/);
+ assert.doesNotMatch(taken(() => ({ name: "the field 'new_x'" })), /cannot tell/);
+});
+
+test('timeline verify: what a build takes out first, what it leaves and what verify cannot tell are each said once, in that order', () => {
+ const leaves = { control: { fieldName: 'new_a' } };
+ const keeps = { control: { fieldName: 'new_b' } };
+ const maybe = { control: { fieldName: 'new_c' } };
+ const verdicts = new Map([
+ [leaves, { name: "the field 'new_a'", goes: 'your layout does not list it, so it is removed', destructive: true }],
+ [keeps, { name: "the field 'new_b'" }],
+ [maybe, { name: "the field 'new_c'", unsure: 'it is on the form more than once' }],
+ ]);
+ const inspect = (cell) => verdicts.get(cell);
+ // Something that certainly stays: the build refuses whatever it does about the rest, and the maker is told to move it.
+ const all = timelineVerifyProblem(formTabs(hostWith(leaves, keeps, maybe)), isHost, { inspect });
+ assert.match(all, / — the Notes section also holds the field 'new_b', which a build does not remove, so the build leaves the section as it is; move it out of it, or delete the section, in the maker, then run a full build of the spec \(not --changed-only, which skips a spec that has not changed\); the build first takes the field 'new_a' \(your layout does not list it, so it is removed\) out of the Notes section, and removing a field needs --allow-destructive; verify cannot tell whether the build also takes the field 'new_c' \(it is on the form more than once\) out of the Notes section first — /);
+ assert.doesNotMatch(all, /the field 'new_c'.*which a build does not remove/, 'what verify cannot tell is not called a control that stays');
+ // With nothing taken out first there is nothing for the build to "also" take.
+ const noneFirst = timelineVerifyProblem(formTabs(hostWith(keeps, maybe)), isHost, { inspect });
+ assert.match(noneFirst, /, then run a full build of the spec \(not --changed-only, which skips a spec that has not changed\); verify cannot tell whether the build takes the field 'new_c' \(it is on the form more than once\) out of the Notes section first — /);
+ assert.doesNotMatch(noneFirst, /also takes|the build first takes/);
+ // Nothing certain in the way: the build is to be run, and what it may leave is said after what it will take.
+ const some = timelineVerifyProblem(formTabs(hostWith(leaves, maybe)), isHost, { inspect });
+ assert.match(some, /— run a full build of the spec \(not --changed-only, which skips a spec that has not changed\); the build first takes the field 'new_a' \(your layout does not list it, so it is removed\) out of the Notes section, and removing a field needs --allow-destructive; the build repairs the timeline in place unless it leaves the field 'new_c' \(it is on the form more than once\) in the Notes section, and verify cannot tell whether it does — /);
+ assert.doesNotMatch(some, /move it out of it, or delete the section|to repair it in place/);
+});
+
+test('timeline verify: the inspector is asked about nothing a form that renders or a host holding only its timeline has, and the id is the reason whatever it says goes', () => {
+ let asked = 0;
+ const inspect = () => { asked += 1; return {}; };
+ assert.strictEqual(timelineVerifyProblem(formTabs(platformHost()), isHost, { inspect }), '');
+ assert.match(timelineVerifyProblem(formTabs(oldHost()), isHost, { inspect }), /to repair it in place$/);
+ assert.strictEqual(asked, 0);
+ const stray = { control: { fieldName: 'new_x' } };
+ const taken = timelineVerifyProblem(formTabs(hostWith(stray), makerControl('notescontrol')), isHost, { inspect: () => ({ name: "the field 'new_x'", goes: 'moved' }) });
+ assert.match(taken, /another control on the form already uses the id 'notescontrol', so a build cannot give this timeline that id; remove or rename one of the two in the maker, then run a full build/);
+ assert.doesNotMatch(taken, /repair it in place|the build first takes/);
+});
+
+// --- verify's model of what a build does with a host's other cells -----------------------------------------------------
+//
+// `notesHostInspector(spec, form, publishedTabs)` answers, for each other cell of the Notes host: what to call it, whether the
+// build takes it out before it judges the section and why, and whether that removes a field. Each case pins one rule;
+// form-timeline-real-bundle.test.js proves the answers agree with what a real build does.
+const ticketSpec = (form) => ({
+ entities: [{ schemaName: 'new_ticket', primaryAttribute: { schemaName: 'new_name' }, columns: [{ schemaName: 'new_code' }, { schemaName: 'new_area' }, { schemaName: 'new_extra' }] }],
+ forms: [Object.assign({ entity: 'new_ticket', name: 'Main', notes: true }, form)],
+});
+// An explicit layout: new_name and new_code in sec_main, new_area in sec_more — and new_extra in neither.
+const explicitForm = (over = {}) => Object.assign({ tabs: [{ name: 'tab_a', sections: [{ name: 'sec_main', fields: ['new_name', 'new_code'] }, { name: 'sec_more', fields: ['new_area'] }] }] }, over);
+const fieldCell = (fieldName) => ({ control: { fieldName } });
+const fieldSection = (name, ...fields) => ({ name, rows: fields.map((f) => ({ cells: [fieldCell(f)] })) });
+// What the inspector says about `cell` once the form is published as `sections` (the Notes host among them).
+const inspected = (form, sections, cell) => {
+ const spec = ticketSpec(form);
+ return notesHostInspector(spec, spec.forms[0], formTabs(...sections))(cell);
+};
+const WEB_RESOURCE = '{9fdf5f91-88b1-47f4-ad53-c11efbb3e0d8}';
+const QUICK_VIEW = '{5C5600E0-1D6E-4205-A272-BE80DA87FD42}';
+const SUBGRID = '{E7A81278-8635-4D9E-8D4D-59480B391C5B}';
+
+test('notes host inspector: a field an explicit layout declares in another section is moved there — an auto layout moves nothing', () => {
+ const stray = fieldCell('new_area'); // sec_more's field, sitting in the Notes host
+ const sections = [fieldSection('sec_main', 'new_name', 'new_code'), hostWith(stray)];
+ assert.deepStrictEqual(inspected(explicitForm(), sections, stray), { name: "the field 'new_area'", goes: "your layout places it in section 'sec_more', so it is moved there" });
+ assert.deepStrictEqual(inspected({}, sections, stray), { name: "the field 'new_area'" }, 'an auto layout declares no section for a field');
+});
+
+test('notes host inspector: a field the layout does not list is removed — unless prune is off, the layout is auto, or it is the primary field', () => {
+ const stray = fieldCell('new_extra');
+ const sections = [fieldSection('sec_main', 'new_name', 'new_code'), fieldSection('sec_more', 'new_area'), hostWith(stray)];
+ assert.deepStrictEqual(inspected(explicitForm(), sections, stray), { name: "the field 'new_extra'", goes: 'your layout does not list it, so it is removed', destructive: true });
+ assert.deepStrictEqual(inspected(explicitForm({ prune: false }), sections, stray), { name: "the field 'new_extra'" });
+ assert.deepStrictEqual(inspected({}, sections, stray), { name: "the field 'new_extra'" });
+ // The primary field is never pruned: the build keeps it wherever it is, even when the layout does not list it.
+ const primary = fieldCell('new_name');
+ const withoutPrimary = explicitForm({ tabs: [{ name: 'tab_a', sections: [{ name: 'sec_main', fields: ['new_code'] }] }] });
+ assert.deepStrictEqual(inspected(withoutPrimary, [fieldSection('sec_main', 'new_code'), hostWith(primary)], primary), { name: "the field 'new_name'" });
+ // A published form may spell a logical name in any case; the build and the prune compare them lower-cased.
+ const shouting = fieldCell('NEW_EXTRA');
+ assert.deepStrictEqual(inspected(explicitForm(), [fieldSection('sec_main', 'new_name'), hostWith(shouting)], shouting), { name: "the field 'new_extra'", goes: 'your layout does not list it, so it is removed', destructive: true });
+});
+
+test('notes host inspector: a field a fieldOptions anchor places beside its anchor is moved there — on any layout, and whatever prune says', () => {
+ const stray = fieldCell('new_extra');
+ const sections = [fieldSection('sec_main', 'new_name', 'new_code'), fieldSection('sec_more', 'new_area'), hostWith(stray)];
+ const anchored = (over) => ({ fieldOptions: { new_extra: { after: 'new_area' } }, ...over });
+ const placed = { name: "the field 'new_extra'", goes: "fieldOptions places it after 'new_area', so it is moved there" };
+ assert.deepStrictEqual(inspected(explicitForm(anchored({ prune: false })), sections, stray), placed);
+ assert.deepStrictEqual(inspected(anchored(), sections, stray), placed, 'an auto layout too');
+ // Anchored AND pruned: the build moves it and then removes it, and the removal is what the maker is told.
+ const both = inspected(explicitForm(anchored()), sections, stray);
+ assert.strictEqual(both.destructive, true);
+ assert.match(both.goes, /does not list it, so it is removed/);
+});
+
+test('notes host inspector: an anchor the build cannot place a field beside leaves the field where it is', () => {
+ const stray = fieldCell('new_extra');
+ const kept = { name: "the field 'new_extra'" };
+ const placed = (anchor) => ({ name: "the field 'new_extra'", goes: `fieldOptions places it after '${anchor}', so it is moved there` });
+ const form = (anchor, over = {}) => explicitForm({ prune: false, fieldOptions: { new_extra: { after: anchor } }, ...over });
+ // An anchor that is not on the form, and that the layout does not place: nothing to place the field beside.
+ assert.deepStrictEqual(inspected(form('new_unlisted'), [fieldSection('sec_main', 'new_name', 'new_code'), hostWith(stray)], stray), kept);
+ // An anchor in a section the build owns — the Notes host itself, or a sub-grid's — where no field is ever placed.
+ const other = fieldCell('new_other');
+ assert.deepStrictEqual(inspected(form('new_other'), [fieldSection('sec_main', 'new_name'), hostWith(stray, other)], stray), kept, 'the anchor is in the Notes host too');
+ const gridHolding = (field) => ({ name: 'section_grid_new_child', rows: [{ cells: [{ control: { classId: SUBGRID } }] }, { cells: [fieldCell(field)] }] });
+ assert.deepStrictEqual(inspected(form('new_other'), [fieldSection('sec_main', 'new_name'), gridHolding('new_other'), hostWith(stray)], stray), kept, 'the anchor is in a sub-grid\u2019s section');
+ // …unless the layout declares the anchor in a section of its own: the build moves it there before it positions anything.
+ assert.deepStrictEqual(inspected(form('new_code'), [fieldSection('sec_main', 'new_name'), gridHolding('new_code'), hostWith(stray)], stray), placed('new_code'));
+ // An anchor the form does not have yet, but the layout places: the build adds it before it positions anything.
+ assert.deepStrictEqual(inspected(form('new_code'), [fieldSection('sec_main', 'new_name'), hostWith(stray)], stray), placed('new_code'));
+ assert.deepStrictEqual(inspected({ fieldOptions: { new_extra: { after: 'new_code' } } }, [fieldSection('section_general', 'new_name'), hostWith(stray)], stray), placed('new_code'), 'an auto layout places the table\u2019s columns');
+ assert.deepStrictEqual(inspected({ fieldOptions: { new_extra: { after: 'new_unlisted' } } }, [fieldSection('section_general', 'new_name'), hostWith(stray)], stray), kept, 'but not a column it does not have');
+ // An anchor in the host that the layout declares elsewhere is moved out first, and the field follows it.
+ const moved = fieldCell('new_other');
+ const layout = form('new_other', { tabs: [{ name: 'tab_a', sections: [{ name: 'sec_main', fields: ['new_name', 'new_code'] }, { name: 'sec_more', fields: ['new_area', 'new_other'] }] }] });
+ assert.deepStrictEqual(inspected(layout, [fieldSection('sec_main', 'new_name', 'new_code'), hostWith(stray, moved)], stray), placed('new_other'));
+ assert.deepStrictEqual(inspected(layout, [fieldSection('sec_main', 'new_name', 'new_code'), hostWith(stray, moved)], moved), { name: "the field 'new_other'", goes: "your layout places it in section 'sec_more', so it is moved there" });
+});
+
+test('notes host inspector: a field anchored to an anchor that is itself moved out of the host follows it — the build places anchored fields in dependency order', () => {
+ const other = fieldCell('new_other');
+ const extra = fieldCell('new_extra');
+ const sections = [fieldSection('section_general', 'new_name', 'new_code', 'new_area'), hostWith(other, extra)];
+ const after = (anchor) => ({ goes: `fieldOptions places it after '${anchor}', so it is moved there` });
+ // new_other goes after new_area first (new_area is not anchored itself), and new_extra after new_other once it is there.
+ const chain = { new_other: { after: 'new_area' }, new_extra: { after: 'new_other' } };
+ assert.deepStrictEqual(inspected({ fieldOptions: chain }, sections, other), { name: "the field 'new_other'", ...after('new_area') });
+ assert.deepStrictEqual(inspected({ fieldOptions: chain }, sections, extra), { name: "the field 'new_extra'", ...after('new_other') });
+ // The order the spec lists them in decides nothing: the build sorts them by what they depend on.
+ const reversed = { new_extra: { after: 'new_other' }, new_other: { after: 'new_area' } };
+ assert.deepStrictEqual(inspected({ fieldOptions: reversed }, sections, extra), { name: "the field 'new_extra'", ...after('new_other') });
+ // On an explicit layout with prune off, where the layout names neither field.
+ assert.deepStrictEqual(inspected(explicitForm({ prune: false, fieldOptions: chain }), [fieldSection('sec_more', 'new_area'), hostWith(other, extra)], extra), { name: "the field 'new_extra'", ...after('new_other') });
+ // A longer chain: every link in the host is followed out.
+ const third = fieldCell('new_third');
+ const long = { new_third: { after: 'new_extra' }, new_extra: { after: 'new_other' }, new_other: { after: 'new_area' } };
+ assert.deepStrictEqual(inspected({ fieldOptions: long }, [fieldSection('section_general', 'new_name', 'new_area'), hostWith(other, extra, third)], third), { name: "the field 'new_third'", ...after('new_extra') });
+ // A chain that never leaves the host moves nothing: the head has no anchor of its own, or its anchor is not on the form.
+ const stuck = { new_extra: { after: 'new_other' } };
+ assert.deepStrictEqual(inspected({ fieldOptions: stuck }, sections, extra), { name: "the field 'new_extra'" });
+ const lost = { new_extra: { after: 'new_other' }, new_other: { after: 'new_unlisted' } };
+ assert.deepStrictEqual(inspected({ fieldOptions: lost }, sections, extra), { name: "the field 'new_extra'" });
+ // A cycle is never placed (the build refuses it), and the walk ends rather than going round for ever.
+ const cycle = { new_extra: { after: 'new_other' }, new_other: { after: 'new_extra' } };
+ assert.deepStrictEqual(inspected({ fieldOptions: cycle }, sections, extra), { name: "the field 'new_extra'" });
+ assert.deepStrictEqual(inspected({ fieldOptions: cycle }, sections, other), { name: "the field 'new_other'" });
+});
+
+test('notes host inspector: one inspector answers for every cell of a chain of three anchors — what it works out for one cell does not use up what the next needs', () => {
+ // `--verify` asks the SAME inspector about each cell of the host in turn, and the walks overlap: the one for the head of the chain
+ // passes through the links the later questions start from, so a walk must not leave anything behind for the next.
+ const [other, extra, third] = ['new_other', 'new_extra', 'new_third'].map(fieldCell);
+ const long = { new_third: { after: 'new_extra' }, new_extra: { after: 'new_other' }, new_other: { after: 'new_area' } };
+ const spec = ticketSpec({ fieldOptions: long });
+ const inspect = notesHostInspector(spec, spec.forms[0], formTabs(fieldSection('section_general', 'new_name', 'new_area'), hostWith(other, extra, third)));
+ const after = (anchor) => ({ goes: `fieldOptions places it after '${anchor}', so it is moved there` });
+ const expected = new Map([
+ [other, { name: "the field 'new_other'", ...after('new_area') }],
+ [extra, { name: "the field 'new_extra'", ...after('new_other') }],
+ [third, { name: "the field 'new_third'", ...after('new_extra') }],
+ ]);
+ // The head of the chain first, then the rest, and again the other way round.
+ for (const cell of [third, extra, other, other, extra, third]) assert.deepStrictEqual(inspect(cell), expected.get(cell));
+});
+
+test('notes host inspector: a field the form has more than once is not predicted when a pass would act on it — which cell a build acts on is not the published order', () => {
+ // A build acts on ONE cell of a field per pass, the first it finds once it has reordered the sections — so with a cell in
+ // sec_main and one in the Notes host, whether the host's goes depends on an order that is not the published one.
+ const inHost = fieldCell('new_code');
+ const unsure = { name: "the field 'new_code'", unsure: 'it is on the form more than once' };
+ assert.deepStrictEqual(inspected(explicitForm(), [fieldSection('sec_main', 'new_name', 'new_code'), hostWith(inHost)], inHost), unsure);
+ assert.deepStrictEqual(inspected(explicitForm(), [hostWith(inHost), fieldSection('sec_main', 'new_name', 'new_code')], inHost), unsure, 'in either published order');
+ // Whatever the pass is: a removal (and it says so, since that takes --allow-destructive), an anchor — on an auto layout too.
+ const extra = fieldCell('new_extra');
+ const withExtra = [fieldSection('sec_main', 'new_name', 'new_code', 'new_extra'), fieldSection('sec_more', 'new_area'), hostWith(extra)];
+ assert.deepStrictEqual(inspected(explicitForm(), withExtra, extra), { name: "the field 'new_extra'", unsure: 'it is on the form more than once', destructive: true });
+ const anchored = { fieldOptions: { new_extra: { after: 'new_area' } } };
+ assert.deepStrictEqual(inspected(explicitForm({ prune: false, ...anchored }), withExtra, extra), { name: "the field 'new_extra'", unsure: 'it is on the form more than once' });
+ assert.deepStrictEqual(inspected(anchored, withExtra, extra), { name: "the field 'new_extra'", unsure: 'it is on the form more than once' });
+ // A field no pass touches stays whichever of its cells is acted on, so that is still said plainly — the host's cell is named
+ // as the second cell of a field the host holds twice, and never as a field that both goes and stays.
+ const inHostTwice = [fieldCell('new_extra'), fieldCell('new_extra'), fieldCell('new_extra')];
+ const twice = [fieldSection('sec_main', 'new_name', 'new_code', 'new_extra'), hostWith(...inHostTwice)];
+ const names = inHostTwice.map((cell) => inspected(explicitForm({ prune: false }), twice, cell).name);
+ assert.deepStrictEqual(names, ["the field 'new_extra'", "a second cell of the field 'new_extra'", "another cell of the field 'new_extra'"]);
+ assert.deepStrictEqual(inspected({}, twice, inHostTwice[1]), { name: "a second cell of the field 'new_extra'" }, 'an auto layout touches nothing either');
+ // …while a field the layout does place, held twice by the host, is said once and not named as both leaving and staying.
+ const placed = [fieldCell('new_code'), fieldCell('new_code')];
+ const heldTwice = [fieldSection('sec_main', 'new_name'), hostWith(...placed)];
+ for (const cell of placed) assert.deepStrictEqual(inspected(explicitForm(), heldTwice, cell), unsure);
+});
+
+test('notes host inspector: an anchor the form has more than once is only relied on where every cell of it is in a section the build does not own', () => {
+ const stray = fieldCell('new_extra');
+ const anchoredAfter = (anchor, over = {}) => explicitForm({ prune: false, fieldOptions: { new_extra: { after: anchor } }, ...over });
+ const placed = { name: "the field 'new_extra'", goes: "fieldOptions places it after 'new_code', so it is moved there" };
+ // Two cells, both in ordinary sections: whichever the build finds first, the field is placed beside it.
+ assert.deepStrictEqual(inspected(anchoredAfter('new_code'), [fieldSection('sec_main', 'new_name', 'new_code'), fieldSection('sec_more', 'new_code'), hostWith(stray)], stray), placed);
+ // One of them in the Notes host: which one the build finds first is not the published order.
+ const unsure = { name: "the field 'new_extra'", unsure: "its anchor 'new_code' is on the form more than once" };
+ assert.deepStrictEqual(inspected(anchoredAfter('new_code'), [fieldSection('sec_main', 'new_name', 'new_code'), hostWith(stray, fieldCell('new_code'))], stray), unsure);
+ assert.deepStrictEqual(inspected(anchoredAfter('new_code'), [hostWith(stray, fieldCell('new_code')), fieldSection('sec_main', 'new_name', 'new_code')], stray), unsure, 'in either published order');
+ // A single cell of the anchor in the host is another matter: the build knows which it is, and takes it out first (as above).
+ assert.deepStrictEqual(inspected(anchoredAfter('new_code'), [fieldSection('sec_main', 'new_name'), hostWith(stray, fieldCell('new_code'))], stray), placed, 'the layout declares new_code in sec_main');
+ // A field whose anchor has ONE cell but is itself anchored to a field the form has twice is not predicted either — and the reason
+ // names the field the form has twice, never an anchor that has one cell.
+ const other = fieldCell('new_other');
+ const third = fieldCell('new_third');
+ const twice = [fieldSection('section_general', 'new_name', 'new_code'), hostWith(third, stray, other, fieldCell('new_code'))];
+ const links = (anchors) => ({ fieldOptions: anchors });
+ const two = links({ new_other: { after: 'new_code' }, new_extra: { after: 'new_other' } });
+ assert.deepStrictEqual(inspected(two, twice, other), { name: "the field 'new_other'", unsure: "its anchor 'new_code' is on the form more than once" });
+ assert.deepStrictEqual(inspected(two, twice, stray), { name: "the field 'new_extra'", unsure: "its anchor 'new_other' follows 'new_code', which is on the form more than once" });
+ // However many links lie between the field and the one the form has twice, each is traced.
+ const three = links({ new_other: { after: 'new_code' }, new_extra: { after: 'new_other' }, new_third: { after: 'new_extra' } });
+ assert.deepStrictEqual(inspected(three, twice, third), { name: "the field 'new_third'", unsure: "its anchor 'new_extra' follows 'new_other', which follows 'new_code', which is on the form more than once" });
+ // When it is the middle link that the form has twice, that link IS the anchor, and is said to be on the form more than once.
+ const middle = [fieldSection('section_general', 'new_name', 'new_other'), hostWith(stray, fieldCell('new_other'))];
+ assert.deepStrictEqual(inspected(two, middle, stray), { name: "the field 'new_extra'", unsure: "its anchor 'new_other' is on the form more than once" });
+});
+
+test('notes host inspector: a control that is not a bound field is never taken out — a quick view carries a field name and is still not one', () => {
+ const web = { control: { classId: WEB_RESOURCE } };
+ const quickView = { control: { fieldName: 'new_extra', classId: QUICK_VIEW } }; // binds a lookup's name, not that field
+ const grid = { control: { classId: SUBGRID } };
+ const spacer = {};
+ const sections = [fieldSection('sec_main', 'new_name', 'new_code'), hostWith(web, quickView, grid, spacer)];
+ for (const cell of [web, quickView, grid, spacer, undefined]) assert.deepStrictEqual(inspected(explicitForm(), sections, cell), {});
+});
+
+test('notes host inspector: a quick view is not a cell of the lookup it names — it does not make the host\u2019s own cell of that field a second one', () => {
+ // The layout declares the lookup in sec_more; sec_main holds a quick view that names it; the host holds the field itself.
+ const layout = explicitForm({ tabs: [{ name: 'tab_a', sections: [{ name: 'sec_main', fields: ['new_name'] }, { name: 'sec_more', fields: ['new_parentid'] }] }] });
+ const field = fieldCell('new_parentid');
+ const quickView = { control: { fieldName: 'new_parentid', classId: QUICK_VIEW } };
+ const sections = [{ name: 'sec_main', rows: [{ cells: [fieldCell('new_name')] }, { cells: [quickView] }] }, hostWith(field)];
+ assert.deepStrictEqual(inspected(layout, sections, field), { name: "the field 'new_parentid'", goes: "your layout places it in section 'sec_more', so it is moved there" });
+ // …and the same as an anchor: a quick view in an ordinary section is not where the build finds the anchor.
+ const anchored = explicitForm({ prune: false, fieldOptions: { new_extra: { after: 'new_parentid' } } });
+ const stray = fieldCell('new_extra');
+ assert.deepStrictEqual(inspected(anchored, [{ name: 'sec_main', rows: [{ cells: [quickView] }] }, hostWith(stray)], stray), { name: "the field 'new_extra'" });
+});
+
+test('notes host inspector: a layout the compiler cannot read predicts nothing, so every cell is in the way, as for a form nothing is known about', () => {
+ const stray = fieldCell('new_extra');
+ const broken = explicitForm({ tabs: [{ name: 'tab_a', sections: [{ name: 'sec_main', fields: 'new_name' }] }] }); // `fields` is not a list
+ const spec = ticketSpec(broken);
+ const tabs = formTabs(hostWith(stray));
+ const inspect = notesHostInspector(spec, spec.forms[0], tabs);
+ assert.strictEqual(inspect, undefined);
+ assert.match(timelineVerifyProblem(tabs, isHost, { inspect }), /the Notes section also holds other controls, so a build leaves it as it is; move them out of it/);
+});
diff --git a/plugins/model-apps/scripts/tests/genpage-cli.test.js b/plugins/model-apps/scripts/tests/genpage-cli.test.js
index 39a81fade..a09a2c22c 100644
--- a/plugins/model-apps/scripts/tests/genpage-cli.test.js
+++ b/plugins/model-apps/scripts/tests/genpage-cli.test.js
@@ -133,12 +133,21 @@ async function withPathFirst(dir, fn, { only = false } = {}) {
// real one is, and an executable script elsewhere. By default it writes a multibyte character in two
// pieces 200 ms apart, then its argv, then an error, and exits 3. With `--big` it writes 1.5 MiB.
// With `--late` it starts a process that shares its stdout and writes 300 ms after the fake exits.
+// With FAKE_PAC_HANG set to a file name it prints the start of a listing, records its own pid there and then runs for 30 s (a pac
+// that never finishes its answer).
const BIG_OUTPUT_BYTES = 1536 * 1024;
function makeFakePac() {
const dir = scratch('genpage-cli-fakepac-');
const script = path.join(dir, 'fake-pac.js');
fs.writeFileSync(script, [
- `if (process.argv.includes('--big')) process.stdout.write('x'.repeat(${BIG_OUTPUT_BYTES}));`,
+ 'if (process.env.FAKE_PAC_HANG) {',
+ // Half a listing first — what a pac that is ended while it is still answering has already printed — and the pid only once
+ // that has been written, so a test that sees the pid knows the partial output is on its way to the runner.
+ " process.stdout.write('Found 2 generated page(s):\\n6e0c28a2-cdbf-41ec-9186-d10fd5de6e35 Ove', () => {",
+ " require('fs').writeFileSync(process.env.FAKE_PAC_HANG, String(process.pid));",
+ ' });',
+ ' setTimeout(() => {}, 30000);',
+ `} else if (process.argv.includes('--big')) process.stdout.write('x'.repeat(${BIG_OUTPUT_BYTES}));`,
"else if (process.argv.includes('--late')) {",
" require('child_process').spawn(process.execPath, ['-e', \"setTimeout(() => process.stdout.write('late'), 300)\"],",
" { stdio: ['ignore', 'inherit', 'inherit'], detached: true, windowsHide: true }).unref();",
@@ -221,6 +230,227 @@ test('runPac resolves with a non-zero status and the launch error when pac canno
assert.match(r.stderr, /ENOENT/, `the failure must say why; got ${JSON.stringify(r)}`);
});
+// A caller that stops needing pac's answer — a verify pass that failed — must be able to END it. pac has no timeout of its
+// own, and on Windows it is usually a batch shim: Node's own kill of the cmd.exe it started leaves pac itself running.
+// The fake records its pid and then hangs, so these tests see whether the process that matters is gone.
+const processAlive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
+async function waitUntil(condition, ms = 5000) {
+ for (const end = Date.now() + ms; Date.now() < end;) {
+ if (await condition()) return true;
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ return false;
+}
+const withHangingPac = async (fn) => {
+ const pidFile = path.join(scratch('genpage-cli-pid-'), 'pac.pid');
+ process.env.FAKE_PAC_HANG = pidFile;
+ try {
+ return await withPathFirst(makeFakePac(), () => fn(pidFile));
+ } finally {
+ delete process.env.FAKE_PAC_HANG;
+ }
+};
+const readPid = (pidFile) => Number(fs.readFileSync(pidFile, 'utf8'));
+const endsWithin = (promise, ms) => Promise.race([promise, new Promise((resolve) => setTimeout(() => resolve('still running'), ms))]);
+
+test('runPac ends pac, and everything it started, when its signal aborts — the answer is a failed, output-free result marked ended', async () => {
+ await withHangingPac(async (pidFile) => {
+ const controller = new AbortController();
+ const run = runPac(['model', 'genpage', 'list'], { signal: controller.signal });
+ assert.ok(await waitUntil(() => fs.existsSync(pidFile) && fs.readFileSync(pidFile, 'utf8')), 'pac started');
+ const pid = readPid(pidFile);
+ assert.ok(processAlive(pid));
+ // The half of a listing that pac printed before it hung has reached the runner by now; an ended run hands back none of it.
+ await new Promise((resolve) => setTimeout(resolve, 150));
+ controller.abort();
+ const r = await endsWithin(run, 5000);
+ assert.notStrictEqual(r, 'still running', 'the run answers at once once it is ended');
+ assert.notStrictEqual(r.status, 0);
+ assert.strictEqual(r.ended, true);
+ assert.strictEqual(r.stdout, '', 'a half-read listing is never handed back, where a caller could parse it');
+ assert.match(r.stderr, /pac was ended/);
+ assert.ok(await waitUntil(() => !processAlive(pid)), 'pac itself is gone — not only the shell that started it');
+ });
+});
+
+test('runPac with a signal that has already aborted starts no pac at all', async () => {
+ await withHangingPac(async (pidFile) => {
+ const controller = new AbortController();
+ controller.abort();
+ const r = await runPac(['model', 'genpage', 'list'], { signal: controller.signal });
+ assert.strictEqual(r.ended, true);
+ assert.notStrictEqual(r.status, 0);
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ assert.ok(!fs.existsSync(pidFile), 'pac was never started');
+ });
+});
+
+test('a pac run nobody aborts is not marked ended, and a signal that never fires changes nothing', async () => {
+ const controller = new AbortController();
+ const r = await withPathFirst(makeFakePac(), () => runPac(['model', 'genpage', 'list', '--big'], { signal: controller.signal }));
+ assert.strictEqual(r.status, 0, r.stderr);
+ assert.strictEqual(r.ended, undefined);
+ assert.strictEqual(r.stdout.length, BIG_OUTPUT_BYTES);
+});
+
+test('the client\'s abort() ends the pac runs it has in flight and a listing that was ended is not retried — and the client is usable afterwards', async () => {
+ const sleeps = [];
+ const cli = realMakeGenpageCli('https://contoso.crm.dynamics.com', { attempts: 3, sleep: async (ms) => { sleeps.push(ms); } });
+ await withHangingPac(async (pidFile) => {
+ const listing = cli.enumerateEnv();
+ assert.ok(await waitUntil(() => fs.existsSync(pidFile) && fs.readFileSync(pidFile, 'utf8')), 'pac started');
+ const pid = readPid(pidFile);
+ cli.abort();
+ const r = await endsWithin(listing, 5000);
+ assert.notStrictEqual(r, 'still running');
+ assert.strictEqual(r.ok, false);
+ assert.match(r.error, /was ended/);
+ assert.deepStrictEqual(sleeps, [], 'no retry: the attempt that was ended is not followed by the pause and the new attempt a flake would get');
+ assert.ok(await waitUntil(() => !processAlive(pid)), 'pac is gone');
+ });
+ // Runs started after an abort are not affected.
+ const after = await withPathFirst(makeFakePac(), () => cli.enumerateEnv());
+ assert.strictEqual(after.ok, false);
+ assert.doesNotMatch(String(after.error), /was ended/, 'it failed for the reason the fake pac fails (exit 3), not because the client was ended');
+ assert.strictEqual(sleeps.length, 2, 'an ordinary failure is retried as before');
+});
+
+// A call that failed once pauses before it asks again, and an abort() that lands in that pause finds nothing in flight to end — so
+// the attempt after the pause used to start a pac run that nothing would ever end (pac has no timeout of its own). A call that
+// began before the abort starts nothing more, whichever call it is; a call that begins afterwards is an ordinary one.
+const flakyRun = (runs) => async (args) => { runs.push(args); return { status: 1, stdout: '', stderr: 'Error: flaky' }; };
+
+test('abort() during the pause between two attempts of a listing stops the call: no further pac run is started — and the client is usable afterwards', async () => {
+ const listings = [
+ ['the env-wide listing', (cli) => cli.enumerateEnv(), /^pac genpage list \(env-wide\) was ended/],
+ ['an app\'s listing', (cli) => cli.enumeratePages('app-1'), /^pac genpage list was ended/],
+ ];
+ for (const [what, call, wanted] of listings) {
+ const runs = [];
+ const pauses = [];
+ let abortInPause = true;
+ let cli;
+ cli = realMakeGenpageCli('https://contoso.crm.dynamics.com', { attempts: 3, run: flakyRun(runs), sleep: async (ms) => { pauses.push(ms); if (abortInPause) cli.abort(); } });
+ const answer = await call(cli);
+ assert.strictEqual(runs.length, 1, `${what}: the attempt after the pause was never started`);
+ assert.strictEqual(answer.ok, false, what);
+ assert.match(answer.error, wanted, what);
+ assert.deepStrictEqual(pauses, [500], `${what}: and the call does not pause again for an attempt it will not make`);
+ // A call that begins after the abort is an ordinary one, retried like any other.
+ abortInPause = false;
+ runs.length = 0;
+ const later = await call(cli);
+ assert.strictEqual(runs.length, 3, `${what}: a later call makes all its attempts`);
+ assert.doesNotMatch(String(later.error), /was ended/, what);
+ }
+});
+
+test('abort() during the pause between two attempts of an upload stops it as well: a create never starts — and an update that failed has no pause to stop, since it is never sent again', async () => {
+ const runs = [];
+ const pauses = [];
+ let cli;
+ cli = realMakeGenpageCli('https://contoso.crm.dynamics.com', { attempts: 3, run: flakyRun(runs), sleep: async (ms) => { pauses.push(ms); cli.abort(); } });
+ await assert.rejects(
+ cli.upload({ appId: 'app-1', pageId: GUID, codeFile: 'page.tsx', name: 'Overview' }),
+ /pac genpage upload for 'Overview' failed \(Error: flaky\) — the UPDATE of page [^ ]+ MAY HAVE LANDED/,
+ );
+ assert.strictEqual(runs.length, 1, 'the update is sent once');
+ assert.deepStrictEqual(pauses, [], 'and nothing waits for an attempt that will not be made');
+ // A create takes its snapshot of the environment first: that listing is the call that is paused, and the create is never started.
+ runs.length = 0;
+ await assert.rejects(
+ cli.upload({ appId: 'app-1', codeFile: 'page.tsx', name: 'Overview' }),
+ /cannot snapshot the environment before create.*was ended/,
+ );
+ assert.strictEqual(runs.length, 1, 'only the listing attempt ran; no `upload` command was ever sent');
+ assert.ok(!runs.some((args) => args.includes('upload')));
+});
+
+// The reconciliation of an uncertain create lists the environment again, and that listing must start nothing either once an abort has come.
+test('abort() during the pause between two attempts of a create makes the reconciliation listing that follows an ended one, not a new pac run', async () => {
+ const runs = [];
+ let cli;
+ const run = async (args) => {
+ runs.push(args.includes('list') ? 'list' : 'upload');
+ return args.includes('list') ? { status: 0, stdout: LIST_EMPTY, stderr: '' } : { status: 1, stdout: '', stderr: 'Error: flaky' };
+ };
+ cli = realMakeGenpageCli('https://contoso.crm.dynamics.com', { attempts: 3, run, sleep: async () => { cli.abort(); } });
+ await assert.rejects(
+ cli.upload({ appId: 'app-1', codeFile: 'page.tsx', name: 'Overview' }),
+ /had an uncertain result and env enumeration failed.*was ended/,
+ );
+ assert.deepStrictEqual(runs, ['list', 'upload', 'list'], 'the snapshot, the create, its first reconciliation — and nothing after the abort');
+});
+
+test('abort() during the pause between two attempts of a listing, with a real pac, starts no second pac — the one an abort could not have ended', async () => {
+ const pidFile = path.join(scratch('genpage-cli-pid-'), 'pac.pid');
+ let cli;
+ cli = realMakeGenpageCli('https://contoso.crm.dynamics.com', {
+ attempts: 3,
+ sleep: async () => {
+ // From here on a pac that is started would hang, so one started after the abort is one nobody ends.
+ process.env.FAKE_PAC_HANG = pidFile;
+ cli.abort();
+ },
+ });
+ try {
+ await withPathFirst(makeFakePac(), async () => {
+ const answer = await endsWithin(cli.enumerateEnv(), 8000);
+ assert.notStrictEqual(answer, 'still running', 'the call answers: it did not wait for a second pac');
+ assert.strictEqual(answer.ok, false);
+ assert.match(answer.error, /was ended/);
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ assert.ok(!fs.existsSync(pidFile), 'no pac was started after the abort');
+ });
+ } finally {
+ delete process.env.FAKE_PAC_HANG;
+ cli.abort(); // ends the pac a client that starts one after an abort would have left behind
+ }
+});
+
+test('abort() ends a download that is running: it fails at once with the reason, and its whole process tree is gone', async () => {
+ const cli = realMakeGenpageCli('https://contoso.crm.dynamics.com');
+ await withHangingPac(async (pidFile) => {
+ const download = cli.download({ appId: 'app-1', outputDir: scratch('genpage-cli-out-'), pageIds: [GP_A] }).then(() => 'resolved', (error) => error);
+ assert.ok(await waitUntil(() => fs.existsSync(pidFile) && fs.readFileSync(pidFile, 'utf8')), 'pac started');
+ const pid = readPid(pidFile);
+ cli.abort();
+ const failure = await endsWithin(download, 5000);
+ assert.notStrictEqual(failure, 'still running');
+ assert.match(failure.message, /^pac genpage download failed: .*was ended/);
+ assert.ok(await waitUntil(() => !processAlive(pid)), 'pac is gone');
+ });
+});
+
+test('a verify pass that fails while pac is still listing pages ends that pac — the whole process tree — before it throws', async () => {
+ const { verifySpec } = require('../lib/verify-spec.js');
+ const { readerFor } = require('../verify-model-app.js');
+ await withHangingPac(async (pidFile) => {
+ const pacStarted = () => fs.existsSync(pidFile) && fs.readFileSync(pidFile, 'utf8');
+ const sdk = {
+ queryRecords: async () => [],
+ // The first check fails once pac is running, so the page check's listing is what the pass gives up on.
+ findTables: async () => { await waitUntil(pacStarted); throw new Error('the environment could not be read'); },
+ };
+ const spec = {
+ schemaVersion: 2,
+ solution: { uniqueName: 'verify_pac', publisherPrefix: 'new' },
+ app: { name: 'Verify Pac', uniqueName: 'new_verifypac' },
+ entities: [{ schemaName: 'new_t0', columns: [] }],
+ pages: [{ key: 'overview', name: 'Overview', source: { kind: 'tsx', codeFile: 'overview.tsx' } }],
+ appShell: { areas: [] },
+ };
+ const cli = realMakeGenpageCli('https://contoso.crm.dynamics.com');
+ const reader = readerFor(sdk, 'new_verifypac', { genpageCli: cli });
+ // The membership read is the first of the page reads; the existence listing — the pac run — comes next.
+ reader.sitemapPageIds = async () => [GP_A];
+ const outcome = await endsWithin(verifySpec(spec, reader, { concurrency: 4 }).then(() => ({}), (error) => ({ error })), 15000);
+ assert.notStrictEqual(outcome, 'still running', 'the pass does not wait for the pac listing');
+ assert.match(outcome.error.message, /the environment could not be read/);
+ assert.ok(await waitUntil(() => !processAlive(readPid(pidFile)), 2000), 'pac, and not only the shell that started it, is gone by the time the pass is over');
+ });
+});
+
test('parsePageId extracts the guid from upload output', () => {
assert.strictEqual(parsePageId(`Successfully pushed page. Page ID: ${GUID}\n`), GUID);
assert.strictEqual(parsePageId('no id here'), null);
@@ -323,19 +553,23 @@ test('upload cleans up its temp files even when it throws after exhausting retri
const fs = require('node:fs');
let promptPath = null;
let agentPath = null;
+ let creates = 0;
const run = async (args) => {
+ // A CREATE whose every attempt fails outright and leaves nothing in the listing — the one kind of upload that is retried — so the wrapper throws after
+ // `attempts`. (An UPDATE that fails is not retried at all: it may have landed.) The finally must still remove the temp dir.
+ if (args.includes('list')) return { status: 0, stdout: LIST_EMPTY, stderr: '' };
+ creates += 1;
const pi = args.indexOf('--prompt-file');
const ai = args.indexOf('--agent-message-file');
if (pi >= 0) promptPath = args[pi + 1];
if (ai >= 0) agentPath = args[ai + 1];
- // UPDATE path (caller pageId) so there is no CREATE reconcile — every attempt just fails and the
- // wrapper throws after `attempts`. The finally must still remove the temp dir.
return { status: 1, stdout: '', stderr: 'boom' };
};
await assert.rejects(
- makeGenpageCli('https://x', { run, sleep: async () => {} }).upload({ appId: 'a', pageId: GUID, codeFile: 'o.tsx', name: 'Overview' }),
- /pac genpage upload failed/i
+ makeGenpageCli('https://x', { run, sleep: async () => {} }).upload({ appId: 'a', codeFile: 'o.tsx', name: 'Overview' }),
+ /pac genpage upload failed for 'Overview': boom/
);
+ assert.strictEqual(creates, 3, 'every attempt was spent');
assert.ok(promptPath && !fs.existsSync(promptPath), 'prompt temp file removed on the retry-exhaustion throw');
assert.ok(agentPath && !fs.existsSync(agentPath), 'agent-message temp file removed on the retry-exhaustion throw');
});
@@ -364,13 +598,16 @@ test('upload with a pageId updates in place (adds --page-id)', async () => {
assert.ok(calls[0].includes('--page-id') && calls[0].includes(GUID));
});
-test('upload retries a transient pac failure then succeeds', async () => {
+// A failed UPDATE is no proof that nothing landed: pac writes the page, records the prompt and the agent message, prints its Page ID, then publishes — so a failure in the
+// publish comes after everything else is written, and a re-send records the prompt again. It is not sent again, flake or not. (A CREATE that failed outright and left
+// nothing behind is still retried: see the uncertain-CREATE tests.)
+test('upload does not send a failed UPDATE again, even when the failure may be a flake', async () => {
let n = 0;
const run = async () => { n += 1; return n === 1 ? { status: 1, stdout: '', stderr: 'flaky help dump' } : { status: 0, stdout: `Page ID: ${GUID}`, stderr: '' }; };
- // Use GUID as pageId (UPDATE path): no CREATE reconcile, I7 guard matches returned GUID.
- const r = await makeGenpageCli('https://x', { run, sleep: async () => {} }).upload({ appId: 'a', pageId: GUID, codeFile: 'o.tsx', name: 'Overview' });
- assert.strictEqual(r.pageId, GUID);
- assert.ok(n >= 2, 'retried after the transient failure');
+ await assert.rejects(
+ makeGenpageCli('https://x', { run, sleep: async () => {} }).upload({ appId: 'a', pageId: GUID, codeFile: 'o.tsx', name: 'Overview' }),
+ /pac genpage upload for 'Overview' failed \(flaky help dump\) — the UPDATE of page 6e0c28a2-cdbf-41ec-9186-d10fd5de6e35 MAY HAVE LANDED: /);
+ assert.strictEqual(n, 1, 'one send');
});
// The diff discovers a candidate, not authority to turn a failed CREATE into an UPDATE.
@@ -569,15 +806,18 @@ test('upload: an uncertain CREATE whose enumeration shows ZERO matches safely re
// ── Task 4: I7 upload-id guard (UPDATE returned id must equal pid) ───────────────────────────────
-test('upload (I7): direct UPDATE with caller-provided pageId returns wrong Page ID → throws', async () => {
+test('upload (I7): direct UPDATE with caller-provided pageId returns wrong Page ID → throws, as an error the build never retries', async () => {
+ const { isTransientHalt } = require('../build-model-app.js');
const WRONG_ID = 'aaaaaaaa-0000-0000-0000-000000000000';
const run = async () => ({ status: 0, stdout: `Page ID: ${WRONG_ID}`, stderr: '' });
const cli = makeGenpageCli('env', { run, sleep: async () => {}, request: createdPage() });
- // pageId: GUID but pac returns WRONG_ID → mismatch must halt
- await assert.rejects(
- cli.upload({ appId: 'app-1', pageId: GUID, codeFile: 'x.tsx', name: 'Overview' }),
- /unexpected Page ID|mismatched/i
- );
+ // pageId: GUID but pac returns WRONG_ID → mismatch must halt. The send did something, and the message quotes the page's name — user text, here one that reads as a
+ // SQL timeout to the build's check of a transient halt — so it carries `transient: false`.
+ const error = await cli.upload({ appId: 'app-1', pageId: GUID, codeFile: 'x.tsx', name: 'SQL Timeouts' }).then(() => null, (e) => e);
+ assert.match(String(error && error.message), /unexpected Page ID|mismatched/i);
+ assert.strictEqual(error.transient, false);
+ assert.strictEqual(isTransientHalt(error), false);
+ assert.strictEqual(isTransientHalt(new Error(error.message)), true, 'the control: the words alone read as transient');
});
// Stop before any candidate update; the explicit-update returned-id guard remains above.
@@ -1075,24 +1315,26 @@ test('a malformed summary line makes the listing unrecognized, not empty', () =>
// update — where the caller supplies `pageId`, so `pid` is truthy from the first attempt — sat
// through every attempt on a fault that can never resolve itself, burying the real message under
// "after 3 attempt(s)". The correct test is whether the NEXT attempt runs the SAME command.
-test('a deterministic failure on an ORDINARY update stops after one attempt', async () => {
+test('a deterministic failure on an ORDINARY update stops after one attempt, as an ordinary error: pac refused it before it sent anything', async () => {
let attempts = 0;
const run = async () => {
attempts += 1;
// Real pac wording for an argument fault — retrying cannot change the outcome.
return { status: 1, stdout: '', stderr: "Error: The value passed to '--code-file' is invalid. The file 'o.tsx' could not be found." };
};
- await assert.rejects(
- makeGenpageCli('https://x', { run, sleep: async () => {} })
- .upload({ appId: 'a', pageId: GUID, codeFile: 'o.tsx', name: 'Overview' }),
- /pac genpage upload failed/i);
+ const error = await makeGenpageCli('https://x', { run, sleep: async () => {} })
+ .upload({ appId: 'a', pageId: GUID, codeFile: 'o.tsx', name: 'Overview' }).then(() => null, (e) => e);
+ assert.match(String(error && error.message), /^pac genpage upload failed for 'Overview': Error: The value passed to '--code-file' is invalid/);
+ assert.doesNotMatch(error.message, /MAY HAVE LANDED/, 'pac checks its arguments before it sends anything, so nothing can have landed');
+ assert.notStrictEqual(error.transient, false);
assert.strictEqual(attempts, 1,
`a deterministic UPDATE fault must not be retried; ran ${attempts} attempt(s)`);
});
-// The control: a TRANSIENT failure on the same ordinary update is still retried, so the guard did
-// not simply disable retries for updates.
-test('a transient failure on an ordinary update is still retried', async () => {
+// The control: a failure that is NOT about pac's arguments — a service message that invites a retry — is no proof that nothing was written (pac can fail in the
+// publish, after the page and its messages are written), so an update is not sent again for it either: it is told as one that may have landed. Only a CREATE that
+// failed outright and left nothing in the listing is retried.
+test('a transient-looking failure on an ordinary update is not retried: it is reported as one that may have landed', async () => {
let attempts = 0;
const run = async () => {
attempts += 1;
@@ -1101,9 +1343,9 @@ test('a transient failure on an ordinary update is still retried', async () => {
await assert.rejects(
makeGenpageCli('https://x', { run, sleep: async () => {} })
.upload({ appId: 'a', pageId: GUID, codeFile: 'o.tsx', name: 'Overview' }),
- /pac genpage upload failed/i);
- assert.ok(attempts > 1,
- `a transient fault must still be retried; ran ${attempts} attempt(s)`);
+ /failed \(Error: The service is temporarily unavailable\. Please try again\.\) — the UPDATE of page [^ ]+ MAY HAVE LANDED/);
+ assert.strictEqual(attempts, 1,
+ `a failed UPDATE must not be sent again; ran ${attempts} attempt(s)`);
});
// Even a deterministic-looking failure can leave a row, but its id does not authorize another mutation.
@@ -1140,3 +1382,777 @@ test('enumeratePages can include unpublished app-scoped pages without changing t
assert.ok(seen[1].includes('--app-id') && seen[1].includes('app-1'), 'option still combines with --app-id');
assert.ok(seen[1].includes('--include-unpublished'), 'the requested option reaches pac argv');
});
+
+// ── A pac call has a time limit ──────────────────────────────────────────────────────────────────────────────────────────────────
+// A page upload once stalled — no CPU, no network — for 17 minutes, until the process was killed by hand. So a pac call waits a bounded time, ends the WHOLE
+// process tree when it runs out, and reports `{ status: null, timedOut: true }`, which no exit code is, so a caller can tell a stalled call from a failed one.
+// What each caller does about it follows from what the call can have done before it was stopped (pac's upload writes the page, records its prompt and agent message,
+// prints `Page ID`, then publishes):
+// list, download read only → retried once
+// upload (UPDATE) may have landed, or be landing → NOT retried: a second send can record the prompt twice and overwrite a later change; reported as one that may have landed
+// upload (CREATE) may have been created, or still be being created → an UNCERTAIN create: reported, and it is NEVER re-run; a Page ID already printed names the page it made
+const { EventEmitter } = require('node:events');
+const { PassThrough } = require('node:stream');
+const { setTimeout: sleepMs } = require('node:timers/promises');
+const { PAC_TIMEOUT_ENV } = require('../lib/cli-failure.js');
+
+// The deadline of a pac call, in the test's hands: runPac arms it with the budget it was given, and `fire()` is the moment that time passes. No test here waits for a real timer.
+function manualClock() {
+ const clock = {
+ callback: null,
+ armedFor: null,
+ setTimeout(callback, ms) { clock.callback = callback; clock.armedFor = ms; return clock; },
+ clearTimeout() { clock.callback = null; },
+ unref() { return clock; },
+ get armed() { return clock.callback !== null; },
+ fire() {
+ const callback = clock.callback;
+ assert.ok(callback, 'the deadline is armed');
+ clock.callback = null;
+ callback();
+ },
+ };
+ return clock;
+}
+// A pac that is never going to finish by itself: pipes to write to, a pid, and nothing else happens until the test says so.
+function stalledChild(pid = 4242) {
+ const child = new EventEmitter();
+ child.pid = pid;
+ child.stdout = new PassThrough();
+ child.stderr = new PassThrough();
+ child.unrefs = 0;
+ child.unref = () => { child.unrefs += 1; };
+ return child;
+}
+const settle = () => new Promise((resolve) => setImmediate(resolve));
+// Waits for something that will happen, and ends the moment it does; the bound only turns a hang into a failure that says what never happened.
+async function until(condition, what, limitMs = 60000) {
+ const deadline = Date.now() + limitMs;
+ while (!condition()) {
+ if (Date.now() > deadline) assert.fail(`${what} did not happen within ${limitMs}ms`);
+ await sleepMs(10);
+ }
+}
+const timedOutRun = (ms = 180000, command = 'pac model genpage list') => ({ status: null, timedOut: true, timeoutMs: ms, command, stdout: '', stderr: '' });
+
+test('runPac gives up on a pac that never finishes: partial output kept, the tree killed once, and a result that says it timed out', async () => {
+ const clock = manualClock();
+ const child = stalledChild();
+ const killed = [];
+ const results = [];
+ const call = runPac(['model', 'genpage', 'upload', '--code-file', 'a.tsx'], { timeoutMs: 600000, clock, spawn: () => child, killTree: (c) => killed.push(c) })
+ .then((r) => { results.push(r); return r; });
+ assert.strictEqual(clock.armedFor, 600000, 'armed with the budget it was given');
+ child.stdout.write('Connected as tester\n');
+ child.stderr.write('Warning: slow response\n');
+ await settle();
+ assert.strictEqual(results.length, 0, 'still waiting: a slow call is not a stalled one');
+ clock.fire();
+ const r = await call;
+ assert.strictEqual(r.status, null, 'no exit code, because there was no exit');
+ assert.strictEqual(r.timedOut, true);
+ assert.strictEqual(r.timeoutMs, 600000);
+ assert.strictEqual(r.command, 'pac model genpage upload');
+ assert.strictEqual(r.stdout, 'Connected as tester\n', 'what pac printed before it stalled is kept');
+ assert.match(r.stderr, /Warning: slow response/);
+ assert.deepStrictEqual(killed, [child], 'the whole tree is ended, once');
+ assert.ok(child.stdout.destroyed && child.stderr.destroyed, 'the pipes are released, so a survivor that holds them cannot keep this process alive');
+ assert.ok(child.unrefs >= 1, 'and the child no longer holds the event loop open');
+ // A child that closes, or fails, after its time was up cannot settle the call a second time or be killed again.
+ child.emit('error', new Error('late failure'));
+ child.emit('close', 0);
+ await settle();
+ assert.strictEqual(results.length, 1, 'resolved once');
+ assert.strictEqual(results[0], r);
+ assert.strictEqual(r.status, null, 'the result is unchanged by the late close');
+ assert.strictEqual(killed.length, 1);
+});
+
+test('runPac leaves a call that ends in time alone: no kill, and the deadline is disarmed', async () => {
+ const clock = manualClock();
+ const child = stalledChild();
+ const killed = [];
+ const call = runPac(['model', 'genpage', 'list'], { timeoutMs: 60000, clock, spawn: () => child, killTree: (c) => killed.push(c) });
+ child.stdout.write('Found 0 generated page(s):\n');
+ child.stdout.end();
+ child.stderr.end();
+ await settle();
+ child.emit('close', 0);
+ const r = await call;
+ assert.strictEqual(r.status, 0);
+ assert.strictEqual(r.stdout, 'Found 0 generated page(s):\n');
+ assert.strictEqual(r.timedOut, undefined, 'a result that did not time out does not say so');
+ assert.strictEqual(clock.armed, false, 'a deadline left armed would kill a later reader of the same pipes');
+ assert.deepStrictEqual(killed, []);
+ // A non-zero exit is still just an exit code.
+ const failing = stalledChild();
+ const failed = runPac(['model', 'genpage', 'list'], { timeoutMs: 60000, clock: manualClock(), spawn: () => failing, killTree: () => assert.fail('nothing to kill') });
+ failing.emit('close', 3);
+ assert.strictEqual((await failed).status, 3);
+});
+
+test('runPac never arms a deadline for a pac that could not be started, and every pac call is bounded by default', async () => {
+ const clock = manualClock();
+ const r = await runPac(['model', 'genpage', 'list'], { timeoutMs: 600000, clock, spawn: () => { throw new Error('spawn pac ENOENT: not found on PATH'); }, killTree: () => assert.fail('nothing to kill') });
+ assert.notStrictEqual(r.status, 0);
+ assert.match(r.stderr, /ENOENT/);
+ assert.strictEqual(r.timedOut, undefined);
+ assert.strictEqual(clock.armed, false);
+ // No budget given: the read budget applies, so no call is ever unbounded.
+ const unbounded = manualClock();
+ const child = stalledChild();
+ const call = runPac(['model', 'genpage', 'list'], { clock: unbounded, spawn: () => child, killTree: () => {} });
+ assert.strictEqual(unbounded.armedFor, 180000);
+ child.emit('close', 0);
+ await call;
+});
+
+// The real thing, because a stub that "kills" a fake proves only what its author believed. On Windows pac is a `pac.cmd` shim, so the tree is
+// cmd.exe → node (the stalled pac) → node (a process it started): ending the shim alone would leave the other two running. Each of the two writes a
+// heartbeat file every 50 ms; a process that is gone stops writing — which, unlike asking whether a pid exists, cannot be fooled by a zombie or a reused pid.
+function makeHangingPac() {
+ const dir = scratch('genpage-cli-hangingpac-');
+ const script = path.join(dir, 'hanging-pac.js');
+ // Both processes end by themselves after a minute, so a run in which the kill failed (or never came) leaves nothing running on the machine.
+ fs.writeFileSync(script, [
+ "const fs = require('fs');",
+ "const base = process.argv[process.argv.indexOf('--hang') + 1];",
+ "const beat = \"const fs = require('fs'); setTimeout(() => process.exit(0), 60000); setInterval(() => fs.writeFileSync(process.argv[1], String(process.hrtime.bigint())), 50);\";",
+ "require('child_process').spawn(process.execPath, ['-e', beat, base + '.grandchild'], { stdio: 'ignore', windowsHide: true });",
+ 'setTimeout(() => process.exit(0), 60000);',
+ "setInterval(() => fs.writeFileSync(base + '.pac', String(process.hrtime.bigint())), 50);",
+ '',
+ ].join('\n'), 'utf8');
+ if (process.platform === 'win32') {
+ fs.writeFileSync(path.join(dir, 'pac.cmd'), `@"${process.execPath}" "${script}" %*\r\n`, 'utf8');
+ } else {
+ fs.writeFileSync(path.join(dir, 'pac'), `#!/bin/sh\nexec "${process.execPath}" "${script}" "$@"\n`, { mode: 0o755 });
+ }
+ return dir;
+}
+const readBeat = (file) => { try { return fs.readFileSync(file, 'utf8'); } catch { return null; } };
+
+test('runPac: a real stalled pac, and the process it started, are both ended when the time is up', async () => {
+ const dir = makeHangingPac();
+ const base = path.join(scratch('genpage-cli-beats-'), 'beat');
+ const files = [`${base}.pac`, `${base}.grandchild`];
+ const clock = manualClock();
+ const result = await withPathFirst(dir, async () => {
+ const call = runPac(['model', 'genpage', 'upload', '--hang', base], { timeoutMs: 600000, clock });
+ // Both are running — each has beaten at least twice — before the deadline passes, so what is ended below is two live processes, however slow this machine is.
+ const firstSeen = files.map(() => null);
+ await until(() => files.every((file, i) => {
+ const beat = readBeat(file);
+ if (beat !== null && firstSeen[i] === null) firstSeen[i] = beat;
+ return beat !== null && beat !== firstSeen[i];
+ }), 'the stalled pac and the process under it starting');
+ clock.fire();
+ return call;
+ });
+ assert.strictEqual(result.timedOut, true);
+ assert.strictEqual(result.status, null);
+ await sleepMs(300); // a beat already in flight lands
+ const after = files.map(readBeat);
+ await sleepMs(500); // ten beats of a live process
+ assert.deepStrictEqual(files.map(readBeat), after, 'neither the stalled pac nor the process under it is still running');
+});
+
+// ── What the callers do with a timeout ───────────────────────────────────────────────────────────────────────────────────────────
+
+test('every pac call gets the budget of its kind: 3 min to list or download, 10 min to upload, or the environment override', async () => {
+ const seen = [];
+ const run = async (args, options) => {
+ seen.push([args[2], options && options.timeoutMs]);
+ if (args[2] === 'list') return { status: 0, stdout: LIST_ONE, stderr: '' };
+ return { status: 0, stdout: `Page ID: ${GUID}`, stderr: '' };
+ };
+ const exercise = async (processEnv) => {
+ seen.length = 0;
+ const cli = makeGenpageCli('https://x', { run, sleep: async () => {}, processEnv });
+ await cli.enumerate({ appId: 'a' });
+ await cli.enumeratePages('a', { includeUnpublished: true });
+ await cli.enumerateEnv();
+ await cli.list({ appId: 'a' });
+ await cli.download({ appId: 'a', outputDir: 'out' });
+ await cli.upload({ appId: 'a', pageId: GUID, codeFile: 'o.tsx', name: 'Overview' });
+ return seen.map(([kind, ms]) => `${kind}:${ms}`);
+ };
+ assert.deepStrictEqual(await exercise({}), ['list:180000', 'list:180000', 'list:180000', 'list:180000', 'download:180000', 'upload:600000']);
+ assert.deepStrictEqual(await exercise({ [PAC_TIMEOUT_ENV]: '45000' }), ['list:45000', 'list:45000', 'list:45000', 'list:45000', 'download:45000', 'upload:45000']);
+ assert.deepStrictEqual(await exercise({ [PAC_TIMEOUT_ENV]: 'soon' }), ['list:180000', 'list:180000', 'list:180000', 'list:180000', 'download:180000', 'upload:600000'], 'an unusable value keeps the defaults');
+});
+
+test('a listing that times out is retried once, then reported as a timeout — never as an empty app or environment', async () => {
+ const calls = {
+ enumerate: (cli) => cli.enumerate({ appId: 'app-1' }),
+ enumeratePages: (cli) => cli.enumeratePages('app-1', { includeUnpublished: true }),
+ enumerateEnv: (cli) => cli.enumerateEnv(),
+ };
+ for (const [name, call] of Object.entries(calls)) {
+ let n = 0;
+ const recovers = makeGenpageCli('env', { run: async () => { n += 1; return n === 1 ? timedOutRun() : { status: 0, stdout: LIST_ONE, stderr: '' }; }, sleep: async () => {}, attempts: 3 });
+ const ok = await call(recovers);
+ assert.strictEqual(ok.ok, true, `${name}: the retry reads the listing`);
+ assert.strictEqual(n, 2, `${name}: one retry`);
+
+ n = 0;
+ const stalls = makeGenpageCli('env', { run: async () => { n += 1; return timedOutRun(); }, sleep: async () => {}, attempts: 3 });
+ const r = await call(stalls);
+ assert.strictEqual(r.ok, false, `${name}: a listing that never answers is not an empty one`);
+ assert.strictEqual(n, 2, `${name}: it stops after the second timeout, though the ordinary budget is three attempts`);
+ assert.match(r.error, /failed after 2 attempt\(s\): `pac model genpage list` did not finish within 180 s and was stopped/, name);
+ assert.match(r.error, /POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS=/, `${name}: and says how to allow it longer`);
+ assert.doesNotMatch(r.error, /null/, `${name}: no "exited null"`);
+ }
+ // Ordinary failures keep the ordinary budget, and a timeout among them counts once.
+ let n = 0;
+ const mixed = makeGenpageCli('env', { run: async () => { n += 1; return n === 1 ? timedOutRun() : n === 2 ? { status: 1, stdout: '', stderr: 'flake' } : { status: 0, stdout: LIST_ONE, stderr: '' }; }, sleep: async () => {}, attempts: 3 });
+ assert.strictEqual((await mixed.enumerateEnv()).ok, true);
+ assert.strictEqual(n, 3);
+});
+
+test('a download that times out is retried once with the same arguments; any other failure is still reported at once', async () => {
+ const seen = [];
+ let n = 0;
+ const recovers = makeGenpageCli('env', { run: async (args) => { seen.push(args); n += 1; return n === 1 ? timedOutRun(180000, 'pac model genpage download') : { status: 0, stdout: '', stderr: '' }; }, sleep: async () => {} });
+ assert.strictEqual(await recovers.download({ appId: 'app-1', outputDir: 'out', pageIds: [GP_A] }), true);
+ assert.strictEqual(seen.length, 2);
+ assert.deepStrictEqual(seen[1], seen[0], 'a read is repeated exactly');
+
+ n = 0;
+ const stalls = makeGenpageCli('env', { run: async () => { n += 1; return timedOutRun(180000, 'pac model genpage download'); }, sleep: async () => {} });
+ await assert.rejects(stalls.download({ appId: 'app-1', outputDir: 'out' }), /pac genpage download failed: `pac model genpage download` did not finish within 180 s and was stopped/);
+ assert.strictEqual(n, 2, 'one retry, then the timeout is reported');
+
+ n = 0;
+ const fails = makeGenpageCli('env', { run: async () => { n += 1; return { status: 1, stdout: '', stderr: 'Error: boom' }; }, sleep: async () => {} });
+ await assert.rejects(fails.download({ appId: 'app-1', outputDir: 'out' }), /pac genpage download failed: Error: boom/);
+ assert.strictEqual(n, 1, 'an ordinary failure is not retried, as before');
+});
+
+// An UPDATE names the page it writes (`--page-id`), but a second send is not harmless for that: pac writes the page, records the prompt and the agent message in two separate
+// requests, prints `Page ID`, then publishes — so a call stalled in the publish has already written everything, and a re-send records the prompt twice and goes out minutes after
+// the caller's own checks, overwriting whatever the maker saved meanwhile. So it is reported, with what to look at, and the caller's own guards decide a re-run.
+test('an UPDATE that times out is NOT sent again: it is reported as one that may have landed, with the check to run before anything is re-run', async () => {
+ const seen = [];
+ const run = async (args) => { seen.push(args); return seen.length === 1 ? timedOutRun(600000, 'pac model genpage upload') : { status: 0, stdout: `Page ID: ${GUID}`, stderr: '' }; };
+ const cli = makeGenpageCli('https://contoso.crm.dynamics.com', { run, sleep: async () => {}, attempts: 3 });
+ await assert.rejects(cli.upload({ appId: 'app-1', pageId: GUID, codeFile: 'out/overview.tsx', name: 'Overview' }), (e) => {
+ assert.match(e.message, /^pac genpage upload for 'Overview' timed out after 600 s and was stopped — the UPDATE of page 6e0c28a2-cdbf-41ec-9186-d10fd5de6e35 MAY HAVE LANDED: /);
+ assert.match(e.message, /pac writes the page, then records the prompt and the agent message, then publishes/, 'what it may have got through');
+ assert.match(e.message, /It was NOT sent again: a second send can record the prompt twice, and would overwrite a change made to the page since\./);
+ assert.match(e.message, /genpage-base\.js check --env https:\/\/contoso\.crm\.dynamics\.com --app-id app-1 --page-id 6e0c28a2-cdbf-41ec-9186-d10fd5de6e35 --file out\/overview\.tsx/, 'the check to run, with this call\'s own values');
+ assert.match(e.message, /"contentSame": true means the update landed; "deployed": "unchanged" means it did not/);
+ assert.match(e.message, /re-run the upload: its own checks decide whether it may go ahead\./);
+ assert.match(e.message, /POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS=1200000 allows a slow upload longer\./);
+ assert.doesNotMatch(e.message, /retry\b/i, 'a stalled upload is not told to "retry"');
+ return true;
+ });
+ assert.strictEqual(seen.length, 1, 'one send, though the ordinary budget is three attempts: it is not run a second time, and nothing is listed or snapshotted around it');
+ assert.strictEqual(seen[0][2], 'upload');
+ assert.ok(seen[0].includes('--page-id') && seen[0].includes(GUID));
+ // An update that FAILED is not sent again either (the tests of a failed UPDATE below): only how it is told differs.
+ let n = 0;
+ const flaky = makeGenpageCli('https://x', { run: async () => { n += 1; return n === 1 ? { status: 1, stdout: '', stderr: 'flaky' } : { status: 0, stdout: `Page ID: ${GUID}`, stderr: '' }; }, sleep: async () => {} });
+ await assert.rejects(flaky.upload({ appId: 'a', pageId: GUID, codeFile: 'o.tsx', name: 'Overview' }), /failed \(flaky\) — the UPDATE of page [^ ]+ MAY HAVE LANDED/);
+ assert.strictEqual(n, 1, 'a failure that is not a timeout is not sent again either');
+});
+
+test('an UPDATE that timed out after pac printed the Page ID says the page was written and the stall came while it published; at the longest budget no longer one is offered', async () => {
+ const run = async () => ({ ...timedOutRun(3600000, 'pac model genpage upload'), stdout: `Connected as [email protected]\r\nUploading page...\r\nPage ID: ${GUID}\r\n` });
+ await assert.rejects(makeGenpageCli('https://x', { run, sleep: async () => {} }).upload({ appId: 'a', pageId: GUID, codeFile: 'o.tsx', name: 'Overview' }), (e) => {
+ assert.match(e.message, /MAY HAVE LANDED: pac had printed the Page ID, which it does once the page and its messages are written, so the stall came while it was publishing\./);
+ assert.doesNotMatch(e.message, /pac writes the page, then records/, 'the general account is replaced by the specific one');
+ assert.match(e.message, /It was NOT sent again/);
+ assert.doesNotMatch(e.message, /POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS/, 'at the longest budget there is no longer one to suggest');
+ return true;
+ });
+ // A Page ID cut off mid-token is not one.
+ const cut = async () => ({ ...timedOutRun(600000, 'pac model genpage upload'), stdout: 'Page ID: 6e0c28a2-cdbf-41ec-91' });
+ await assert.rejects(makeGenpageCli('https://x', { run: cut, sleep: async () => {} }).upload({ appId: 'a', pageId: GUID, codeFile: 'o.tsx', name: 'Overview' }), /pac writes the page, then records the prompt/);
+});
+
+// The check is a command the user — or the agent — pastes, so a code file under a folder with a space in its name (a Windows profile folder is often one) has to stay one
+// argument in it, and a path with shell syntax in it (an untrusted checkout) must not run any of it: such a path is single-quoted, and one no shell can be given unchanged
+// (a quote or a line break in it, say) is not written into the command at all — a placeholder is, and the path is named as data.
+test('the check an UPDATE that timed out points to is a whole command, and keeps a code file path one literal argument — or names it outside the command', async () => {
+ const cli = makeGenpageCli('https://contoso.crm.dynamics.com', { run: async () => timedOutRun(600000, 'pac model genpage upload'), sleep: async () => {} });
+ await assert.rejects(cli.upload({ appId: 'app-1', pageId: GUID, codeFile: 'C:\\Users\\Dev User\\pages\\overview.tsx', name: 'Overview' }), (e) => {
+ assert.match(e.message, /First see what is deployed: node scripts\/genpage-base\.js check --env https:\/\/contoso\.crm\.dynamics\.com --app-id app-1 --page-id 6e0c28a2-cdbf-41ec-9186-d10fd5de6e35 --file 'C:\\Users\\Dev User\\pages\\overview\.tsx' \("contentSame"/);
+ return true;
+ });
+ await assert.rejects(cli.upload({ appId: 'app-1', pageId: GUID, codeFile: 'out/overview.tsx', name: 'Overview' }), /--file out\/overview\.tsx \("contentSame"/, 'a plain path is shown as it is');
+ await assert.rejects(cli.upload({ appId: 'app-1', pageId: GUID, codeFile: 'pages/x;rm -rf ~;$(curl e.vil).tsx', name: 'Overview' }), (e) => {
+ assert.ok(e.message.includes("--file 'pages/x;rm -rf ~;$(curl e.vil).tsx' (\"contentSame\""), 'shell syntax in a path stays inside single quotes');
+ return true;
+ });
+ await assert.rejects(cli.upload({ appId: 'app-1', pageId: GUID, codeFile: "pages/it's;echo x.tsx", name: 'Overview' }), (e) => {
+ assert.ok(e.message.includes('--file <file> ("contentSame"'), 'a path with a quote is not written into the command');
+ assert.ok(e.message.includes('<file> is "pages/it\'s;echo x.tsx"; it is not written into the command because no way of writing it reaches the command unchanged in both PowerShell and a POSIX shell. Then re-run the upload'), e.message);
+ assert.ok(!e.message.includes("--file 'pages/it"), 'never as an argument');
+ return true;
+ });
+ await assert.rejects(cli.upload({ appId: 'app-1', pageId: GUID, codeFile: 'pages/x"y.tsx', name: 'Overview' }), (e) => {
+ assert.ok(e.message.includes('--file <file> ("contentSame"'), 'Windows PowerShell would drop the double quote on its way to node');
+ assert.ok(e.message.includes('<file> is "pages/x\\"y.tsx"; it is not written into the command'), e.message);
+ return true;
+ });
+});
+
+// The upload script sends pac a COPY of the bytes it checked (removed once pac answers) and passes the file the caller named as `sourceFile`: the check the message points to is
+// about that file — the one its base marker belongs to — never the copy, which is gone by the time anyone reads the message.
+test('the check an UPDATE that timed out points to names the caller\'s file (sourceFile), never the copy pac read', async () => {
+ const cli = makeGenpageCli('https://contoso.crm.dynamics.com', { run: async () => timedOutRun(600000, 'pac model genpage upload'), sleep: async () => {} });
+ const copy = 'C:\\Users\\Dev User\\AppData\\Local\\Temp\\genpage-code-x1y2z3\\overview.tsx';
+ await assert.rejects(cli.upload({ appId: 'app-1', pageId: GUID, codeFile: copy, sourceFile: 'C:\\Users\\Dev User\\pages\\overview.tsx', name: 'Overview' }), (e) => {
+ assert.match(e.message, /--file 'C:\\Users\\Dev User\\pages\\overview\.tsx' \("contentSame"/);
+ assert.ok(!e.message.includes('genpage-code-'), 'the copy is not named');
+ return true;
+ });
+});
+
+// The build is a different caller: it writes no base marker, so `genpage-base.js check` could only answer "unknown" about what is deployed, and the code file it hands pac — for
+// every page — is a STAGING copy that the build deletes when it ends, so the command the standalone script is told to run fails on a missing file. The build's message sends the reader
+// to the deployed page through the download the build already uses, and says what running the build again does (sdk-build.js passes `caller: 'build'`).
+test('an UPDATE that times out under the BUILD is told to read the deployed page with pac\'s download and to run the build again — never to check a file the build deletes', async () => {
+ const seen = [];
+ const run = async (args) => { seen.push(args); return seen.length === 1 ? timedOutRun(600000, 'pac model genpage upload') : { status: 0, stdout: `Page ID: ${GUID}`, stderr: '' }; };
+ const cli = makeGenpageCli('https://contoso.crm.dynamics.com', { run, sleep: async () => {}, attempts: 3 });
+ const staging = 'C:\\Users\\Dev User\\crm\\.maker-workspace\\.pageref-deploy\\0c9b6f1e\\overview.tsx';
+ await assert.rejects(cli.upload({ appId: 'app-1', pageId: GUID, codeFile: staging, name: 'Overview', caller: 'build' }), (e) => {
+ assert.match(e.message, /^pac genpage upload for 'Overview' timed out after 600 s and was stopped — the UPDATE of page 6e0c28a2-cdbf-41ec-9186-d10fd5de6e35 MAY HAVE LANDED: /);
+ assert.match(e.message, /pac writes the page, then records the prompt and the agent message, then publishes/, 'what it may have got through is still said');
+ assert.match(e.message, /It was NOT sent again: a second send can record the prompt twice, and would overwrite a change made to the page since\./);
+ assert.match(e.message, /First see what is deployed: pac model genpage download --environment https:\/\/contoso\.crm\.dynamics\.com --app-id app-1 --page-id 6e0c28a2-cdbf-41ec-9186-d10fd5de6e35 --output-directory <folder>, then read the page\.tsx in the folder under <folder> that is named for the page id \(pac writes the id in its own letter case, so look for it without regard to case; /);
+ // pac names the downloaded folder with ITS casing of the id, which need not be the one the caller typed (genpage-base.js findDownloadedPageDir), so no path is built from the id as it was typed.
+ assert.doesNotMatch(e.message, /<folder>[\\/]6e0c28a2/, 'no path spelled with the id as typed: on a case-sensitive file system it can name a folder that is not there');
+ assert.match(e.message, /a page that links to another shows that page's id where its source in the app folder has a PAGEREF_ name/);
+ assert.match(e.message, /Then run the build again: it sends this page once more, to the same page id, so nothing new is created — but if the stalled send did land, the page's history now records its prompt a second time, and anything saved to the page in Maker since is replaced by the app folder's version\. Look first if either matters\./);
+ assert.match(e.message, /POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS=1200000 allows a slow upload longer\./);
+ // Nothing the build cannot support: no check on a file it deletes, no base marker it never wrote, no upload script to re-run.
+ assert.doesNotMatch(e.message, /genpage-base\.js|contentSame|"deployed"|base marker|re-run the upload|its own checks decide/);
+ assert.ok(!e.message.includes(staging) && !e.message.includes('.pageref-deploy'), 'the staging copy is not named');
+ assert.doesNotMatch(e.message, /retry\b/i, 'a stalled upload is not told to "retry"');
+ assert.strictEqual(e.transient, false, 'marked so that nothing retries it');
+ return true;
+ });
+ assert.strictEqual(seen.length, 1, 'one send, as for any caller: it is not sent again');
+ assert.strictEqual(seen[0][2], 'upload');
+ // The advice's command is whole: the download it names takes exactly the arguments the wrapper's own download passes.
+ const download = [];
+ await makeGenpageCli('https://contoso.crm.dynamics.com', { run: async (args) => { download.push(args); return { status: 0, stdout: '', stderr: '' }; }, sleep: async () => {} }).download({ appId: 'app-1', outputDir: '<folder>', pageIds: [GUID] });
+ assert.deepStrictEqual(download[0].slice(0, 3), ['model', 'genpage', 'download']);
+ for (const part of ['--environment', 'https://contoso.crm.dynamics.com', '--app-id', 'app-1', '--page-id', GUID, '--output-directory']) assert.ok(download[0].includes(part), part);
+ // Any other caller — the upload script, which names no caller — keeps the check against its code file and the re-run through its own guards.
+ for (const caller of [undefined, 'upload', 'other']) {
+ await assert.rejects(makeGenpageCli('https://x', { run: async () => timedOutRun(600000, 'pac model genpage upload'), sleep: async () => {} }).upload({ appId: 'a', pageId: GUID, codeFile: 'out/p.tsx', name: 'N', caller }),
+ /First see what is deployed: node scripts\/genpage-base\.js check --env https:\/\/x --app-id a --page-id [^ ]+ --file out\/p\.tsx[\s\S]*Then re-run the upload: its own checks decide whether it may go ahead\./, String(caller));
+ }
+});
+
+// A stalled upload must never be sent again by anything — and the build has a retry of its own for a halt it judges transient (isTransientHalt, build-model-app.js), which would be a re-send.
+// Neither message may read as transient, with or without the marker the error carries.
+test('the message of an UPDATE that timed out is not one the build retries, for either caller', async () => {
+ const { isTransientHalt } = require('../build-model-app.js');
+ const { BuildHalt } = require('../lib/entity-provision.js');
+ for (const caller of ['build', undefined]) {
+ const cli = makeGenpageCli('https://contoso.crm.dynamics.com', { run: async () => timedOutRun(600000, 'pac model genpage upload'), sleep: async () => {} });
+ const error = await cli.upload({ appId: 'app-1', pageId: GUID, codeFile: 'out/overview.tsx', name: 'Overview', caller }).then(() => null, (e) => e);
+ assert.ok(error, String(caller));
+ // The way the build reports it: wrapped by the runner, with the error as its cause.
+ assert.strictEqual(isTransientHalt(new BuildHalt(`pages failed: ${error.message}`, { phase: 'pages', code: 'sdk-error', cause: error })), false, `${String(caller)}: wrapped`);
+ // The words alone, as an error that does not carry the marker.
+ assert.strictEqual(isTransientHalt(new Error(error.message)), false, `${String(caller)}: the text itself`);
+ }
+});
+
+// An UPDATE that FAILS is in the same state as one that stalled: pac can fail in the publish, after it wrote the page and recorded the prompt and the agent message, so a
+// second send records them again and can overwrite a change saved in between. It is not sent again, and is told as one that may have landed — what pac had printed says how far
+// it got — with each caller's own look-first advice. An exit 0 with no Page ID is one too, whatever its words: pac said it succeeded. Only a non-zero exit for pac's own
+// arguments or files is an ordinary failure (the deterministic tests above): pac checks those before it sends anything.
+test('an UPDATE that FAILS is NOT sent again: it is reported as one that may have landed, with how far pac got and the check to run', async () => {
+ const cases = [
+ ['a non-zero exit', { status: 1, stdout: '', stderr: 'Error: Something went wrong.' },
+ /^pac genpage upload for 'Overview' failed \(Error: Something went wrong\.\) — the UPDATE of page 6e0c28a2-cdbf-41ec-9186-d10fd5de6e35 MAY HAVE LANDED: pac writes the page, then records the prompt and the agent message, then publishes, so the failure can have come after any of those\. /],
+ ['a non-zero exit after pac printed the Page ID', { status: 1, stdout: `Uploading page...\r\nPage ID: ${GUID}\r\nPublishing...\r\n`, stderr: 'Error: Publish failed.' },
+ /failed \(Error: Publish failed\.\) — the UPDATE of page [^ ]+ MAY HAVE LANDED: pac had printed the Page ID, which it does once the page and its messages are written, so the failure came while it was publishing\. /],
+ ['an exit 0 with no Page ID', { status: 0, stdout: 'Uploading page...\r\n', stderr: '' },
+ /failed \(returned no Page ID: Uploading page\.\.\.\) — the UPDATE of page [^ ]+ MAY HAVE LANDED: pac writes the page/],
+ ['an exit 0 with no Page ID, in words that read like a refused file', { status: 0, stdout: "Error: The file 'x.tsx' could not be found.\r\n", stderr: '' },
+ /failed \(returned no Page ID: Error: The file 'x\.tsx' could not be found\.\) — the UPDATE of page [^ ]+ MAY HAVE LANDED/],
+ // After the Page ID pac's only step is the publish, whose error carries the server's own text — which can read like a refused file. The Page ID proves the page and its
+ // messages were written, so it is no refusal of pac's arguments, whatever the words.
+ ['a non-zero exit after pac printed the Page ID, in words that read like a refused file', { status: 1, stdout: `Page ID: ${GUID}\r\n`, stderr: 'Error: Required file not found.' },
+ /failed \(Error: Required file not found\.\) — the UPDATE of page [^ ]+ MAY HAVE LANDED: pac had printed the Page ID, which it does once the page and its messages are written, so the failure came while it was publishing\. /],
+ ];
+ for (const [what, result, wanted] of cases) {
+ const seen = [];
+ const cli = makeGenpageCli('https://contoso.crm.dynamics.com', { run: async (args) => { seen.push(args); return result; }, sleep: async () => {}, attempts: 3 });
+ await assert.rejects(cli.upload({ appId: 'app-1', pageId: GUID, codeFile: 'tmp/copy/overview.tsx', sourceFile: 'out/overview.tsx', name: 'Overview' }), (e) => {
+ assert.match(e.message, wanted, what);
+ assert.match(e.message, /It was NOT sent again: a second send can record the prompt twice, and would overwrite a change made to the page since\./, what);
+ assert.match(e.message, /First see what is deployed: node scripts\/genpage-base\.js check --env https:\/\/contoso\.crm\.dynamics\.com --app-id app-1 --page-id 6e0c28a2-cdbf-41ec-9186-d10fd5de6e35 --file out\/overview\.tsx /, `${what}: the caller's file, never the copy pac read`);
+ assert.match(e.message, /Then re-run the upload: its own checks decide whether it may go ahead\.$/, what);
+ assert.doesNotMatch(e.message, /PAC_TIMEOUT_MS|timed out/, `${what}: a failure is not a timeout, and no longer budget is offered`);
+ assert.strictEqual(e.transient, false, what);
+ return true;
+ });
+ assert.strictEqual(seen.length, 1, `${what}: one send, though the budget is three attempts`);
+ assert.ok(seen[0].includes('--page-id') && seen[0].includes(GUID), what);
+ }
+ // Under the build: it keeps no base marker and deletes its staging copies, so it is told to read the deployed page with pac's download, and what a re-run of the build costs.
+ const built = makeGenpageCli('https://x', { run: async () => ({ status: 1, stdout: '', stderr: 'Error: Something went wrong.' }), sleep: async () => {} });
+ await assert.rejects(built.upload({ appId: 'a', pageId: GUID, codeFile: 'staging/p.tsx', name: 'Overview', caller: 'build' }), (e) => {
+ assert.match(e.message, /First see what is deployed: pac model genpage download --environment https:\/\/x --app-id a --page-id 6e0c28a2-cdbf-41ec-9186-d10fd5de6e35 --output-directory <folder>/);
+ assert.match(e.message, /Then run the build again: it sends this page once more, to the same page id, so nothing new is created — but if the failed send did land, the page's history now records its prompt a second time/);
+ assert.doesNotMatch(e.message, /genpage-base\.js|re-run the upload/, 'no advice the build cannot follow');
+ return true;
+ });
+});
+
+// The same for every error that follows a CREATE that was sent. Their text quotes the page's name — user text, so a page called "SQL Timeouts" reads as a SQL timeout to the build's check of a transient
+// halt — and, for a listing that failed, pac's own words ("… try again later"); a re-run of the build is a second create. Each carries `transient: false`, which that check reads on the error and on
+// the halt that wraps it. The words alone DO read as transient (the control), so it is the marker that is tested.
+test('every error that follows a CREATE that was sent is one the build never retries — whatever the page is called, whatever pac said', async () => {
+ const { isTransientHalt } = require('../build-model-app.js');
+ const { BuildHalt } = require('../lib/entity-provision.js');
+ const TRY_AGAIN_LATER = 'Error: The service is unavailable. Please try again later.';
+ const stalled = (stdout = '') => ({ ...timedOutRun(600000, 'pac model genpage upload'), stdout });
+ const failed = (stdout = '', stderr = 'Error: the upload failed') => ({ status: 1, stdout, stderr });
+ const nothing = () => ({ status: 0, stdout: LIST_EMPTY, stderr: '' });
+ const broken = () => ({ status: 1, stdout: '', stderr: TRY_AGAIN_LATER });
+ const shows = (name) => ({ status: 0, stdout: listText([{ pageId: GUID, name }]), stderr: '' });
+ const scenarios = [
+ ['stalled, nothing visible yet', () => stalled(), nothing, /UNCERTAIN create/],
+ ['stalled, the listing then fails with "try again later"', () => stalled(), broken, /env enumeration failed/],
+ ['stalled, its page then shows up', () => stalled(), shows, /ambiguous ownership/],
+ ['stalled after pac printed the Page ID', () => stalled(`Page ID: ${GUID}`), nothing, /CREATED the page as/],
+ ['failed, the listing then fails with "try again later"', () => failed(), broken, /env enumeration failed/],
+ ['failed, its page then shows up', () => failed(), shows, /ambiguous ownership/],
+ ['failed after pac printed the Page ID, saying "try again later"', () => failed(`Page ID: ${GUID}`, TRY_AGAIN_LATER), nothing, /CREATED the page as/],
+ ];
+ let controls = 0;
+ for (const pageName of ['SQL Timeouts', 'Concurrent Deletes', 'Overview']) {
+ for (const [what, create, after, says] of scenarios) {
+ const uploads = [];
+ let lists = 0;
+ const run = async (args) => {
+ if (args[2] === 'list') { lists += 1; return lists === 1 ? { status: 0, stdout: LIST_EMPTY, stderr: '' } : after(pageName); }
+ uploads.push(args);
+ return create();
+ };
+ const cli = makeGenpageCli('https://contoso.crm.dynamics.com', { run, sleep: async () => {}, attempts: 3, request: createdPage(pageName) });
+ const error = await cli.upload({ appId: 'app-1', codeFile: 'o.tsx', name: pageName }).then(() => null, (e) => e);
+ const label = `${what}, page "${pageName}"`;
+ assert.ok(error, label);
+ assert.match(error.message, says, label);
+ assert.strictEqual(uploads.length, 1, `${label}: one create`);
+ assert.strictEqual(error.transient, false, `${label}: marked`);
+ assert.strictEqual(isTransientHalt(error), false, `${label}: bare`);
+ assert.strictEqual(isTransientHalt(new BuildHalt(`pages failed: ${error.message}`, { phase: 'pages', code: 'sdk-error', cause: error })), false, `${label}: as the runner wraps it`);
+ // The words alone, with no marker: what the check would have made of them.
+ if (isTransientHalt(new Error(error.message))) controls += 1;
+ }
+ }
+ assert.ok(controls >= 10, `the marker is what stops the retry: without it ${controls} of these read as transient`);
+ // Not a blanket: a listing that fails BEFORE any create was sent leaves nothing to duplicate, and stays an error the build may retry.
+ const snapshotFails = makeGenpageCli('https://x', { run: async () => ({ status: 1, stdout: '', stderr: TRY_AGAIN_LATER }), sleep: async () => {}, attempts: 3 });
+ const early = await snapshotFails.upload({ appId: 'a', codeFile: 'o.tsx', name: 'Overview' }).then(() => null, (e) => e);
+ assert.match(early.message, /cannot snapshot the environment before create/);
+ assert.notStrictEqual(early.transient, false);
+ assert.strictEqual(isTransientHalt(early), true);
+});
+
+// A run its caller ENDED (abort(), runPac's `signal`) says as little about what it did as one that timed out: pac may have written the page, may still be writing it, or may never have started.
+// So an upload that ends that way is held to the same rule — told like a stalled one, never sent again by the client's own attempts, and never by the build's re-run of a halt that reads as
+// transient — in the UPDATE branch and in every branch of an uncertain CREATE.
+test('an upload whose run was ENDED is never sent again — an UPDATE, and a CREATE in every branch — and each error is one the build never retries', async () => {
+ const { isTransientHalt } = require('../build-model-app.js');
+ const { BuildHalt } = require('../lib/entity-provision.js');
+ const TRY_AGAIN_LATER = 'Error: The service is unavailable. Please try again later.';
+ const ended = (stdout = '') => ({ status: 1, stdout, stderr: 'pac was ended: its answer is no longer needed', ended: true });
+ const nothing = () => ({ status: 0, stdout: LIST_EMPTY, stderr: '' });
+ const broken = () => ({ status: 1, stdout: '', stderr: TRY_AGAIN_LATER });
+ const shows = (name) => ({ status: 0, stdout: listText([{ pageId: GUID, name }]), stderr: '' });
+ const neverRetried = (error, label) => {
+ assert.strictEqual(error.transient, false, `${label}: marked`);
+ assert.strictEqual(isTransientHalt(error), false, `${label}: bare`);
+ assert.strictEqual(isTransientHalt(new BuildHalt(`pages failed: ${error.message}`, { phase: 'pages', code: 'sdk-error', cause: error })), false, `${label}: as the runner wraps it`);
+ assert.doesNotMatch(error.message, /POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS/, `${label}: a longer budget is no answer to a run that was ended, not stalled`);
+ };
+
+ // An UPDATE: one send, no pause for a second, and the error says it may have landed.
+ const sent = [];
+ const pauses = [];
+ const update = makeGenpageCli('https://contoso.crm.dynamics.com', { run: async (args) => { sent.push(args); return ended(); }, sleep: async (ms) => { pauses.push(ms); }, attempts: 3 });
+ const updateError = await update.upload({ appId: 'app-1', pageId: GUID, codeFile: 'o.tsx', name: 'Overview' }).then(() => null, (e) => e);
+ assert.match(updateError.message, /^pac genpage upload failed for 'Overview': pac was ended: its answer is no longer needed — the UPDATE of page 6e0c28a2-cdbf-41ec-9186-d10fd5de6e35 may have landed before it was ended, and it was NOT sent again: look at the page before running it again$/);
+ assert.strictEqual(sent.length, 1, 'one send, though the ordinary budget is three attempts');
+ assert.deepStrictEqual(pauses, [], 'and no pause for an attempt that will not be made');
+ neverRetried(updateError, 'an UPDATE that was ended');
+
+ // A CREATE. Each scenario is what the environment answers after the create was ended: nothing yet, a listing that fails, a page that shows up, and a Page ID pac had already printed.
+ const scenarios = [
+ ['nothing visible yet', () => ended(), nothing, /was ended before it answered — an UNCERTAIN create: no new page is visible in the environment yet/],
+ ['the listing then fails with "try again later"', () => ended(), broken, /was ended before it answered, and had an uncertain result and env enumeration failed/],
+ ['its page then shows up', () => ended(), shows, /was ended before it answered, and had an uncertain create \(ambiguous ownership\)/],
+ ['after pac printed the Page ID', () => ended(`Page ID: ${GUID}`), nothing, /failed after it had CREATED the page as 6e0c28a2-cdbf-41ec-9186-d10fd5de6e35/],
+ ];
+ for (const pageName of ['SQL Timeouts', 'Overview']) {
+ for (const [what, create, after, says] of scenarios) {
+ const uploads = [];
+ let lists = 0;
+ const run = async (args) => {
+ if (args[2] === 'list') { lists += 1; return lists === 1 ? { status: 0, stdout: LIST_EMPTY, stderr: '' } : after(pageName); }
+ uploads.push(args);
+ return create();
+ };
+ const cli = makeGenpageCli('https://contoso.crm.dynamics.com', { run, sleep: async () => {}, attempts: 3, request: createdPage(pageName) });
+ const error = await cli.upload({ appId: 'app-1', codeFile: 'o.tsx', name: pageName }).then(() => null, (e) => e);
+ const label = `${what}, page "${pageName}"`;
+ assert.ok(error, label);
+ assert.match(error.message, says, label);
+ assert.strictEqual(uploads.length, 1, `${label}: one create, never a second`);
+ neverRetried(error, label);
+ }
+ }
+
+ // The contrast: a create that FAILED outright (not ended) and left nothing is still safe to run again.
+ let creates = 0;
+ const failed = makeGenpageCli('https://x', { run: async (args) => { if (args[2] === 'list') return nothing(); creates += 1; return creates === 1 ? { status: 1, stdout: '', stderr: 'flaky' } : { status: 0, stdout: `Page ID: ${GUID}`, stderr: '' }; }, sleep: async () => {}, attempts: 3 });
+ assert.strictEqual((await failed.upload({ appId: 'a', codeFile: 'o.tsx', name: 'Overview' })).pageId, GUID);
+ assert.strictEqual(creates, 2);
+});
+
+// An UPDATE is never paused between two attempts: one that failed is not sent again (the tests of a failed UPDATE above), so it is reported at once — and its error is one
+// the build never retries, whatever the page is called and whatever pac said. The words alone DO read as transient (the control), so it is the marker that is tested.
+test('an UPDATE that fails is never paused for or sent again, and its error is one the build never retries — whatever the page is called, whatever pac said', async () => {
+ const { isTransientHalt } = require('../build-model-app.js');
+ const { BuildHalt } = require('../lib/entity-provision.js');
+ for (const caller of ['build', undefined]) {
+ const runs = [];
+ const pauses = [];
+ const cli = makeGenpageCli('https://contoso.crm.dynamics.com', { run: async (args) => { runs.push(args); return { status: 1, stdout: '', stderr: 'Error: The service is busy, try again later.' }; }, sleep: async (ms) => { pauses.push(ms); }, attempts: 3 });
+ const error = await cli.upload({ appId: 'app-1', pageId: GUID, codeFile: 'o.tsx', name: 'SQL Timeouts', caller }).then(() => null, (e) => e);
+ assert.match(String(error && error.message), /^pac genpage upload for 'SQL Timeouts' failed \(Error: The service is busy, try again later\.\) — the UPDATE of page [^ ]+ MAY HAVE LANDED/, String(caller));
+ assert.strictEqual(runs.length, 1, `${String(caller)}: one send`);
+ assert.deepStrictEqual(pauses, [], `${String(caller)}: no pause for an attempt that will not be made`);
+ assert.strictEqual(error.transient, false, String(caller));
+ assert.strictEqual(isTransientHalt(error), false, String(caller));
+ assert.strictEqual(isTransientHalt(new BuildHalt(`pages failed: ${error.message}`, { phase: 'pages', code: 'sdk-error', cause: error })), false, `${String(caller)}: wrapped`);
+ assert.strictEqual(isTransientHalt(new Error(error.message)), true, `${String(caller)}: the control — the text alone reads as transient`);
+ }
+});
+
+// A CREATE that timed out may have landed, may be landing, or may never have started. The env-wide id diff reports what is already visible; what is not visible YET
+// proves nothing, because the service may still be working — so a timed-out create is never run again, whatever the diff shows. And what is said to do next must not be
+// "update it" or "create it again" when the page the stalled create left behind is not in the app's navigation: an update of such a page is refused, a create duplicates it.
+// `printed` is what pac had written to stdout when it was stopped; `lists` counts the environment listings made.
+function createRun({ afterShows = [], uploads, listFails = false, printed = '', lists = { n: 0 } }) {
+ return async (args) => {
+ if (args[2] === 'list') {
+ lists.n += 1;
+ if (lists.n > 1 && listFails) return { status: 1, stdout: '', stderr: 'list failed' };
+ return { status: 0, stdout: lists.n === 1 || !afterShows.length ? LIST_EMPTY : listText(afterShows), stderr: '' };
+ }
+ uploads.push(args);
+ return { ...timedOutRun(600000, 'pac model genpage upload'), stdout: printed };
+ };
+}
+const ADD_PAGE = (id, app = 'a') => new RegExp(`add page ${id} to the app's navigation — in Maker, or with \`pac model genpage add --environment https://x --app-id ${app} --page-id ${id} --publish\``);
+
+test('a CREATE that times out is an uncertain create: its candidates are reported, and no create or update follows', async () => {
+ const uploads = [];
+ const cli = makeGenpageCli('https://x', { run: createRun({ afterShows: [{ pageId: GUID, name: 'Overview' }], uploads }), sleep: async () => {}, request: createdPage() });
+ await assert.rejects(cli.upload({ appId: 'a', codeFile: 'o.tsx', name: 'Overview' }), (e) => {
+ assert.match(e.message, /timed out and was stopped, and had an uncertain create \(ambiguous ownership\)/);
+ assert.ok(e.message.includes(`${GUID}: stored name "Overview"`));
+ // A candidate that appeared after a stalled create is most likely not in the app's navigation, so the advice places it first — an update of it would be refused.
+ assert.match(e.message, ADD_PAGE(GUID), 'it says how to place the page');
+ assert.match(e.message, new RegExp(`re-run the upload as an update with --page-id ${GUID} \\(a build: set that page's pageId to ${GUID} in the App Spec\\); or delete page ${GUID} and re-run the create`));
+ assert.match(e.message, /otherwise leave them and re-run the create\./, 'and a page that is not yours is left alone');
+ assert.doesNotMatch(e.message, /If it is yours, re-run the upload as an update/, 'update-it-straight-away is not the way on for a page the stalled create left out of the navigation');
+ return true;
+ });
+ assert.strictEqual(uploads.length, 1, 'the one create; neither a second create nor an update of the candidate');
+ assert.ok(!uploads[0].includes('--page-id'));
+ // Two candidates: the advice does not pick one for the maker.
+ const other = '5c0a4889-45fd-46ea-91a8-ff876914d644';
+ const several = makeGenpageCli('https://x', { run: createRun({ afterShows: [{ pageId: GUID, name: 'Overview' }, { pageId: other, name: 'Detail' }], uploads: [] }), sleep: async () => {}, request: createdPage() });
+ await assert.rejects(several.upload({ appId: 'a', codeFile: 'o.tsx', name: 'Overview' }), (e) => ADD_PAGE('<its id>').test(e.message) && e.message.includes(GUID) && e.message.includes(other));
+});
+
+test('a CREATE that times out with nothing visible yet is NOT run again — the service may still be creating it', async () => {
+ const uploads = [];
+ const cli = makeGenpageCli('https://x', { run: createRun({ uploads }), sleep: async () => {}, attempts: 3 });
+ await assert.rejects(cli.upload({ appId: 'a', codeFile: 'o.tsx', name: 'Overview' }), (e) => {
+ assert.match(e.message, /pac genpage upload for 'Overview' timed out/);
+ assert.match(e.message, /UNCERTAIN create/);
+ assert.match(e.message, /may still be (?:creating|running)/);
+ assert.match(e.message, /Refusing to re-run the create/);
+ assert.match(e.message, /pac model genpage list --environment https:\/\/x --include-unpublished/, 'it says how to look');
+ // If the page does appear it is the unplaced page of a stalled create: placing it comes before any update, and deleting it before another create.
+ assert.match(e.message, ADD_PAGE('<its id>'), 'and what to do if the page appears');
+ assert.match(e.message, /; or delete page <its id> and re-run the create; if none appears, re-run the create\./);
+ assert.match(e.message, /POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS=1200000 allows a slow upload longer\./);
+ return true;
+ });
+ assert.strictEqual(uploads.length, 1, 'never a second create, though the ordinary budget is three attempts');
+ // The contrast that pins the rule: a create that FAILED (not timed out) and left nothing is still safe to run again.
+ let creates = 0;
+ const failed = makeGenpageCli('https://x', { run: async (args) => { if (args[2] === 'list') return { status: 0, stdout: LIST_EMPTY, stderr: '' }; creates += 1; return creates === 1 ? { status: 1, stdout: '', stderr: 'flaky' } : { status: 0, stdout: `Page ID: ${GUID}`, stderr: '' }; }, sleep: async () => {}, attempts: 3 });
+ assert.strictEqual((await failed.upload({ appId: 'a', codeFile: 'o.tsx', name: 'Overview' })).pageId, GUID);
+ assert.strictEqual(creates, 2);
+});
+
+// pac prints `Page ID: <id>` after it has written the page and its messages and before it publishes, and before `--add-to-sitemap` places it. A create stopped after that has
+// CREATED the page: it is reported as that page, whatever else is visible, and the way on is to place it or delete it — never "update it" (refused: not in the app's
+// navigation), and never "run the create again" (a duplicate).
+test('a CREATE that times out after pac printed the Page ID is reported as created as that page, stalled before it was published or placed', async () => {
+ const uploads = [];
+ const lists = { n: 0 };
+ const printed = `Connected as [email protected]\r\nUploading page 'Overview'...\r\nPage ID: ${GUID}\r\n`;
+ const cli = makeGenpageCli('https://contoso.crm.dynamics.com', { run: createRun({ uploads, printed, lists }), sleep: async () => {}, attempts: 3 });
+ await assert.rejects(cli.upload({ appId: 'app-9', codeFile: 'o.tsx', name: 'Overview', addToSitemap: true }), (e) => {
+ assert.match(e.message, /^pac genpage upload for 'Overview' timed out after 600 s and was stopped after it had CREATED the page as 6e0c28a2-cdbf-41ec-9186-d10fd5de6e35 /);
+ assert.match(e.message, /stalled before the page was published, and before it was added to the app's navigation if that was asked for\./);
+ assert.match(e.message, /The create was NOT run again: a second create would make a duplicate page\./);
+ assert.match(e.message, new RegExp(`add page ${GUID} to the app's navigation — in Maker, or with \`pac model genpage add --environment https://contoso\\.crm\\.dynamics\\.com --app-id app-9 --page-id ${GUID} --publish\``));
+ assert.match(e.message, new RegExp(`re-run the upload as an update with --page-id ${GUID} \\(a build: set that page's pageId to ${GUID} in the App Spec\\); or delete page ${GUID} and re-run the create\\.`));
+ assert.match(e.message, /POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS=1200000 allows a slow upload longer\./);
+ // The one way to run the create again comes only after the page has been deleted — never as the way on from a page that is still there.
+ assert.doesNotMatch(e.message, /if none appears|UNCERTAIN create|Wait a few minutes/, 'no wait-and-see: the page is known to exist');
+ assert.strictEqual((e.message.match(/re-run the create/g) || []).length, 1);
+ return true;
+ });
+ assert.strictEqual(uploads.length, 1, 'never a second create, though the ordinary budget is three attempts');
+ assert.strictEqual(lists.n, 1, 'only the snapshot before the create: the page is named by what pac printed, so nothing is listed to find it');
+ // pac's partial output is read the way a finished one is: the id must be a whole GUID, and not the start of a longer token.
+ for (const cut of ['Page ID: 6e0c28a2-cdbf-41ec-91', `Page ID: ${GUID}f`, 'Page ID: ', '']) {
+ const lists2 = { n: 0 };
+ const unsure = makeGenpageCli('https://x', { run: createRun({ uploads: [], printed: cut, lists: lists2 }), sleep: async () => {}, attempts: 3 });
+ await assert.rejects(unsure.upload({ appId: 'a', codeFile: 'o.tsx', name: 'Overview' }), /an UNCERTAIN create: no new page is visible/, JSON.stringify(cut));
+ assert.strictEqual(lists2.n, 2, `${JSON.stringify(cut)}: no usable id, so the environment is listed to look for the page`);
+ }
+ // A page id printed by a create that FAILED is the same: pac prints it once the page is written, so the page exists — even when the environment's listing does not show it yet — and the
+ // create is not run again. (A failure with no usable id is an ordinary uncertain create: the next test.)
+ const failedLists = { n: 0 };
+ const failedUploads = [];
+ const failed = makeGenpageCli('https://x', { run: async (args) => {
+ if (args[2] === 'list') { failedLists.n += 1; return { status: 0, stdout: LIST_EMPTY, stderr: '' }; }
+ failedUploads.push(args);
+ return { status: 1, stdout: `Page ID: ${GUID}`, stderr: 'boom' };
+ }, sleep: async () => {}, attempts: 3 });
+ await assert.rejects(failed.upload({ appId: 'a', codeFile: 'o.tsx', name: 'Overview' }), /failed after it had CREATED the page as 6e0c28a2-cdbf-41ec-9186-d10fd5de6e35/);
+ assert.strictEqual(failedUploads.length, 1, 'one create, though the ordinary budget is three attempts');
+ assert.strictEqual(failedLists.n, 1, 'only the snapshot before the create: the page is named by what pac printed');
+});
+
+test('a CREATE that times out after pac printed the Page ID is reported as that page even when the environment cannot be listed', async () => {
+ const uploads = [];
+ const cli = makeGenpageCli('https://x', { run: createRun({ uploads, listFails: true, printed: `Page ID: ${GUID}` }), sleep: async () => {}, attempts: 3 });
+ await assert.rejects(cli.upload({ appId: 'a', codeFile: 'o.tsx', name: 'Overview' }), /after it had CREATED the page as 6e0c28a2-cdbf-41ec-9186-d10fd5de6e35/);
+ assert.strictEqual(uploads.length, 1);
+});
+
+// A create that FAILS (exits non-zero) after pac printed `Page ID` is in the same state as one that stalled after it: pac has written the page, and the publish — or the placement — did not
+// finish. So it is reported as that page and never sent again, whatever the environment's listing shows (the page need not be in it yet). And the page is then not in the app's navigation,
+// so "re-run the upload as an update with --page-id" — what 2.13.0 said for such a create — is refused by genpage-upload.js ("not in the app's navigation", no base marker), and the build
+// cannot bind it. The way on is the one a stalled create gets: place the page, or delete it.
+test('a CREATE that FAILS after pac printed the Page ID is reported as created as that page and never sent again, whatever the listing shows — told to place it or delete it', async () => {
+ const printed = `Connected as [email protected]\r\nPage ID: ${GUID}\r\n`;
+ for (const [what, listing] of [
+ ['the listing does not show the page yet', () => LIST_EMPTY],
+ ['the listing shows the page', () => listText([{ pageId: GUID, name: 'Overview' }])],
+ ['the listing cannot be read', null],
+ ]) {
+ const lists = { n: 0 };
+ const uploads = [];
+ const run = async (args) => {
+ if (args[2] === 'list') {
+ lists.n += 1;
+ if (lists.n > 1 && !listing) return { status: 1, stdout: '', stderr: 'list failed' };
+ return { status: 0, stdout: lists.n === 1 || !listing ? LIST_EMPTY : listing(), stderr: '' };
+ }
+ uploads.push(args);
+ return { status: 1, stdout: printed, stderr: 'Error: the page could not be published' };
+ };
+ const cli = makeGenpageCli('https://contoso.crm.dynamics.com', { run, sleep: async () => {}, attempts: 3, request: createdPage() });
+ await assert.rejects(cli.upload({ appId: 'app-9', codeFile: 'o.tsx', name: 'Overview' }), (e) => {
+ assert.match(e.message, /^pac genpage upload for 'Overview' failed after it had CREATED the page as 6e0c28a2-cdbf-41ec-9186-d10fd5de6e35 \(pac prints the Page ID once the page is written\) — /, what);
+ assert.match(e.message, /it stopped before the page was published, or before it was added to the app's navigation if that was asked for \(Error: the page could not be published\)\./, `${what}: what pac said`);
+ assert.match(e.message, /The create was NOT run again: a second create would make a duplicate page\./, what);
+ assert.match(e.message, new RegExp(`To finish it, add page ${GUID} to the app's navigation — in Maker, or with \`pac model genpage add --environment https://contoso\\.crm\\.dynamics\\.com --app-id app-9 --page-id ${GUID} --publish\``), `${what}: how to place it`);
+ assert.match(e.message, new RegExp(`and then re-run the upload as an update with --page-id ${GUID} \\(a build: set that page's pageId to ${GUID} in the App Spec\\); or delete page ${GUID} and re-run the create\\.$`), `${what}: update only after it is placed`);
+ assert.doesNotMatch(e.message, /timed out|POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS|ambiguous ownership|If it is yours, re-run the upload as an update/, `${what}: it did not stall, and names no candidate`);
+ assert.strictEqual(e.transient, false, `${what}: nothing re-runs it`);
+ return true;
+ }, what);
+ assert.strictEqual(uploads.length, 1, `${what}: the create is not run again, though the ordinary budget is three attempts`);
+ assert.strictEqual(lists.n, 1, `${what}: only the snapshot before the create — the page is named by what pac printed`);
+ }
+});
+
+// With no usable id printed the page can only be found by the listing, and what it shows decides what is said. The same advice applies to a candidate: place it, or delete it.
+test('a CREATE that FAILS with no Page ID printed and leaves a candidate behind is told to place the page or delete it, never to update it, which would be refused', async () => {
+ for (const [what, stdout] of [['nothing printed', 'No page id returned'], ['a page id cut off mid-token', 'Page ID: 6e0c28a2-cdbf-41ec-91']]) {
+ const lists = { n: 0 };
+ const uploads = [];
+ const run = async (args) => {
+ if (args[2] === 'list') { lists.n += 1; return { status: 0, stdout: lists.n === 1 ? LIST_EMPTY : listText([{ pageId: GUID, name: 'Overview' }]), stderr: '' }; }
+ uploads.push(args);
+ return { status: 1, stdout, stderr: 'Error: the page could not be published' };
+ };
+ const cli = makeGenpageCli('https://contoso.crm.dynamics.com', { run, sleep: async () => {}, attempts: 3, request: createdPage() });
+ await assert.rejects(cli.upload({ appId: 'app-9', codeFile: 'o.tsx', name: 'Overview' }), (e) => {
+ assert.match(e.message, /had an uncertain create \(ambiguous ownership\)/, what);
+ assert.doesNotMatch(e.message, /timed out|CREATED the page as/, `${what}: it did not stall, and no id was printed`);
+ assert.ok(e.message.includes(`${GUID}: stored name "Overview"`), what);
+ assert.match(e.message, new RegExp(`If one is yours, add page ${GUID} to the app's navigation — in Maker, or with \`pac model genpage add --environment https://contoso\\.crm\\.dynamics\\.com --app-id app-9 --page-id ${GUID} --publish\``), `${what}: how to place it`);
+ assert.match(e.message, new RegExp(`and then re-run the upload as an update with --page-id ${GUID} \\(a build: set that page's pageId to ${GUID} in the App Spec\\); or delete page ${GUID} and re-run the create; otherwise leave them and re-run the create\\.`), `${what}: update only after it is placed`);
+ assert.doesNotMatch(e.message, /If it is yours, re-run the upload as an update/, `${what}: the advice that is refused is gone`);
+ assert.strictEqual(e.transient, false, `${what}: nothing re-runs it`);
+ return true;
+ }, what);
+ assert.strictEqual(uploads.length, 1, `${what}: the create is not run again`);
+ }
+});
+
+test('a CREATE that times out while the environment cannot be listed refuses to go on, as every uncertain create does — and says how to find out whether it made a page', async () => {
+ const uploads = [];
+ const cli = makeGenpageCli('https://x', { run: createRun({ uploads, listFails: true }), sleep: async () => {}, attempts: 3 });
+ await assert.rejects(cli.upload({ appId: 'a', codeFile: 'o.tsx', name: 'Overview' }), (e) => {
+ assert.match(e.message, /^pac genpage upload for 'Overview' timed out after 600 s and was stopped, and had an uncertain result and env enumeration failed — refusing to retry \(would risk a duplicate\): pac genpage list \(env-wide\) failed after 3 attempt\(s\): list failed\. /);
+ // Nothing is known about what the create made, so the way on is to look: wait, list, and place a page that is there — before anything is created again.
+ assert.match(e.message, /The create may have made a page\. Wait a few minutes, then run `pac model genpage list --environment https:\/\/x --include-unpublished`: if a new page with this name appears and it is yours, /);
+ assert.match(e.message, ADD_PAGE('<its id>'));
+ assert.match(e.message, /; or delete page <its id> and re-run the create; if none appears, re-run the create\. POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS=1200000 allows a slow upload longer\.$/);
+ assert.strictEqual(e.transient, false);
+ return true;
+ });
+ assert.strictEqual(uploads.length, 1);
+ // A create that FAILED (did not stall) and cannot be checked says the same, without the words about a stall or a longer budget.
+ const failedUploads = [];
+ let lists = 0;
+ const failed = makeGenpageCli('https://x', { run: async (args) => {
+ if (args[2] === 'list') { lists += 1; return lists === 1 ? { status: 0, stdout: LIST_EMPTY, stderr: '' } : { status: 1, stdout: '', stderr: 'list failed' }; }
+ failedUploads.push(args);
+ return { status: 1, stdout: '', stderr: 'Error: the upload failed' };
+ }, sleep: async () => {}, attempts: 3 });
+ await assert.rejects(failed.upload({ appId: 'a', codeFile: 'o.tsx', name: 'Overview' }), (e) => {
+ assert.match(e.message, /^pac genpage upload for 'Overview' had an uncertain result and env enumeration failed — refusing to retry/);
+ assert.doesNotMatch(e.message, /timed out|POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS/);
+ assert.match(e.message, /The create may have made a page\. Wait a few minutes, then run `pac model genpage list/);
+ assert.strictEqual(e.transient, false);
+ return true;
+ });
+ assert.strictEqual(failedUploads.length, 1);
+});
+
+test('a listing that times out BEFORE a create stops it before anything is created', async () => {
+ const uploads = [];
+ const run = async (args) => { if (args[2] === 'list') return timedOutRun(); uploads.push(args); return { status: 0, stdout: `Page ID: ${GUID}`, stderr: '' }; };
+ await assert.rejects(makeGenpageCli('https://x', { run, sleep: async () => {} }).upload({ appId: 'a', codeFile: 'o.tsx', name: 'Overview' }),
+ /cannot snapshot the environment before create[\s\S]*did not finish within 180 s[\s\S]*refusing to create/);
+ assert.deepStrictEqual(uploads, [], 'no create was issued');
+});
diff --git a/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js b/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js
index a77a538aa..2d28e6660 100644
--- a/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js
+++ b/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js
@@ -270,22 +270,233 @@ test('the manifest step halts on exit 2 instead of carrying on over a stale pack
assert.doesNotMatch(step, /do\s+not\s+block\s+the\s+workflow/i, 'no non-zero exit is waved through');
});
-test('page generation rejects Griffel borderWidth shorthand before deploy', () => {
- const rules = readDoc(path.join(PLUGIN, 'references', 'rules.md'));
- const builder = readDoc(path.join(PLUGIN, 'agents', 'genpage-page-builder.md'));
- const skill = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md'));
- const editFlow = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'edit-flow.md'));
- assert.match(rules, /borderWidth/i, 'rules must name the runtime-only Griffel failure');
- assert.match(builder, /borderWidth/i, 'page-builder must scan its output for the shorthand');
- assert.match(skill, /borderWidth/i, 'inline page generation must run the same scan');
- assert.match(editFlow, /borderWidth/i, 'edited pages must run the same scan before upload');
- const documentedPattern = `['"]?borderWidth['"]?\\s*:`;
- for (const [name, text] of [['rules', rules], ['page-builder', builder], ['create flow', skill], ['edit flow', editFlow]]) {
- assert.ok(text.includes(documentedPattern), `${name} must carry the complete Griffel key regex`);
+// The Griffel shorthand gate (AB#6691124). Griffel's runtime drops ten CSS shorthands from a `makeStyles` object and the page then deploys without them, so every instruction
+// that writes, edits or accepts a page names them, and every orchestrator runs scripts/check-griffel-styles.js on the page before it transpiles or uploads it. Nothing executes
+// those instructions, so — as with the Connectors line above — a document that drops the rule or the command is invisible until a page ships without its border. The rule is ONE
+// text, stated in the same words in every document (whitespace aside: they wrap their lines differently), so a correction to one cannot leave another stating the old rule.
+const { UNSUPPORTED_GRIFFEL_SHORTHANDS } = require('../lib/griffel-styles.js');
+
+const squash = (text) => text.replace(/\s+/g, ' ');
+const GRIFFEL_RULE = [
+ 'Griffel does not support ten CSS shorthands, and `makeStyles` drops them at runtime: the page type-checks, transpiles and deploys, then renders without the border, color or reset.',
+ 'They are `all`, `borderColor`, `borderStyle`, `borderWidth`, `borderBlock`, `borderBlockStart`, `borderBlockEnd`, `borderInline`, `borderInlineStart` and `borderInlineEnd`.',
+ 'Write longhands instead: `borderColor`, `borderStyle` and `borderWidth` become one longhand per side, `border` + `Top`, `Right`, `Bottom` or `Left` + `Color`, `Style` or `Width`',
+ '(`borderWidth` → `borderTopWidth`, `borderRightWidth`, `borderBottomWidth`, `borderLeftWidth`);',
+ '`borderBlock`, `borderInline` and their `Start` and `End` forms become the `Width`, `Style` and `Color` longhands of the sides they name',
+ '(`borderBlockStart` → `borderBlockStartWidth`, `borderBlockStartStyle`, `borderBlockStartColor`; `borderBlock` → those and the three `borderBlockEnd…` ones);',
+ '`all` has no longhands, so set the properties you need one by one.',
+ 'Every other shorthand (`padding`, `margin`, `border`, `borderRadius`, `gap`, `outline`) is supported, and an inline `style={{ … }}` is not Griffel at all.',
+].join(' ');
+// What the documents that RUN the checker add: its output, its exit code, and that nothing is transpiled or uploaded before it exits 0.
+const GRIFFEL_GATE = [
+ '`check-griffel-styles.js` prints each problem it finds — a key Griffel drops in a `makeStyles` call, at any depth, with its line, column and longhands,',
+ 'or a call or a style object it cannot read, with what to change — and exits 3 while any is left:',
+ 'fix what it reports and run it again, and do not transpile or upload the page until it exits 0.',
+ 'It reads the style objects written inline in the call, `makeStyles({ … })`, so write them there:',
+ 'one passed or spread in from elsewhere (`makeStyles(styles)`, `...base`) is reported, because the check cannot see its keys,',
+ 'and so is a key computed from an expression (`[key]: …`), whose name it cannot see (a template that starts with `--`, `&`, `:` or `@` is read);',
+ 'Fluent\'s `...shorthands.*(…)` and `...typographyStyles.*` may be spread as they are.',
+].join(' ');
+const OLD_BORDER_WIDTH_GREP = `['"]?borderWidth['"]?\\s*:`;
+
+function griffelDocs() {
+ return {
+ rules: readDoc(path.join(PLUGIN, 'references', 'rules.md')),
+ 'page-builder': readDoc(path.join(PLUGIN, 'agents', 'genpage-page-builder.md')),
+ 'create flow': readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md')),
+ 'edit flow': readDoc(path.join(PLUGIN, 'skills', 'genpage', 'edit-flow.md')),
+ 'app-builder': readDoc(path.join(PLUGIN, 'skills', 'app-builder', 'SKILL.md')),
+ };
+}
+
+test('every instruction that writes a page states the Griffel rule in the same words, with all ten properties and their longhands', () => {
+ for (const [name, text] of Object.entries(griffelDocs())) {
+ assert.ok(squash(text).includes(GRIFFEL_RULE), `${name} must state the Griffel rule in the shared words`);
+ }
+ // The shared text is the checker's own set: a property the checker gains has to reach the instructions, and one it loses must leave them.
+ for (const property of UNSUPPORTED_GRIFFEL_SHORTHANDS.keys()) assert.ok(GRIFFEL_RULE.includes(`\`${property}\``), `the rule names ${property}`);
+ assert.equal(GRIFFEL_RULE.match(/ They are (.*?)\. /)[1].split(/, | and /).length, UNSUPPORTED_GRIFFEL_SHORTHANDS.size, 'and names no other');
+ for (const property of ['borderWidth', 'borderBlockStart']) {
+ for (const longhand of UNSUPPORTED_GRIFFEL_SHORTHANDS.get(property)) assert.ok(GRIFFEL_RULE.includes(`\`${longhand}\``), `the rule spells out ${longhand}`);
}
- const regex = /['"]?borderWidth['"]?\s*:/;
- for (const source of ['borderWidth: 0', 'borderWidth : 0', '"borderWidth": 0', "'borderWidth' : 0"]) {
- assert.match(source, regex, `guard must detect ${source}`);
+});
+
+test('the grep for borderWidth alone — one of the ten, and blind to a string or a comment — is gone from every instruction', () => {
+ for (const file of mdFiles()) assert.ok(!readDoc(file).includes(OLD_BORDER_WIDTH_GREP), `${rel(file)} still greps for borderWidth alone`);
+});
+
+test('every orchestrator runs the Griffel checker as a gate before it transpiles or uploads a page', () => {
+ const docs = griffelDocs();
+ const command = (target) => `node "\${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file '${target}'`;
+ const gated = (name, text) => assert.ok(squash(text).includes(GRIFFEL_GATE), `${name} must state the gate: exit 3 while a problem is left, nothing uploaded until exit 0`);
+
+ // /genpage, one page: step 9 of Phase 5b, ahead of the completeness gate (step 10) and of Phase 6.
+ const skill = docs['create flow'];
+ const fastPath = skill.split(/#### 5b\. Single-page fast path/)[1].split(/#### 5c\. Multi-page/)[0];
+ assert.ok(fastPath.includes(command('<working-dir>/<filename>.tsx')), 'single-page generation runs the checker on the page it wrote');
+ gated('single-page generation', fastPath);
+ assert.ok(fastPath.indexOf('check-griffel-styles.js') < fastPath.indexOf('genpage-worker-output.js" --file'), 'the Griffel check comes before the completeness gate');
+
+ // /genpage, several pages: the workers cannot run it, so the orchestrator does, per page, before Phase 6.
+ const multiPage = skill.split(/#### 5c\. Multi-page/)[1].split(/### Phase 6: Deploy/)[0];
+ assert.ok(multiPage.includes(command('<working-dir>/<filename>.tsx')), 'multi-page generation runs the checker on every page');
+ assert.match(squash(multiPage), /workers have no shell, so they cannot run the Griffel check themselves/);
+ assert.match(squash(multiPage), /A page that has not exited 0 is not deployed\./);
+ assert.ok(multiPage.lastIndexOf('genpage-worker-output.js') < multiPage.indexOf('check-griffel-styles.js'), 'the Griffel check follows the completeness gate');
+
+ // /genpage, an edit: before Edit Phase 6.
+ const edit = docs['edit flow'];
+ assert.ok(edit.includes(command('<working-dir>/<page-id>/page.tsx')), 'an edited page is checked');
+ gated('the edit flow', edit);
+ assert.ok(edit.indexOf('check-griffel-styles.js') < edit.indexOf('## Edit Phase 6: Deploy Updated Page'), 'the edited page is checked before it is uploaded');
+
+ // /app-builder: its pages come from the same workers, and are checked before promote-intent-pages.js commits them.
+ const appBuilder = docs['app-builder'];
+ assert.ok(appBuilder.includes('node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file <working-dir>/<file>'), 'app-builder checks every generated page');
+ gated('app-builder', appBuilder);
+ assert.ok(appBuilder.indexOf('check-griffel-styles.js') < appBuilder.indexOf('promote-intent-pages.js" \\'), 'the pages are checked before they are promoted');
+
+ // The reference the workers read spells the same command and gate out.
+ assert.ok(docs.rules.includes(command('<page.tsx>')), 'rules.md names the checker');
+ gated('rules.md', docs.rules);
+});
+
+// The page-builder worker has Read, Write, Edit and Grep — no shell — so it cannot run a Node script, and an instruction to would be one it can only skip or fake. It gets the rule
+// and a Grep to find the places to look; the orchestrators above run the checker on what it writes.
+test('the page-builder, which has no shell, is given the Griffel rule and a Grep self-review rather than a command it cannot run', () => {
+ const builder = griffelDocs()['page-builder'];
+ const tools = /^---\n([\s\S]*?)\n---/.exec(builder)[1];
+ assert.doesNotMatch(tools, /^\s*-\s*(Bash|execute|shell|powershell)\s*$/im, 'the premise: this agent has no shell tool — if it gains one, make it run the checker');
+ const step = squash(builder.split('## Step 2.6')[1].split('## Step 3')[0]);
+ assert.doesNotMatch(step, /node\s+"\$\{PLUGIN_ROOT\}/, 'no command for a worker to run');
+ assert.match(step, /You have no shell, so you cannot run the checker: after you return, the orchestrator runs `\$\{PLUGIN_ROOT\}\/scripts\/check-griffel-styles\.js` on your file and fixes anything it reports before the page is deployed\./);
+ assert.match(step, /so write every one that way\./, 'the worker is told to write the objects inline, the one form the checker reads');
+ assert.match(step, /Do not return a file that still has one in a `makeStyles` object\./);
+
+ // The Grep is the documented regex: it must list every place a flagged key is written and nothing that merely resembles one.
+ const documented = /with the regex `([^`]+)`/.exec(step)[1];
+ const grep = new RegExp(documented);
+ for (const property of UNSUPPORTED_GRIFFEL_SHORTHANDS.keys()) assert.ok(documented.includes(property), `the regex lists ${property}`);
+ const keyed = ["borderWidth: 0", " borderWidth : 0", "{ all: 'unset' }", '"borderColor": 1', "'borderStyle' : 'solid'", "['borderBlock']: x", '{borderInline: 1}',
+ ',borderInlineStart: 1', 'root: { borderBlockEnd: `1px` }', '\tborderBlockStart:'];
+ for (const line of keyed) assert.match(line, grep, `the Grep must list ${JSON.stringify(line)}`);
+ const lookalikes = ['overall: 1', 'borderTopWidth: 1', 'borderWidths: 1', 'padding: 1', "border: '1px solid red'", 'borderRadius: 1', 'borderBlockStartWidth: 1', 'allow: true', "content: 'borderWidth'"];
+ for (const line of lookalikes) assert.doesNotMatch(line, grep, `the Grep must not list ${JSON.stringify(line)}`);
+});
+
+// The orchestrators' gate above is an instruction, and an instruction can be skipped — so the paths that upload a page AFTER a fix or a hand edit, which had no check at all, name the
+// checker as well, and say that the code holds the same line: genpage-upload.js refuses the page, and so does the build (scripts/tests/genpage-upload.test.js and
+// sdk-build-pages-deploy.test.js run those).
+test('the paths that re-upload a page after a browser-verify fix or a hand edit run the Griffel checker too, and say the upload and the build enforce it', () => {
+ const checker = (target) => `node "\${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file ${target}`;
+ // /genpage §7.5: the fix is new code, checked before the update command.
+ const fix = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'verify-flow.md')).split('## 7.5 Fix and Re-deploy')[1];
+ assert.ok(fix.includes(checker("'<working-dir>/<file>.tsx'")), 'the fixed page is checked');
+ assert.ok(fix.indexOf('check-griffel-styles.js') < fix.indexOf('node "${PLUGIN_ROOT}/scripts/genpage-upload.js" `'), 'the check comes before the update command');
+ assert.match(squash(fix), /Do not upload until it exits 0: fix what it reports \(each key's line, column and longhands\) and run it again\./);
+ assert.match(squash(fix), /`genpage-upload\.js` makes the same check and refuses a page that adds a key the deployed page did not already have, or gives one it had another value \(`griffel-shorthand`\)/);
+ assert.match(squash(fix), /`references\/rules\.md` Common Pitfalls 5/, 'and it points at the rule rather than restating it');
+
+ // /app-builder, editing a deployed app: a page edited by hand is checked before the rebuild, and the build's own halt is named.
+ const appBuilder = readDoc(path.join(PLUGIN, 'skills', 'app-builder', 'SKILL.md'));
+ const editing = appBuilder.split('## Editing a deployed app')[1].split('## What the builder does')[0];
+ const editStep = editing.split(/\n2\. /)[1].split(/\n3\. /)[0];
+ assert.ok(editStep.includes(checker('<page.tsx>')), 'a hand-edited page is checked');
+ assert.match(squash(editStep), /before you rebuild \(the rule and the ten shorthands are in Phase 1\.5, step 5\)/);
+ assert.match(squash(editStep), /halts as `pages-griffel-shorthand` — naming the page, each key's line and column, and the longhands/);
+ assert.match(squash(appBuilder), /- `pages-griffel-shorthand` — a page's `makeStyles` writes a CSS shorthand Griffel drops at runtime/, 'the halt is in the list a user is told to follow');
+ assert.match(readDoc(path.join(PLUGIN, 'references', 'app-spec-schema.md')), /- `pages-griffel-shorthand` — a page that this run uploads has a `makeStyles` key Griffel drops at runtime/);
+
+ // /genpage Phase 6: the upload script's refusal is described, with its code.
+ const skill = squash(readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md')));
+ assert.match(skill, /`genpage-upload\.js` reads the code file and refuses a page whose `makeStyles` writes one of the ten Griffel shorthands \(Phase 5b step 9\): a create outright, before it lists, reads or writes anything, and an update for any key the deployed page did not already have \(below\)\. The result is `"code":"griffel-shorthand"`/);
+ assert.match(skill, /no flag skips it, and `--overwrite-deployed` does not/);
+ // The plugin guide says the same, and that the check is made in code.
+ const agents = squash(readDoc(path.join(PLUGIN, 'AGENTS.md')));
+ assert.match(agents, /the code \*\*enforces\*\* it where pages are uploaded/);
+ assert.match(agents, /`genpage-upload\.js` reads the code file first and refuses a create with `code: "griffel-shorthand"`/);
+ assert.match(agents, /the build's pages phase halts as `pages-griffel-shorthand` in its pre-write scan/);
+});
+
+// A page deployed by an earlier release can already hold a key Griffel drops (its only guard was a grep for `borderWidth`), and it renders without it today. Sending the same bytes again
+// ships nothing new, and refusing them stops a rebuild over a page nobody touched — whose way through, the longhands, CHANGES how the page renders. So the gates hold a page to what a run
+// would ADD, and say what each way out does. These are instructions nothing executes, so a document that drops the distinction — or the advice that goes with it — is invisible until
+// a maker is told to change how a page looks. scripts/tests/sdk-build-pages-deploy.test.js and genpage-upload.test.js run the gates themselves.
+test('the docs say the gates hold a page to what a run would add, and say what each way out does to the page', () => {
+ const read = (...parts) => squash(readDoc(path.join(PLUGIN, ...parts)));
+ const agents = read('AGENTS.md');
+ // The plugin guide: the build's four standings and why the unrecorded one fails open, and the upload script's comparison.
+ const holds = agents.split('**What the gates hold a page to.**')[1].split('- **Who runs it.**')[0];
+ assert.match(holds, /So every refusal and warning says both: \*deleting a key changes nothing on screen; writing the longhands makes the style start to render\*\./);
+ assert.match(holds, /A page that does not exist yet \(`keyToId` has no id for it: it is \*created\*\) and a page that exists but whose source no longer hashes to the `__contentSha` that `last-applied\.json` recorded for it at the last apply \(\*changed\*\) are held to the check/);
+ assert.match(holds, /A page whose source hashes to that record \(\*unchanged\*\), or that has no record \(\*unrecorded\*\), is sent as it is, and the build warns \(`opts\.warn`\) with file:line:column and both remedies\./);
+ assert.match(holds, /returned only for this app \*\*in this environment\*\* \(`readBaseline`/);
+ assert.match(holds, /\*Unrecorded\* [^.]*fails \*\*open\*\* on purpose/);
+ assert.match(holds, /a page that does not exist is always held, record or not/);
+ assert.match(holds, /\*\*`genpage-upload\.js`\*\* has the deployed page in hand/);
+ assert.match(holds, /`griffelProblemsNotIn`: the same key set to the same value in the same place \(`within`: its slot, selectors and at-rules\), or failing that the same key and value anywhere that nothing else has claimed/);
+ assert.match(holds, /A key given \*\*another value\*\* is new too: Griffel drops the new value as it dropped the old one, so the page would show none of the change the maker meant/);
+ assert.match(holds, /the hash recorded is of the source the pages phase \*read and checked\* \(`created\.pageSourceShas`\), not of the file when the baseline is written as the build ends/);
+ assert.match(holds, /What is sent is what was checked: every page, a navigation source or not, goes to pac from a staging copy of the bytes the scan read \(`writeStagingFile`\), never from its own file, so a save made after the check does not ship until a build has checked it\./);
+ assert.doesNotMatch(holds, /sent from its own file|ships unchecked/, 'no page is uploaded from its canonical file any more, so the guide must not describe the gap that closed');
+ assert.match(holds, /`--overwrite-deployed` is no way past that/);
+ assert.match(holds, /A call the checker cannot read\*\* is not CSS Griffel drops, and is not said to be/);
+ assert.match(holds, /quotes a path that has white space/);
+ // The skills and references that tell a user or an agent what to do.
+ const editFlow = read('skills', 'genpage', 'edit-flow.md');
+ assert.match(editFlow, /A page that was deployed before this check existed can already hold such a key, so the checker may report one that your edit did not add\./);
+ assert.match(editFlow, /\*\*delete the key\*\* — nothing changes on screen, so it is the edit that preserves the page — or \*\*write the longhands\*\*, which makes the style start to render, so the page changes\. Delete it unless the user asked for that change/);
+ const skill = read('skills', 'genpage', 'SKILL.md');
+ assert.match(skill, /An update is held to what it \*\*adds\*\*\./);
+ assert.match(skill, /\*\*delete the key\*\* \(nothing changes on screen\) or \*\*write the longhands\*\* \(the style starts to render, so the page changes\)\. Only a key the deployed page did not have — or one it had, given another value, because Griffel drops the new value just as it dropped the old, so the page would show none of the change — stops the upload\./);
+ assert.match(read('skills', 'genpage', 'verify-flow.md'), /delete it to keep the page looking as it does, or write the longhands to make the style start to render/);
+ const appBuilder = read('skills', 'app-builder', 'SKILL.md');
+ assert.match(appBuilder, /The build runs the same check on every page it uploads that is new or that you changed since the last successful apply of this app, and halts as `pages-griffel-shorthand`/);
+ assert.match(appBuilder, /"Changed" is measured against the source that apply recorded for the page in `\.maker-workspace\/last-applied\.json` \(a successful full or changed-only apply, or a download, writes it; a failed or partial build records nothing\)\./);
+ assert.match(appBuilder, /A page you did not touch is sent again as it is, and a key it already has only draws a warning — and so does a page you changed in a workspace that holds no record of it/);
+ assert.match(appBuilder, /Deleting a key keeps the page looking as it does; writing the longhands makes the style start to render\. The same halt reports a `makeStyles` call the check cannot read for certain as that — not as CSS Griffel drops — and says what to change in the code\./);
+ const schema = read('references', 'app-spec-schema.md');
+ assert.match(schema, /is \*\*new\*\* \(no deployed page\) or \*\*changed\*\* \(its source no longer hashes to the `__contentSha` that `last-applied\.json` recorded for it at the last apply to this app in this environment — the record a successful full or changed-only apply, or a download, writes; for a page it is the hash of the source the build read and sent, and a failed or partial build records nothing\)/);
+ assert.match(schema, /deleting a key changes nothing on screen \(Griffel never applied it\), writing the longhands makes the style start to render/);
+ assert.match(schema, /is sent as it is and the build \*\*warns\*\* with the same detail instead: it ships nothing new\./);
+});
+
+// A pac upload that stalls is stopped, and what the script — and so the agent — does next depends on what the stalled call can have done: pac writes the page, records the prompt
+// and the agent message, prints its Page ID, then publishes. The first version of these instructions said an UPDATE is simply sent again ("a second send cannot create anything"),
+// which is false — a call stalled in the publish has already written everything, so a re-send records the prompt twice and overwrites whatever was saved meanwhile — and its
+// advice for a create ("update it") is refused when the stalled create left the page out of the app's navigation. scripts/tests/genpage-cli.test.js runs what the script does.
+test('the docs say a stalled upload is never sent again by the script, what to check after an update that timed out, and what finishes a create that stalled', () => {
+ const skill = squash(readDoc(path.join(PLUGIN, 'skills', 'genpage', 'SKILL.md')));
+ assert.match(skill, /A listing or a download that times out is retried once\. An \*\*upload is never sent again by the script\*\*/);
+ assert.match(skill, /sending it again can record the prompt a second time or overwrite a change someone saved in the meantime\. Follow the message the script prints; do not simply re-run the command\./);
+ assert.match(skill, /\*\*An update that timed out, or failed,\*\* "MAY HAVE LANDED" — pac can fail while publishing, after it wrote the page, so neither is sent again by the script\. \(A failure pac reports for its own arguments or files is an ordinary error: fix what it names and re-run\.\) Compare the deployed page with your file first: `node "\$\{PLUGIN_ROOT\}\/scripts\/genpage-base\.js" check --env '<org-url>' --app-id '<app-id>' --page-id '<page-id>' --file '<working-dir>\/<file>\.tsx'`/);
+ assert.match(skill, /`"contentSame": true` means the update landed: do not upload it again/);
+ assert.match(skill, /`"deployed": "unchanged"` means it did not land, and re-running the update is safe\./);
+ assert.match(skill, /\*\*A create that timed out\*\* is an \*uncertain\* create, and is never run again — by the script, or by you\./);
+ assert.match(skill, /If the message says the page was \*\*created as `<page-id>`\*\*, it exists but was stopped before it was published/);
+ assert.match(skill, /Add it to the app's navigation \(in Maker, or `pac model genpage add --environment '<org-url>' --app-id '<app-id>' --page-id '<page-id>' --publish`\)/);
+ assert.match(skill, /An update of a page that is not in the app's navigation is refused, and a second create makes a duplicate — so neither is the way on\. A create that \*\*failed\*\* \(not timed out\) after pac had printed a `Page ID` is in the same state: its error says the page was \*\*created as `<page-id>`\*\* and that the create was not run again, with the same two ways on rather than "re-run it as an update"\. The build never re-sends such a create by itself either: every one of these errors is marked as one that is not to be retried\./);
+ assert.match(skill, /The same goes for a message that says the environment could not be listed after the create, so nothing is known about what it made\./);
+ const agents = squash(readDoc(path.join(PLUGIN, 'AGENTS.md')));
+ assert.match(agents, /A timed-out list or download is read-only, so it is retried once\. A timed-out \*\*update\*\* is \*\*not\*\* retried, though it names a page that exists/);
+ assert.match(agents, /It is reported as one that \*may have landed\*, and what it sends you to look at depends on the caller \(`upload\(\)`'s `caller`\): the upload script's message names `genpage-base\.js check`/);
+ // The build keeps no base marker and sends every page from a staging copy it deletes, so the script's advice fails there: it gets its own, and its error is never retried by the build.
+ assert.match(agents, /The \*\*build\*\* keeps no base marker, so that check could only answer "unknown", and every page's code file is a staging copy its cleanup deletes, so the command would fail on a missing file: the build's message tells you to read the deployed page with `pac model genpage download`/);
+ // A FAILED update is in the same state as a stalled one (pac can fail in the publish), so it is not retried either; only a refusal of pac's own arguments is ordinary.
+ assert.match(agents, /An \*\*update\*\* that \*\*fails\*\* — a non-zero exit, or an exit 0 with no `Page ID` — is handled the same way, for the same reason \(pac can fail in the publish, after everything else is written\): it is \*\*not\*\* retried/);
+ assert.match(agents, /Only a non-zero exit that pac reports for its own arguments or input files \(`isDeterministic`\) is an ordinary error, because pac checks those before it sends anything — and only when pac printed no `Page ID`:/);
+ assert.match(agents, /and to open the `page\.tsx` in the folder named for the id, which pac writes in its own letter case\) and then run the build again, which sends the page once more to the same id — nothing new is created, but if the stalled send did land, the page's history now records its prompt a second time/);
+ assert.match(agents, /The error carries `transient: false`, so the build's own retry of transient halts never re-sends it\./);
+ assert.match(agents, /A `Page ID` pac had already printed names the page it created, whether the call then stalled or \*\*failed\*\* \(exited non-zero\): it is reported as \*created as `<id>`, stalled \(or failed\) before publish or placement\*, the create is \*\*not\*\* sent again however the environment's listing looks/);
+ assert.match(agents, /a create that failed and left a candidate gets the same way on, not "re-run it as an update with `--page-id`"/);
+ // Every error that follows a create whose outcome is not known to be nothing is one the build's own retry cannot re-send — the page's name and pac's words are what that retry reads —
+ // and a create that failed outright and left nothing is retried, as in 2.13.0.
+ assert.match(agents, /\*\*Every error that follows a create whose outcome is not known to be nothing carries `transient: false`\*\* \(`neverRetriedError`\) — a stall, a printed Page ID, a candidate in the listing, a listing that cannot be read: the build re-runs a phase when a halt reads as transient/);
+ assert.match(agents, /A create that failed outright and left nothing in the listing, and a listing that fails \*before\* the create was sent, leave nothing to duplicate: both are still retried — by the upload \(3 sends\) and, when the error's text reads as transient, by the build — as in 2\.13\.0\./);
+ assert.doesNotMatch(agents, /Every error that follows a create that was sent|every error that follows a sent create/, 'the claim is made for the creates whose outcome is not known to be nothing, not for every create that was sent');
+ // The retired claim is in none of them, nor in the wrapper's own comments.
+ for (const [name, text] of [['the genpage skill', skill], ['AGENTS.md', agents], ['lib/genpage-cli.js', squash(fs.readFileSync(path.join(PLUGIN, 'scripts', 'lib', 'genpage-cli.js'), 'utf8'))]]) {
+ assert.doesNotMatch(text, /cannot create anything|So it is retried\.|a time out is retried once, and so is an \*\*update\*\*/i, `${name} still says a second send of an update is harmless`);
}
});
diff --git a/plugins/model-apps/scripts/tests/genpage-lexer-hardening.test.js b/plugins/model-apps/scripts/tests/genpage-lexer-hardening.test.js
index 462469347..336e3a45a 100644
--- a/plugins/model-apps/scripts/tests/genpage-lexer-hardening.test.js
+++ b/plugins/model-apps/scripts/tests/genpage-lexer-hardening.test.js
@@ -463,6 +463,11 @@ test('execution oracle: a rewrite changes only the calls JavaScript makes with a
['computed optional member', `Xrm.Navigation?.["navigateTo"]?.(${obj})`, true, true],
['computed escaped member', `Xrm.Navigation["navigate\\u0054o"](${obj})`, true, true],
['computed optional member, parenthesised argument', `Xrm.Navigation?.['navigateTo']?.((${obj}))`, true, true],
+ // After `return` an expression starts on the same line, so the parenthesised callee is the call; after a line break the statement is `return;`, and the call after it never runs.
+ // `await` is a keyword only in an async function, which the lexer cannot tell: the call is made there and left alone here, and the token is reported.
+ ['return, parenthesised callee', `function f() { return (navigateTo)(${obj}); } f();`, true, true],
+ ['return, a line break, parenthesised callee', `function f() { return\n(navigateTo)(${obj}); } f();`, false, false],
+ ['await in an async function, parenthesised callee', `async function f() { await (navigateTo)(${obj}); } f();`, true, false],
];
for (const term of ['\n', '\r', '\r\n', '\u2028', '\u2029']) {
// The key is `pageType` once the continuation is read; the value is "PAGEREF_detail", but spelled across the line
diff --git a/plugins/model-apps/scripts/tests/genpage-upload.test.js b/plugins/model-apps/scripts/tests/genpage-upload.test.js
index ad85a2a3e..591b678a7 100644
--- a/plugins/model-apps/scripts/tests/genpage-upload.test.js
+++ b/plugins/model-apps/scripts/tests/genpage-upload.test.js
@@ -21,6 +21,8 @@ const uploadMod = require('../genpage-upload.js');
const { notPlainFile } = uploadMod;
const { pageHash, writeMarker } = require('../lib/genpage-base.js');
const { buildPacInvocation, makeGenpageCli } = require('../lib/genpage-cli.js');
+// How a path appears in a command a message suggests: bare when plain, single-quoted otherwise (a Windows temp path has backslashes).
+const { commandArg } = require('../lib/cli-failure.js');
const dirs = [];
test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });
@@ -31,29 +33,33 @@ function tmp() {
}
// What a capturing download writes as page.tsx, and what a dummy `--code-file` is replaced with.
-// Legacy update tests named `c.tsx` / `p.tsx` without a base marker. An update now refuses that
-// (`no-base`) and, on success, would write a marker next to the dummy path in this directory.
-// Those tests still prove their own rule; the replacement only supplies the base they now need.
+// Legacy tests name `c.tsx` / `p.tsx` / `page.tsx` / `CODE.tsx`, which are no files. The upload reads the
+// code file once, before anything else, and sends pac a copy of those bytes, so a name that is no file now
+// stops it there: every dummy becomes a real file holding the live page. An update without a base marker is
+// refused (`no-base`), so an update's dummy also gets the marker it needs — those tests still prove their own
+// rule; the replacement only supplies the file and the base they now need.
const LIVE_PAGE = 'export default function Page() { return null; }\n';
const DUMMY_CODE = new Set(['p.tsx', 'c.tsx', 'page.tsx', 'CODE.tsx']);
function maybeBase(argv, deps) {
- if (!argv || (deps && deps.skipBase)) return argv;
+ if (!argv) return argv;
const fileIdx = argv.indexOf('--code-file');
const pageIdx = argv.indexOf('--page-id');
- if (fileIdx < 0 || pageIdx < 0) return argv;
+ if (fileIdx < 0) return argv;
const current = argv[fileIdx + 1];
if (!DUMMY_CODE.has(current)) return argv;
const file = path.join(tmp(), 'page.tsx');
fs.writeFileSync(file, LIVE_PAGE);
const appIdx = argv.indexOf('--app-id');
- writeMarker(file, {
- version: 1,
- pageId: argv[pageIdx + 1],
- appId: appIdx >= 0 ? argv[appIdx + 1] : 'app',
- deployedSha256: pageHash(LIVE_PAGE),
- localSha256: pageHash(LIVE_PAGE),
- source: 'download',
- });
+ if (pageIdx >= 0 && !(deps && deps.skipBase)) {
+ writeMarker(file, {
+ version: 1,
+ pageId: argv[pageIdx + 1],
+ appId: appIdx >= 0 ? argv[appIdx + 1] : 'app',
+ deployedSha256: pageHash(LIVE_PAGE),
+ localSha256: pageHash(LIVE_PAGE),
+ source: 'download',
+ });
+ }
const next = argv.slice();
next[fileIdx + 1] = file;
return next;
@@ -523,16 +529,22 @@ test('main forwards every option through the real wrapper to the pac invocation,
const d = tmp();
const pf = path.join(d, 'prompt.txt');
fs.writeFileSync(pf, 'the approved prompt', 'utf8');
+ const codeFile = path.join(d, 'CODE.tsx');
+ fs.writeFileSync(codeFile, LIVE_PAGE, 'utf8');
const seen = [];
// The wrapper deletes its temp dir in a `finally`, so the prompt file cannot be read after
- // upload() returns. Capture the contents DURING the invocation instead.
+ // upload() returns. Capture the contents DURING the invocation instead — the code file too, which
+ // is a copy of the checked bytes that is removed once pac has answered.
let promptOnDisk = null;
+ let codeOnDisk = null;
const factory = (env) => makeGenpageCli(env, {
run: async (args) => {
seen.push(args);
const i = args.indexOf('--prompt-file');
if (i !== -1) promptOnDisk = fs.readFileSync(args[i + 1], 'utf8');
+ const c = args.indexOf('--code-file');
+ if (c !== -1) codeOnDisk = fs.readFileSync(args[c + 1], 'utf8');
if (args.includes('list')) return { status: 0, stdout: 'Found 0 generated page(s):\n', stderr: '' };
return { status: 0, stdout: 'Page ID: 13ecbc57-a3a4-4132-b0a2-a6c6b12691e8', stderr: '' };
},
@@ -541,7 +553,7 @@ test('main forwards every option through the real wrapper to the pac invocation,
const r = await new Promise((resolve) => {
main([
- '--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'APPID-1', '--code-file', 'CODE.tsx',
+ '--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'APPID-1', '--code-file', codeFile,
'--name', 'NamedPage', '--data-sources', 'account,contact',
'--model', 'MODEL-9', '--connectors', 'CONN.json', '--actions', 'ACT.json',
'--prompt-file', pf, '--agent-message', 'msg', '--add-to-sitemap',
@@ -556,7 +568,11 @@ test('main forwards every option through the real wrapper to the pac invocation,
// EXACT pairs. A dropped flag or a swapped value fails here, which is what the old tests missed.
assert.strictEqual(valueOf('--environment'), 'https://contoso.crm.dynamics.com/');
assert.strictEqual(valueOf('--app-id'), 'APPID-1');
- assert.strictEqual(valueOf('--code-file'), 'CODE.tsx');
+ // The code file pac reads is a copy of the checked bytes, under the file's own name, not the file itself.
+ assert.notStrictEqual(valueOf('--code-file'), codeFile);
+ assert.strictEqual(path.basename(valueOf('--code-file')), 'CODE.tsx');
+ assert.strictEqual(codeOnDisk, LIVE_PAGE);
+ assert.ok(!fs.existsSync(valueOf('--code-file')), 'the copy is gone once the upload has answered');
assert.strictEqual(valueOf('--name'), 'NamedPage');
assert.strictEqual(valueOf('--data-sources'), 'account,contact');
assert.strictEqual(valueOf('--model'), 'MODEL-9');
@@ -623,6 +639,7 @@ test('implicit update metadata reaches real wrapper argv', async () => {
const requests = [];
const probeDirs = [];
const uploadDirs = [];
+ const stageDirs = [];
const pacInvocation = winPac(`C:\\pac\\${installation}`);
const factory = (url) => makeGenpageCli(url, {
pacInvocation,
@@ -656,6 +673,12 @@ test('implicit update metadata reaches real wrapper argv', async () => {
dirs.push(uploadDirs[uploadDirs.length - 1]);
assert.strictEqual(fs.readFileSync(valueOf('--prompt-file'), 'utf8'), 'Fix the sort handler');
assert.strictEqual(fs.readFileSync(valueOf('--agent-message-file'), 'utf8'), 'Preserve page metadata');
+ // pac reads a copy of the bytes that were checked, under the file's own name, in a folder of its own.
+ stageDirs.push(path.dirname(valueOf('--code-file')));
+ dirs.push(stageDirs[stageDirs.length - 1]);
+ assert.notStrictEqual(valueOf('--code-file'), codeFile);
+ assert.strictEqual(path.basename(valueOf('--code-file')), 'page.tsx');
+ assert.strictEqual(fs.readFileSync(valueOf('--code-file'), 'utf8'), fs.readFileSync(codeFile, 'utf8'));
return { status: 0, stdout: `Page ID: ${id}`, stderr: '' };
},
sleep: async () => {},
@@ -671,7 +694,7 @@ test('implicit update metadata reaches real wrapper argv', async () => {
'--prompt', 'Fix the sort handler', '--agent-message', 'Preserve page metadata'], {
makeGenpageCli: factory,
emit: (ok, payload) => {
- cleanupAtEmit = [...probeDirs, ...uploadDirs].map((dir) => fs.existsSync(dir));
+ cleanupAtEmit = [...probeDirs, ...uploadDirs, ...stageDirs].map((dir) => fs.existsSync(dir));
result = { ok, payload };
},
});
@@ -692,7 +715,7 @@ test('implicit update metadata reaches real wrapper argv', async () => {
assert.strictEqual(valueOf('--environment'), env);
assert.strictEqual(valueOf('--app-id'), appId);
assert.strictEqual(valueOf('--page-id'), id);
- assert.strictEqual(valueOf('--code-file'), codeFile);
+ assert.strictEqual(path.basename(valueOf('--code-file')), 'page.tsx', 'a copy of the checked file, under its own name');
assert.strictEqual(valueOf('--model'), 'gpt-4.1');
assert.strictEqual(valueOf('--data-sources'), 'contoso_ticket,contoso_asset');
for (const flag of ['--connectors', '--actions', '--add-to-sitemap']) assert.ok(!args.includes(flag), flag);
@@ -714,8 +737,8 @@ test('implicit update metadata reaches real wrapper argv', async () => {
assert.ok(invocation.args[4].includes('--data-sources contoso_ticket,contoso_asset'));
assert.strictEqual(invocation.options.windowsVerbatimArguments, true);
}
- assert.deepStrictEqual([probeDirs.length, uploadDirs.length], [2, 1], 'the update probes once, then re-reads the stored page to record its hash');
- assert.deepStrictEqual(cleanupAtEmit, [false, false, false], 'every temp directory is gone before the emitter can exit');
+ assert.deepStrictEqual([probeDirs.length, uploadDirs.length, stageDirs.length], [2, 1, 1], 'the update probes once, then re-reads the stored page to record its hash');
+ assert.deepStrictEqual(cleanupAtEmit, [false, false, false, false], 'every temp directory is gone before the emitter can exit');
}
});
@@ -925,13 +948,16 @@ test('an update that omits --model re-sends the page\'s current model; an explic
assert.strictEqual(odd.calls[0].model, undefined);
assert.match(oddRun.payload.warnings[0], /config\.json model is number, not a string/);
- // A create has no current model to keep.
+ // A create has no current model to keep: nothing is downloaded before the upload (the one download after it re-reads the stored page to record its base).
const created = capturingCli({ liveModel: 'gpt-4.1' });
+ const createFactory = created.factory;
+ let downloadsBeforeUpload = null;
+ created.factory = () => { const c = createFactory(); const upload = c.upload; c.upload = async (o) => { downloadsBeforeUpload = created.downloads.length; return upload(o); }; return c; };
const createRun = await new Promise((resolve) => {
main(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'a1', '--code-file', 'c.tsx', '--prompt', 'p', '--agent-message', 'm'],
{ makeGenpageCli: created.factory, emit: (ok, payload) => resolve({ ok, payload }) });
});
- assert.deepStrictEqual([createRun.ok, created.downloads.length, created.calls[0].model], [true, 0, undefined]);
+ assert.deepStrictEqual([createRun.ok, downloadsBeforeUpload, created.calls[0].model], [true, 0, undefined]);
});
// pac stores every ASCII `"` in a page name as `\"` — in the page row and in the navigation title it writes —
@@ -1074,10 +1100,12 @@ test('an unreadable current binding list refuses the update rather than unbindin
test('a CREATE never probes for bindings (there is nothing to preserve)', async () => {
let probed = false;
+ let uploaded = false;
const seen = [];
const factory = () => ({
- download: async () => { probed = true; return true; },
- upload: async (o) => { seen.push(o); return { pageId: '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8' }; },
+ // The one download a create makes comes after the upload, to record its base: only one before it would be a probe.
+ download: async () => { if (!uploaded) probed = true; return true; },
+ upload: async (o) => { uploaded = true; seen.push(o); return { pageId: '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8' }; },
});
const r = await new Promise((resolve) => {
main(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', 'a1', '--code-file', 'c.tsx',
@@ -1886,3 +1914,380 @@ test('an update reads the page name and the deployed page together, and a guard
assert.strictEqual(downloaded, false);
assert.strictEqual(named, false);
});
+
+// ── The Griffel check, held where every page upload passes (AB#6691124) ─────────────────────────────────────────────────────────────
+// Griffel drops ten CSS shorthands from a `makeStyles` object at runtime, and nothing on the way to the service notices: pac transpiles without executing makeStyles, so the page
+// deploys and renders without its border, colour or reset. The skills tell the agent to run scripts/check-griffel-styles.js first, but an instruction is not a gate — a /genpage
+// create, an edit-flow update and a browser-verify fix all end in this script, so it refuses such a page itself, with the file, line, column and longhands, before it lists, reads or
+// writes anything.
+const GRIFFEL_IMPORT = "import { makeStyles, tokens } from '@fluentui/react-components';\n";
+const GRIFFEL_BAD = `${GRIFFEL_IMPORT}const useStyles = makeStyles({\n root: {\n borderWidth: '1px',\n padding: '4px',\n },\n hover: { ':hover': { borderColor: 'red', borderStyle: 'solid' } },\n});\nexport default function P() { return null; }\n`;
+// What a refusal or a warning says each way out of a dropped key does to the page.
+const BOTH_WAYS_OUT = 'Deleting a key changes nothing on screen, because Griffel never applied it; writing the longhands (for `all`, the properties you want) makes the style start to render, which changes how the page looks.';
+// `needle`'s line and column as an editor counts them: independent of the checker, so the refusal is held to where the key really is.
+const placeOf = (source, needle) => {
+ const at = source.indexOf(needle);
+ const before = source.slice(0, at).split('\n');
+ return `${before.length}:${before[before.length - 1].length + 1}`;
+};
+// A CLI that fails the test on ANY use, and a count of how often one was asked for.
+function untouchableCli() {
+ const made = { n: 0 };
+ return { made, factory: () => { made.n += 1; return new Proxy({}, { get: (_, name) => () => { throw new Error(`the pac wrapper must not be used: ${String(name)}`); } }); } };
+}
+
+test('a create of a page whose makeStyles drops Griffel shorthands is refused with each key\'s line, column, longhands and both ways out, before the CLI is even made', async () => {
+ const file = divCode(GRIFFEL_BAD);
+ const cli = untouchableCli();
+ const r = await divRun(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', DIV_APP, '--code-file', file, '--name', 'Overview', '--prompt', 'p', '--agent-message', 'm'], cli);
+ assert.strictEqual(r.ok, false);
+ assert.strictEqual(r.payload.code, 'griffel-shorthand');
+ assert.strictEqual(r.payload.ok, false);
+ assert.strictEqual(cli.made.n, 0, 'nothing is listed, downloaded or uploaded: the check reads the file and nothing else');
+ const error = r.payload.error;
+ assert.ok(error.startsWith(`${file} writes CSS that Griffel drops at runtime, so the page would deploy without it — refusing to upload. `), error);
+ for (const [needle, longhands] of [
+ ['borderWidth', ['borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth']],
+ ['borderColor', ['borderTopColor', 'borderRightColor', 'borderBottomColor', 'borderLeftColor']],
+ ['borderStyle', ['borderTopStyle', 'borderRightStyle', 'borderBottomStyle', 'borderLeftStyle']],
+ ]) {
+ assert.ok(error.includes(`${file}:${placeOf(GRIFFEL_BAD, needle)}: \`${needle}\` is not supported by Griffel`), `${needle}: its place is named in the message`);
+ assert.ok(error.includes(`Write the longhands instead: ${longhands.join(', ')}.`), `${needle}: and what to write`);
+ }
+ assert.ok(error.includes(BOTH_WAYS_OUT), 'and what each way out does: deleting a key keeps the look, the longhands start to render');
+ assert.match(error, new RegExp(`Fix them in the file \\(\`node scripts/check-griffel-styles\\.js --file ${commandArg(file).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\` lists every one\\), then re-run the upload\\.$`));
+ assert.deepStrictEqual(r.payload.problems.map((p) => [p.code, p.property, p.line, p.column]), [
+ ['unsupported-shorthand', 'borderWidth', 4, 5], ['unsupported-shorthand', 'borderColor', 7, 24], ['unsupported-shorthand', 'borderStyle', 7, 44],
+ ], 'the structured problems ride along, for a caller that reads JSON');
+ assert.deepStrictEqual(r.payload.problems.map((p) => p.within), [['root'], ['hover', ':hover'], ['hover', ':hover']], 'with where each sits: the slot, then the selector');
+ assert.strictEqual(placeOf(GRIFFEL_BAD, 'borderColor'), '7:24');
+ // A single key is "it", not "them".
+ const one = divCode(`${GRIFFEL_IMPORT}const s = makeStyles({ root: { all: 'unset' } });\n`);
+ const single = await divRun(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', DIV_APP, '--code-file', one, '--name', 'N', '--prompt', 'p', '--agent-message', 'm'], untouchableCli());
+ assert.match(single.payload.error, /`all` is not supported by Griffel[\s\S]*Fix it in the file/);
+ assert.doesNotMatch(single.payload.error, /Fix them/);
+});
+
+// An UPDATE is held to what it ADDS. The page is already deployed — possibly with a key Griffel drops that an earlier release let through (its only guard was a grep for `borderWidth`) — and
+// the same bytes sent again ship nothing new, while switching a key to its longhands CHANGES how the page renders. The update downloads the deployed page anyway, for its base check, so
+// the file is compared with it: a key the deployed page already has goes ahead with a warning that says both ways out; only a key it did not have stops the upload.
+const UPDATE_ARGS = (file, extra = []) => ['--env', 'https://contoso.crm.dynamics.com/', '--app-id', DIV_APP, '--code-file', file, '--page-id', DIV_PAGE, '--prompt', 'p', ...extra];
+// An UPDATE of the page with `local` as the file and `deployed` as what is deployed (the base marker says the file was downloaded from it, so the base check passes).
+async function griffelUpdate(local, deployed, { extra = [], deployedAs = deployed } = {}) {
+ const file = divCode(local);
+ seedBase(file, { deployed, local: deployed });
+ const cli = divFactory({ page: deployedAs });
+ return { file, cli, r: await divRun(UPDATE_ARGS(file, extra), cli) };
+}
+
+test('an UPDATE of a page that already has the keys — sent as it is, or edited with the keys kept — goes ahead with a warning naming each key and both ways out', async () => {
+ for (const [what, local] of [
+ ['the deployed page, sent again', GRIFFEL_BAD],
+ ['edited, the keys kept', GRIFFEL_BAD.replace("padding: '4px'", "padding: '8px'")],
+ ['the keys a line further down', GRIFFEL_BAD.replace('const useStyles', '// moved\nconst useStyles')],
+ ]) {
+ const { file, cli, r } = await griffelUpdate(local, GRIFFEL_BAD);
+ assert.strictEqual(r.ok, true, `${what}: ${JSON.stringify(r.payload)}`);
+ assert.strictEqual(cli.calls.length, 1, `${what}: the page is uploaded`);
+ const [warning] = r.payload.warnings;
+ assert.ok(warning.startsWith(`${file} updates a page that is already deployed, and the deployed page already had these, set the same, so the upload goes on. It writes CSS that Griffel drops at runtime, so the page renders without it as it does today: `), `${what}: ${warning}`);
+ for (const needle of ['borderWidth', 'borderColor', 'borderStyle']) assert.ok(warning.includes(`${file}:${placeOf(local, needle)}: \`${needle}\` is not supported by Griffel`), `${what}: ${needle}, at its place in the file that is uploaded`);
+ assert.ok(warning.includes(BOTH_WAYS_OUT), `${what}: both ways out`);
+ assert.match(warning, new RegExp(`Edit the file to do either \\(\`node scripts/check-griffel-styles\\.js --file ${commandArg(file).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\` lists every one\\); an upload that adds anything the check reports, or sets one of these to another value, is refused\\.$`), what);
+ }
+});
+
+test('an UPDATE that ADDS a key the deployed page did not have is refused, naming only the new key — and --overwrite-deployed is no way past it', async () => {
+ const added = GRIFFEL_BAD.replace('});\nexport default', " card: { borderStyle: 'dashed' },\n});\nexport default");
+ for (const extra of [[], ['--overwrite-deployed']]) {
+ const { file, cli, r } = await griffelUpdate(added, GRIFFEL_BAD, { extra });
+ assert.strictEqual(r.ok, false, JSON.stringify(extra));
+ assert.strictEqual(r.payload.code, 'griffel-shorthand', JSON.stringify(extra));
+ assert.strictEqual(cli.calls.length, 0, `${JSON.stringify(extra)}: nothing is uploaded`);
+ assert.deepStrictEqual(r.payload.problems.map((p) => [p.property, p.within]), [['borderStyle', ['card']]], 'only the key that is new');
+ const error = r.payload.error;
+ assert.ok(error.startsWith(`${file} writes CSS that Griffel drops at runtime, so the page would deploy without it — refusing to upload. `), error);
+ assert.ok(error.includes(`${file}:${placeOf(added, "borderStyle: 'dashed'")}: \`borderStyle\` is not supported by Griffel`), 'the new key, where it is');
+ for (const old of ['borderWidth', 'borderColor']) assert.ok(!error.includes(`${file}:${placeOf(added, old)}:`), `${old} was already deployed, so it is not what stops the upload`);
+ assert.ok(error.includes(BOTH_WAYS_OUT));
+ assert.match(error, /Fix it in the file \(`node scripts\/check-griffel-styles\.js --file [^`]+` lists every one\), then re-run the upload\.$/);
+ }
+});
+
+test('an UPDATE is judged key by key: a renamed slot keeps the keys the deployed page had, and a second key where there was one is new — and is the one that is named', async () => {
+ const deployed = `${GRIFFEL_IMPORT}const s = makeStyles({\n root: { borderWidth: '1px' },\n});\nexport default function P() { return null; }\n`;
+ // The slot is renamed: the same key, still dropped, still not new.
+ const renamed = await griffelUpdate(deployed.replace('root:', 'container:'), deployed);
+ assert.strictEqual(renamed.r.ok, true, JSON.stringify(renamed.r.payload));
+ // (The read-back after the upload also warns that the deployed page differs from the file, because this fixture's download never changes: it is not about Griffel.)
+ const aboutGriffel = (result) => (result.r.payload.warnings || []).filter((w) => /Griffel/.test(w));
+ assert.strictEqual(aboutGriffel(renamed).length, 1);
+ // A second `borderWidth`, in another slot, is new — wherever it comes in the file.
+ for (const [what, local] of [
+ ['after the old one', deployed.replace("root: { borderWidth: '1px' },", "root: { borderWidth: '1px' },\n card: { borderWidth: '2px' },")],
+ ['before the old one', deployed.replace("root: { borderWidth: '1px' },", "card: { borderWidth: '2px' },\n root: { borderWidth: '1px' },")],
+ ]) {
+ const { file, cli, r } = await griffelUpdate(local, deployed);
+ assert.strictEqual(r.ok, false, what);
+ assert.strictEqual(cli.calls.length, 0, what);
+ assert.deepStrictEqual(r.payload.problems.map((p) => [p.property, p.within]), [['borderWidth', ['card']]], `${what}: the new one, not the one that was already there`);
+ assert.ok(r.payload.error.includes(`${file}:${placeOf(local, "borderWidth: '2px'")}: \`borderWidth\``), `${what}: named where it is`);
+ assert.ok(!r.payload.error.includes(`${file}:${placeOf(local, "borderWidth: '1px'")}:`), `${what}: the old one is not named`);
+ }
+ // Fixing the page — the key deleted — is an update like any other.
+ const fixed = await griffelUpdate(deployed.replace("root: { borderWidth: '1px' },", "root: { padding: '1px' },"), deployed);
+ assert.strictEqual(fixed.r.ok, true);
+ assert.deepStrictEqual(aboutGriffel(fixed), [], 'and says nothing about Griffel');
+});
+
+// A key the deployed page already has is not what the check holds back — but a key given ANOTHER value is a change the maker meant to see, and Griffel drops the new value just as it dropped the
+// old one: the upload would ship it as a silent no-op, which is the defect this check exists to stop. The value is compared as written (nothing is evaluated), so a reformat is not a change.
+test('an UPDATE that gives a key the deployed page already had ANOTHER value is refused — the new value would be dropped too — while a reformat of it goes ahead', async () => {
+ const deployed = `${GRIFFEL_IMPORT}const useStyles = makeStyles({\n row: { ':hover': { borderColor: 'red' } },\n});\nexport default function P() { return null; }\n`;
+ for (const [what, value] of [['a token', 'tokens.colorBrandStroke1'], ['another colour', "'blue'"]]) {
+ for (const extra of [[], ['--overwrite-deployed']]) {
+ const local = deployed.replace("'red'", value);
+ const { file, cli, r } = await griffelUpdate(local, deployed, { extra });
+ const label = `${what} ${JSON.stringify(extra)}`;
+ assert.strictEqual(r.ok, false, label);
+ assert.strictEqual(r.payload.code, 'griffel-shorthand', label);
+ assert.strictEqual(cli.calls.length, 0, `${label}: nothing is uploaded`);
+ assert.deepStrictEqual(r.payload.problems.map((p) => [p.property, p.within, p.value]), [['borderColor', ['row', ':hover'], value.startsWith("'") ? '"blue"' : value]], `${label}: the key that was given a new value`);
+ assert.ok(r.payload.error.includes(`${file}:${placeOf(local, 'borderColor')}: \`borderColor\` is not supported by Griffel`), `${label}: where it is`);
+ assert.ok(r.payload.error.includes(BOTH_WAYS_OUT), label);
+ }
+ }
+ // The same key, set to the same value, written another way: nothing changed, so the page goes ahead with the warning an inherited key gets.
+ for (const [what, text] of [
+ ['other quotes', deployed.replace("'red'", '"red"')],
+ ['other spacing', deployed.replace("{ borderColor: 'red' }", '{\n borderColor: \'red\' ,\n }')],
+ ]) {
+ const { file, cli, r } = await griffelUpdate(text, deployed);
+ assert.strictEqual(r.ok, true, `${what}: ${JSON.stringify(r.payload)}`);
+ assert.strictEqual(cli.calls.length, 1, what);
+ assert.ok(r.payload.warnings.some((w) => w.startsWith(`${file} updates a page that is already deployed, and the deployed page already had these, set the same, so the upload goes on. `)), what);
+ }
+});
+
+test('when the deployed page cannot be read (--overwrite-deployed) there is nothing to compare with, so the update goes ahead with a warning — as the build does for a page it has no record of', async () => {
+ const file = divCode(GRIFFEL_BAD);
+ const cli = divFactory({ page: null }); // pac wrote no page.tsx
+ const r = await divRun(UPDATE_ARGS(file, ['--overwrite-deployed']), cli);
+ assert.strictEqual(r.ok, true, JSON.stringify(r.payload));
+ assert.strictEqual(cli.calls.length, 1);
+ assert.ok(r.payload.warnings[0].startsWith(`${file} updates a page that is already deployed, and the deployed page could not be read to tell which of these it already had, so the upload goes on. `), r.payload.warnings[0]);
+ assert.ok(r.payload.warnings[0].includes(BOTH_WAYS_OUT));
+ // Without the flag an unreadable deployed page is refused first, as it always was.
+ const refused = await divRun(UPDATE_ARGS(divCode(GRIFFEL_BAD)), divFactory({ page: null }));
+ assert.strictEqual(refused.payload.code, 'deployed-unreadable');
+});
+
+test('a page that is clean — longhands, or the same names in a string, a comment, a template and an inline style — is uploaded as before', async () => {
+ const clean = `${GRIFFEL_IMPORT}// borderWidth: 1 would be dropped in makeStyles, but this is a comment\nconst note = 'borderColor: red';\nconst useStyles = makeStyles({ root: { borderTopWidth: '1px', borderTopStyle: 'solid', padding: '4px', border: '1px solid red' } });\n`
+ + 'export default function P() { return <div style={{ borderWidth: 1, borderColor: "red" }}>{`borderStyle: solid`}</div>; }\n';
+ for (const [what, text] of [['a clean page', clean], ['a page with no makeStyles at all', 'export default function P() { return null; }\n']]) {
+ const file = divCode(text);
+ const cli = capturingCli();
+ const r = await runMain(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', DIV_APP, '--code-file', file, '--name', 'N', '--prompt', 'p', '--agent-message', 'm'], cli);
+ assert.strictEqual(r.ok, true, `${what}: ${JSON.stringify(r.payload)}`);
+ assert.strictEqual(cli.calls.length, 1, what);
+ }
+ // A file the script cannot read is refused before anything runs: the upload reads the page once, checks those bytes and sends pac a copy of them,
+ // so there is nothing to check or send — and a file that appears later must not go up unchecked.
+ const missing = capturingCli();
+ const absent = path.join(tmp(), 'absent.tsx');
+ const r = await runMain(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', DIV_APP, '--code-file', absent, '--name', 'N', '--prompt', 'p', '--agent-message', 'm'], missing);
+ assert.strictEqual(r.ok, false);
+ assert.match(r.payload.error, /^--code-file could not be read: .*ENOENT/);
+ assert.deepStrictEqual([missing.calls.length, missing.downloads.length], [0, 0], 'nothing is listed, downloaded or uploaded');
+});
+
+test('a call the checker cannot read for certain is refused too, and one that lies before the lexer\'s first guess is read as usual', async () => {
+ const call = "const useStyles = makeStyles({ root: { borderWidth: 1 } });";
+ const guess = 'const o = {a: 1} / 2; const x = /re/;';
+ const after = divCode(`${GRIFFEL_IMPORT}${guess}\n${call}\nexport default function P() { return null; }\n`);
+ const r = await divRun(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', DIV_APP, '--code-file', after, '--name', 'N', '--prompt', 'p', '--agent-message', 'm'], untouchableCli());
+ assert.strictEqual(r.ok, false);
+ assert.strictEqual(r.payload.code, 'griffel-shorthand');
+ assert.match(r.payload.error, /the makeStyles call here cannot be checked for certain/);
+ assert.deepStrictEqual(r.payload.problems.map((p) => p.code), ['unverifiable-style-call']);
+ // The same page with its call moved above the guess is clean and uploads.
+ const before = divCode(`${GRIFFEL_IMPORT}const useStyles = makeStyles({ root: { borderTopWidth: 1 } });\n${guess}\nexport default function P() { return null; }\n`);
+ const cli = capturingCli();
+ const ok = await runMain(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', DIV_APP, '--code-file', before, '--name', 'N', '--prompt', 'p', '--agent-message', 'm'], cli);
+ assert.strictEqual(ok.ok, true, JSON.stringify(ok.payload));
+});
+
+// A call the checker cannot read is not a key Griffel drops: a valid page with `if (s) { } /x/.test(s);` before a clean makeStyles must not be refused as "writes CSS that Griffel drops at
+// runtime", which sends the author looking for CSS that is not there when only rewriting the code gets past it. The refusal says what it is, and what to change; and the command it suggests is a
+// whole one — a path with a space (a Windows profile folder often has one) stays ONE argument in it.
+const GRIFFEL_UNREADABLE = `${GRIFFEL_IMPORT}export function skip(s: string) { if (s) { } /x/.test(s); }\nconst useStyles = makeStyles({ root: { padding: '4px' } });\nexport default function P() { return null; }\n`;
+function spacedFile(text) {
+ const dir = path.join(tmp(), 'Dev User');
+ fs.mkdirSync(dir);
+ const file = path.join(dir, 'page.tsx');
+ fs.writeFileSync(file, text);
+ return file;
+}
+
+test('a call the checker cannot read is refused as one it could not read — not as CSS Griffel drops — and the command it suggests keeps a path with a space as one argument', async () => {
+ const file = spacedFile(GRIFFEL_UNREADABLE);
+ const r = await divRun(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', DIV_APP, '--code-file', file, '--name', 'N', '--prompt', 'p', '--agent-message', 'm'], untouchableCli());
+ assert.strictEqual(r.ok, false);
+ assert.strictEqual(r.payload.code, 'griffel-shorthand');
+ const error = r.payload.error;
+ assert.ok(error.startsWith(`${file} has makeStyles calls the Griffel check could not read, so it cannot tell whether the page writes CSS that Griffel drops at runtime — refusing to upload. ${file}:3:19: the makeStyles call here cannot be checked for certain`), error);
+ assert.doesNotMatch(error, /writes CSS that Griffel drops at runtime, so the page would deploy without it/, 'it is not said to write any');
+ assert.match(error, /put an operand in parentheses, \(\{ … \}\) \/ 2 or \(\/re\/\)\.test\(text\), or end the statement with a ";" — or move the makeStyles call above it\./, 'what to change');
+ assert.ok(error.endsWith(`Change the file as that says (\`node scripts/check-griffel-styles.js --file '${file}'\` shows what it cannot read), then re-run the upload.`), error);
+ assert.deepStrictEqual(r.payload.problems.map((p) => p.code), ['unverifiable-style-call']);
+ // A shorthand refusal quotes it as well.
+ const bad = await divRun(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', DIV_APP, '--code-file', spacedFile(GRIFFEL_BAD), '--name', 'N', '--prompt', 'p', '--agent-message', 'm'], untouchableCli());
+ assert.match(bad.payload.error, /\(`node scripts\/check-griffel-styles\.js --file '[^']*Dev User[^']*page\.tsx'` lists every one\), then re-run the upload\.$/);
+ // Both in one page: the keys come first, and the call is named as one the check could not read.
+ const both = await divRun(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', DIV_APP, '--code-file', divCode(`${GRIFFEL_IMPORT}const a = makeStyles({ root: { all: 'unset' } });\nexport function skip(s: string) { if (s) { } /x/.test(s); }\nconst b = makeStyles({ root: { padding: 1 } });\n`), '--name', 'N', '--prompt', 'p', '--agent-message', 'm'], untouchableCli());
+ assert.match(both.payload.error, /writes CSS that Griffel drops at runtime, so the page would deploy without it — refusing to upload\. [^ ]+:2:\d+: `all` is not supported[\s\S]*It also has makeStyles calls the check could not read, so it cannot tell whether they hold more: [^ ]+:4:\d+: the makeStyles call here cannot be checked for certain[\s\S]*Fix them in the file/);
+});
+
+// The command a refusal suggests is one the user — or the agent — pastes, and the path comes from wherever the page file is: an untrusted checkout can name a file so that
+// pasting a command written with it bare runs part of the name. Shell syntax stays inside single quotes; a name with a quote, which no shell can be given unchanged, is not
+// written into the command at all — a placeholder is, and the path is named in a sentence before the way on.
+test('a refusal\'s command never runs shell syntax from the page file\'s name: quoted, or a placeholder with the path named as data', async () => {
+ const named = (name) => {
+ const dir = tmp();
+ const file = path.join(dir, name);
+ fs.writeFileSync(file, GRIFFEL_BAD);
+ return file;
+ };
+ const hostile = named('x;echo INJECTED;$(whoami)`id`.tsx');
+ const r = await divRun(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', DIV_APP, '--code-file', hostile, '--name', 'N', '--prompt', 'p', '--agent-message', 'm'], untouchableCli());
+ assert.strictEqual(r.payload.code, 'griffel-shorthand');
+ assert.ok(r.payload.error.endsWith(`Fix them in the file (\`node scripts/check-griffel-styles.js --file '${hostile}'\` lists every one), then re-run the upload.`), r.payload.error);
+ const quoted = named("it's;echo INJECTED.tsx");
+ const q = await divRun(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', DIV_APP, '--code-file', quoted, '--name', 'N', '--prompt', 'p', '--agent-message', 'm'], untouchableCli());
+ assert.strictEqual(q.payload.code, 'griffel-shorthand');
+ assert.ok(q.payload.error.endsWith(`<file> is ${JSON.stringify(quoted)}; it is not written into the command because no way of writing it reaches the command unchanged in both PowerShell and a POSIX shell. `
+ + 'Fix them in the file (`node scripts/check-griffel-styles.js --file <file>` lists every one), then re-run the upload.'), q.payload.error);
+});
+
+test('an UPDATE of an unreadable page that IS the deployed page only warns; one that changed is refused, because what it hides cannot be compared', async () => {
+ const same = await griffelUpdate(GRIFFEL_UNREADABLE, GRIFFEL_UNREADABLE);
+ assert.strictEqual(same.r.ok, true, JSON.stringify(same.r.payload));
+ assert.strictEqual(same.cli.calls.length, 1);
+ assert.ok(same.r.payload.warnings[0].startsWith(`${same.file} updates a page that is already deployed, and the deployed page already had these, set the same, so the upload goes on. It has makeStyles calls the Griffel check could not read, so it cannot tell whether the page writes CSS that Griffel drops at runtime: `), same.r.payload.warnings[0]);
+ assert.doesNotMatch(same.r.payload.warnings[0], /Deleting a key/, 'there is no key to delete');
+ // Re-saved with the other line endings and a BOM — not a difference to pac or to the base marker — it is still the deployed page.
+ const resaved = await griffelUpdate(`\uFEFF${GRIFFEL_UNREADABLE.replace(/\n/g, '\r\n')}`, GRIFFEL_UNREADABLE);
+ assert.strictEqual(resaved.r.ok, true, JSON.stringify(resaved.r.payload));
+ // Edited: the unreadable call cannot be shown to hide nothing new.
+ const edited = await griffelUpdate(`${GRIFFEL_UNREADABLE}// edited\n`, GRIFFEL_UNREADABLE);
+ assert.strictEqual(edited.r.ok, false);
+ assert.strictEqual(edited.r.payload.code, 'griffel-shorthand');
+ assert.ok(edited.r.payload.error.startsWith(`${edited.file} has makeStyles calls the Griffel check could not read`), edited.r.payload.error);
+ assert.strictEqual(edited.cli.calls.length, 0);
+});
+
+// A style object written elsewhere — `const styles = { root: { borderWidth: '1px' } }; makeStyles(styles)` — holds keys the check cannot see, and this one holds a key
+// Griffel drops. The page is refused as one the check could not read, as an unreadable call is: a create before anything is sent, and an update that changes the page;
+// an update that IS the deployed page only warns, because sending the same bytes again ships nothing new.
+const GRIFFEL_INDIRECT = `${GRIFFEL_IMPORT}const styles = { root: { borderWidth: '1px' } };\nconst useStyles = makeStyles(styles);\nexport default function P() { return null; }\n`;
+test('a page whose style object is written elsewhere is refused before anything is sent, as one the check could not read', async () => {
+ const r = await divRun(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', DIV_APP, '--code-file', divCode(GRIFFEL_INDIRECT), '--name', 'N', '--prompt', 'p', '--agent-message', 'm'], untouchableCli());
+ assert.strictEqual(r.ok, false);
+ assert.strictEqual(r.payload.code, 'griffel-shorthand');
+ assert.deepStrictEqual(r.payload.problems.map((p) => p.code), ['unread-style-object']);
+ assert.match(r.payload.error, /has makeStyles calls the Griffel check could not read, so it cannot tell whether the page writes CSS that Griffel drops at runtime — refusing to upload\. [^ ]+:3:\d+: this makeStyles call is given a style object written elsewhere/);
+ const same = await griffelUpdate(GRIFFEL_INDIRECT, GRIFFEL_INDIRECT);
+ assert.strictEqual(same.r.ok, true, JSON.stringify(same.r.payload));
+ assert.match(same.r.payload.warnings[0], /It has makeStyles calls the Griffel check could not read/);
+ const edited = await griffelUpdate(`${GRIFFEL_INDIRECT}// edited\n`, GRIFFEL_INDIRECT);
+ assert.strictEqual(edited.r.ok, false);
+ assert.deepStrictEqual(edited.r.payload.problems.map((p) => p.code), ['unread-style-object']);
+ assert.strictEqual(edited.cli.calls.length, 0);
+});
+
+// ── What pac is sent is what was checked ────────────────────────────────────────────────────────────────────────────────────────────
+// The upload reads the page once and checks those bytes, but pac reads the code file itself — after an update's listing and download, seconds
+// later. A save in between would ship bytes nothing here checked, so pac is sent a copy of the checked bytes, and the base marker records them.
+// And JavaScript passed with --compiled-code-file would be deployed instead of the checked TypeScript, so that flag is refused.
+
+test('--compiled-code-file is refused before anything runs: the JavaScript in it would be deployed without the Griffel check', async () => {
+ const file = divCode(DIV_TEXT);
+ const compiled = path.join(path.dirname(file), 'page.js');
+ fs.writeFileSync(compiled, 'const s = (0, rc.makeStyles)({ root: { borderWidth: "1px" } });\n');
+ const cli = untouchableCli();
+ for (const extra of [[], ['--page-id', DIV_PAGE]]) {
+ const r = await divRun(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', DIV_APP, '--code-file', file, '--compiled-code-file', compiled,
+ '--name', 'N', '--prompt', 'p', '--agent-message', 'm', ...extra], cli);
+ assert.strictEqual(r.ok, false, JSON.stringify(extra));
+ assert.match(r.payload.error, /^--compiled-code-file is not accepted: the Griffel check reads the TypeScript in --code-file/);
+ }
+ assert.strictEqual(cli.made.n, 0, 'nothing is listed, downloaded or uploaded');
+});
+
+test('a create sends pac a copy of the bytes that were checked: a save to the file after the check does not ship, and the marker records what was sent', async () => {
+ const file = divCode(DIV_TEXT);
+ const seen = [];
+ const cli = {
+ factory: () => ({
+ upload: async (o) => {
+ // The file is saved again, with a key Griffel drops, between the check and pac's read.
+ fs.writeFileSync(file, GRIFFEL_BAD);
+ seen.push({ codeFile: o.codeFile, sourceFile: o.sourceFile, sent: fs.readFileSync(o.codeFile, 'utf8') });
+ return { pageId: '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8' };
+ },
+ download: async ({ outputDir, pageIds }) => { for (const pid of pageIds || []) writeProbe(outputDir, pid, { page: DIV_TEXT }); },
+ }),
+ };
+ const r = await divRun(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', DIV_APP, '--code-file', file, '--name', 'N', '--prompt', 'p', '--agent-message', 'm'], cli);
+ assert.strictEqual(r.ok, true, JSON.stringify(r.payload));
+ assert.strictEqual(seen.length, 1);
+ assert.strictEqual(seen[0].sent, DIV_TEXT, 'the checked bytes, not the later save');
+ assert.notStrictEqual(seen[0].codeFile, file);
+ assert.strictEqual(path.basename(seen[0].codeFile), 'page.tsx', 'under the file\'s own name, so pac compiles it as it would the file');
+ assert.strictEqual(seen[0].sourceFile, file, 'the file the caller named, for the upload\'s own messages');
+ assert.ok(!fs.existsSync(path.dirname(seen[0].codeFile)), 'the copy is removed once pac has answered');
+ // The marker is the caller's file's, and records the hash of what was sent — so a later check sees the save as the local change it is.
+ const marker = readMarker(file);
+ assert.strictEqual(marker.localSha256, pageHash(DIV_TEXT));
+ assert.strictEqual(marker.source, 'upload');
+});
+
+test('an update sends pac the checked bytes even when the file is saved while the listing and download run', async () => {
+ const file = divCode(DIV_TEXT);
+ seedBase(file);
+ const sent = [];
+ const inner = divFactory();
+ const cli = {
+ factory: () => {
+ const real = inner.factory();
+ return {
+ ...real,
+ // The save lands while the update lists the environment, after the Griffel check and before the base check and the upload.
+ enumerateEnvironment: async () => { fs.writeFileSync(file, GRIFFEL_BAD); return real.enumerateEnvironment(); },
+ upload: async (o) => { sent.push(fs.readFileSync(o.codeFile, 'utf8')); return real.upload(o); },
+ };
+ },
+ };
+ const r = await divRun(UPDATE_ARGS(file), cli);
+ assert.strictEqual(r.ok, true, JSON.stringify(r.payload));
+ assert.deepStrictEqual(sent, [DIV_TEXT], 'the bytes the Griffel check and the comparison with the deployed page were made on');
+ assert.strictEqual(readMarker(file).localSha256, pageHash(DIV_TEXT));
+});
+
+test('the copy pac was sent is removed when the upload fails, before the failure is reported', async () => {
+ const file = divCode(DIV_TEXT);
+ let staged = null;
+ let stagedAtEmit = null;
+ const cli = { factory: () => ({ upload: async (o) => { staged = o.codeFile; throw new Error('pac exploded'); } }) };
+ const r = await new Promise((resolve, reject) => {
+ main(['--env', 'https://contoso.crm.dynamics.com/', '--app-id', DIV_APP, '--code-file', file, '--name', 'N', '--prompt', 'p', '--agent-message', 'm'], {
+ makeGenpageCli: cli.factory,
+ emit: (ok, payload) => { stagedAtEmit = staged && fs.existsSync(path.dirname(staged)); resolve({ ok, payload }); },
+ }).catch(reject);
+ });
+ assert.strictEqual(r.ok, false);
+ assert.match(r.payload.error, /pac exploded/);
+ assert.ok(staged, 'the upload was given a copy');
+ assert.strictEqual(stagedAtEmit, false, 'gone before the emitter can end the process');
+});
diff --git a/plugins/model-apps/scripts/tests/griffel-styles.test.js b/plugins/model-apps/scripts/tests/griffel-styles.test.js
new file mode 100644
index 000000000..1492e8da5
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/griffel-styles.test.js
@@ -0,0 +1,1353 @@
+'use strict';
+// The Griffel unsupported-shorthand gate (AB#6691124): lib/griffel-styles.js and the check-griffel-styles.js CLI.
+//
+// Griffel's runtime skips ten CSS shorthands in a `makeStyles` style object and only logs to the browser console, so a page that writes one type-checks,
+// transpiles, deploys and then renders without the border or the reset. The gate used to be an agent grepping the page for `borderWidth`: one property of the ten,
+// and a text search that cannot tell a key from a string, a comment or an inline `style={{ … }}`. These tests pin what replaced it. That the docs run it before every
+// transpile and upload is asserted in genpage-dispatch-contract.test.js.
+
+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, spawnSync } = require('node:child_process');
+
+const { griffelStyleProblems, griffelProblemsNotIn, describeGriffelRefusal, describeGriffelWarning, SHORTHAND_REMEDIES, UNSUPPORTED_GRIFFEL_SHORTHANDS, STYLE_FUNCTIONS } = require('../lib/griffel-styles.js');
+const { checkGriffelStyles } = require('../check-griffel-styles.js');
+
+const SCRIPT = path.join(__dirname, '..', 'check-griffel-styles.js');
+const PLUGIN = path.join(__dirname, '..', '..');
+const REPO = path.join(PLUGIN, '..', '..');
+const IMPORT = "import { makeStyles, tokens } from '@fluentui/react-components';\n";
+
+// Griffel's UNSUPPORTED_CSS_PROPERTIES (packages/core/src/constants.ts of @griffel/core 1.19 and 1.20), each with the longhands CSS defines for it.
+const TEN = [
+ ['all', []],
+ ['borderColor', ['borderTopColor', 'borderRightColor', 'borderBottomColor', 'borderLeftColor']],
+ ['borderStyle', ['borderTopStyle', 'borderRightStyle', 'borderBottomStyle', 'borderLeftStyle']],
+ ['borderWidth', ['borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth']],
+ ['borderBlock', ['borderBlockStartWidth', 'borderBlockStartStyle', 'borderBlockStartColor', 'borderBlockEndWidth', 'borderBlockEndStyle', 'borderBlockEndColor']],
+ ['borderBlockStart', ['borderBlockStartWidth', 'borderBlockStartStyle', 'borderBlockStartColor']],
+ ['borderBlockEnd', ['borderBlockEndWidth', 'borderBlockEndStyle', 'borderBlockEndColor']],
+ ['borderInline', ['borderInlineStartWidth', 'borderInlineStartStyle', 'borderInlineStartColor', 'borderInlineEndWidth', 'borderInlineEndStyle', 'borderInlineEndColor']],
+ ['borderInlineStart', ['borderInlineStartWidth', 'borderInlineStartStyle', 'borderInlineStartColor']],
+ ['borderInlineEnd', ['borderInlineEndWidth', 'borderInlineEndStyle', 'borderInlineEndColor']],
+];
+
+// A page whose makeStyles argument is `slots` (source text of the object), under the usual import.
+const styles = (slots, header = IMPORT) => `${header}const useStyles = makeStyles(${slots});\n`;
+// `property@line:column` of each unsupported key, in source order.
+const found = (source) => griffelStyleProblems(source).problems.map((p) => `${p.property || p.code}@${p.line}:${p.column}`);
+const names = (source) => griffelStyleProblems(source).problems.map((p) => p.property || p.code);
+
+// ─── The set ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+test('griffel-styles: the checked set is exactly the ten shorthands Griffel drops, each with the longhands CSS defines for it', () => {
+ assert.deepEqual([...UNSUPPORTED_GRIFFEL_SHORTHANDS.keys()].sort(), TEN.map(([property]) => property).sort());
+ for (const [property, longhands] of TEN) assert.deepEqual(UNSUPPORTED_GRIFFEL_SHORTHANDS.get(property), longhands, property);
+});
+
+for (const [property, longhands] of TEN) {
+ test(`griffel-styles: ${property} in a slot is reported with its line, column and longhands`, () => {
+ const source = `${IMPORT}const useStyles = makeStyles({\n root: {\n ${property}: 'x',\n },\n});\n`;
+ const { calls, problems } = griffelStyleProblems(source);
+ assert.equal(calls, 1);
+ assert.equal(problems.length, 1);
+ const [p] = problems;
+ assert.deepEqual(
+ { code: p.code, property: p.property, line: p.line, column: p.column, longhands: p.longhands },
+ { code: 'unsupported-shorthand', property, line: 4, column: 5, longhands },
+ );
+ assert.ok(p.message.includes(`\`${property}\``), 'the message names the key');
+ assert.match(p.message, /Griffel/);
+ for (const longhand of longhands) assert.ok(p.message.includes(longhand), `the message lists ${longhand}`);
+ });
+}
+
+test('griffel-styles: `all` has no longhand list, so its message says to set the properties one by one', () => {
+ const [p] = griffelStyleProblems(styles("{ root: { all: 'unset' } }")).problems;
+ assert.deepEqual(p.longhands, []);
+ assert.match(p.message, /one by one/);
+ assert.doesNotMatch(p.message, /Write the longhands/);
+});
+
+test('griffel-styles: the shorthands Griffel supports, their longhands, and names that only contain a flagged one are not reported', () => {
+ const supported = [
+ 'padding', 'paddingBlock', 'margin', 'border', 'borderTop', 'borderRight', 'borderBottom', 'borderLeft', 'borderRadius', 'borderCollapse', 'borderImage',
+ 'outline', 'gap', 'overflow', 'flex', 'font', 'background', 'inset', 'transition', 'animation',
+ 'borderTopWidth', 'borderRightStyle', 'borderBottomColor', 'borderLeftWidth', 'borderBlockStartWidth', 'borderBlockEndStyle', 'borderInlineStartColor',
+ 'borderInlineEndWidth', 'borderStartStartRadius',
+ 'borderColors', 'xborderWidth', 'borderWidthX', 'allow', 'allAbout',
+ ];
+ const source = styles(`{ root: { ${supported.map((key) => `${key}: 'x'`).join(', ')} } }`);
+ const { calls, problems } = griffelStyleProblems(source);
+ assert.equal(calls, 1);
+ assert.deepEqual(problems, []);
+});
+
+// ─── Keys ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+test('griffel-styles: a key is found however it is written — bare, quoted, spaced, commented, computed from a string, escaped, or shorthand', () => {
+ const members = [
+ "borderWidth: 'x'",
+ "borderWidth : 'x'",
+ "borderWidth\n : 'x'",
+ "borderWidth/* why */: 'x'",
+ "'borderWidth': 'x'",
+ "\"borderWidth\" : 'x'",
+ "['borderWidth']: 'x'",
+ '["borderWidth"]: "x"',
+ "[`borderWidth`]: 'x'",
+ "[ 'borderWidth' ]: 'x'",
+ "'border\\u0057idth': 'x'",
+ "'border\\x57idth': 'x'",
+ "'border\\u{57}idth': 'x'",
+ "'border\\\nWidth': 'x'",
+ 'borderWidth: undefined',
+ 'borderWidth: null',
+ 'borderWidth: 0',
+ 'borderWidth: tokens.strokeWidthThin',
+ 'borderWidth: `${tokens.strokeWidthThin}`',
+ "borderWidth: ['1px', 'thin']",
+ 'borderWidth',
+ ];
+ for (const member of members) {
+ const source = styles(`{ root: { color: 'red', ${member}, padding: 1 } }`);
+ assert.deepEqual(names(source), ['borderWidth'], member);
+ }
+});
+
+test('griffel-styles: a string that is not one of the ten, a value that names one, and a method are not keys Griffel drops', () => {
+ const members = [
+ "'borderWidth ': 'x'",
+ "'border-width': 'x'",
+ "' borderWidth': 'x'",
+ "content: '\"borderWidth\": 1'",
+ "transition: 'borderWidth 1s'",
+ // A method's value is a function and a setter alone defines none: Griffel writes nothing for either, so no style is lost.
+ "set borderColor(v) {}",
+ "borderStyle() { return 'solid'; }",
+ "async borderBlock() {}",
+ "async *borderInline() {}",
+ "*borderInlineEnd() {}",
+ "[`--${name}`]: 'x'",
+ "[`padding${side}`]: tokens.spacingHorizontalS",
+ // A key that starts with `-` is a property whatever follows, and so is one that starts with `--` whatever its substitution holds — a nested template that
+ // is raw text included — and one that starts with anything else Griffel does not nest under (`.`, a space).
+ "[`-${suffix}`]: tokens.colorBrandForeground1",
+ "[`--${String.raw`\\u`.length}`]: tokens.colorBrandForeground1",
+ "[`.${className}`]: hover",
+ "[` :${state}`]: hover",
+ ];
+ for (const member of members) {
+ const source = styles(`{ root: { ${member}, color: 'red' } }`);
+ assert.deepEqual(names(source), [], member);
+ }
+});
+
+// A getter defines a key, and Griffel reads it — `for … in`, then `obj[key]`, which calls it — so what it returns is that key's value: its name is checked as any
+// key's is, and the value it returns, which the check cannot read, is reported wherever a style object is wanted. A getter is also code that runs, so one that
+// defines a property is reported too (see the next tests).
+test('griffel-styles: a getter is a key Griffel reads, and the object it returns is one the check cannot see', () => {
+ const GETTER = "get root(): Record<string, string> { return { borderWidth: '1px' }; }";
+ assert.deepEqual(names(styles(`{ ${GETTER} }`)), ['unread-style-object']);
+ assert.deepEqual(names(styles("{ root: { get ':hover'() { return hover; }, get color() { return 'red'; } } }")), ['unread-style-object', 'unread-style-object']);
+ assert.deepEqual(names(styles("{ root: { get borderWidth() { return '1px'; } } }")), ['borderWidth', 'unread-style-object']);
+ assert.deepEqual(names(styles("{ root: { get [key]() { return 'red'; } }, get 0() { return base; }, get 'b'() { return { color: 'red' }; } }")),
+ ['unread-style-object', 'unread-style-object', 'unread-style-object']);
+ // A key named get, set or async is a key like any other.
+ assert.deepEqual(names(styles("{ get: { borderColor: 'x' }, set : { color: 'red' }, async: base }")), ['borderColor', 'unread-style-object']);
+ // A getter's name may follow `get` with no space at all.
+ for (const getter of ["get['root']()", "get'root'()", 'get.5()']) {
+ assert.deepEqual(names(styles(`{ ${getter} { return { borderWidth: '1px' }; } }`)), ['unread-style-object'], getter);
+ }
+ // Its return type is a type, however it is written: one that reads like a conditional of objects is not the getter's value, and an object type's members are
+ // not keys (the one problem below is the getter itself, which runs).
+ assert.deepEqual(names(`${IMPORT}type Style<A, B> = Record<string, string>;\nconst useStyles = makeStyles({ get root(): Style<true extends true ? {} : {}, never> { return { borderWidth: '1px' }; } });\n`),
+ ['unread-style-object']);
+ assert.deepEqual(names(styles("{ root: { get color(): { borderWidth: string }['borderWidth'] { return 'red'; } } }")), ['unread-style-object']);
+ const [slot] = griffelStyleProblems(styles(`{ ${GETTER} }`)).problems;
+ assert.match(slot.message, /^the style object of slot "root" is not written here \(get root\(\)/);
+ // The value is a getter's however it is named: one called `as` is no cast.
+ const [as] = griffelStyleProblems(styles("{ get as(): Record<string, string> { return { color: 'red' }; } }")).problems;
+ assert.match(as.message, /^the style object of slot "as" is not written here/);
+});
+
+// A function member — a getter, a setter, a method, an async or generator method — ends where its body closes: its return type may hold commas, and the member
+// after it is read from where it starts. (A getter that runs is reported for itself — the one `unread-style-object` below each — never for a key in its type.)
+test('griffel-styles: a function member ends with its body, not at a comma of its return type', () => {
+ assert.deepEqual(names(`${IMPORT}type Color<A, B, C> = string;\ntype all = string;\nconst useStyles = makeStyles({ root: { get color(): Color<string, all, string> { return 'red'; } } });\n`),
+ ['unread-style-object']);
+ // Each kind of function member, with a type argument that would read as a key `all` if the member ended at the first comma.
+ assert.deepEqual(names(styles("{ root: { color(): Color<string, all, string> { return 1; }, borderWidth: '1px' } }")), ['borderWidth']);
+ assert.deepEqual(names(styles("{ root: { async color(): Promise<Map<a, all>> { }, *gen(): Generator<a, all, b> { }, async *g(): X<a, all, b> {}, borderColor: 'x' } }")),
+ ['borderColor']);
+ assert.deepEqual(names(styles("{ root: { set['borderColor'](v) {}, get x(): T<a, b> { return 1; }, borderStyle: 's', fn(a = { all: 1 }): { all: 1 } { return 1; } } }")),
+ ['unread-style-object', 'borderStyle']);
+ // An object type inside the type arguments is not the body, though a comma follows it.
+ assert.deepEqual(names(styles('{ root: { fn(): Map<{}, all, x> { return 1; } } }')), []);
+ // Nor is one in a conditional return type, which a `:` follows.
+ assert.deepEqual(names(`${IMPORT}type Color<A, B, C> = string;\ntype all = string;\nconst useStyles = makeStyles({ root: { get color():\n false extends true ? {} : Color<string, all, string> {\n return 'red';\n }, } });\n`),
+ ['unread-style-object']);
+ // A method's type parameters come before its parameters, and hold commas too.
+ assert.deepEqual(names(styles("{ root: { fn<A, all, C>(): string { return 'x'; }, async g<A, all>(): X<a, all, b> {}, *h<A, all>() {}, color: 'red' } }")), []);
+});
+
+// A getter is code, and it runs: Griffel calls it as it reads its key, and a spread as it copies its object — before a later definition replaces what it returned.
+// Its `this` is that object, so it can rewrite or delete a key Griffel reads after it, and the check does not read code: a getter that runs is reported, whatever
+// key it defines. One that never runs — replaced in its own object before anything reads it, or inherited under an own key — is not; nor is one whose object never
+// reaches Griffel, though a spread runs it, since its own object is all it can change without writing shared state, which no check of the style objects can see
+// (WHAT CODE CAN CHANGE, in the library's header). Each page here was run (TypeScript 5.8.3, then Node and Griffel 1.20.3's own resolveStyleRulesForSlots) and the
+// getters it called counted: the check reports each one that runs on a style object Griffel reads or on an object a spread copies into one, and no other.
+test('griffel-styles: a getter that runs is reported whatever key it defines, and one that never runs is not', () => {
+ const page = (slots) => styles(slots, `${IMPORT}const bad: Record<string, string> = { borderWidth: '1px' };\nconst c = true;\n`);
+ // Griffel reads `color`, which runs the getter, which writes the `:hover` Griffel reads next.
+ assert.deepEqual(names(page("{ root: { get color() { (this as any)[':hover'] = { borderWidth: '1px' }; return 'red'; }, ':hover': { color: 'blue' } } }")),
+ ['unread-style-object']);
+ // The same under animationName: its keyframes are not read, but its getter runs.
+ assert.deepEqual(names(page("{ root: { get animationName() { (this as any)[':hover'] = bad; return {}; }, ':hover': { color: 'blue' } } }")), ['unread-style-object']);
+ // Deleting the own `:hover` lets Griffel read the inherited one, which the own key hid.
+ assert.deepEqual(names(page("{ root: { __proto__: { ':hover': bad }, get color() { delete (this as any)[':hover']; return 'red'; }, ':hover': { color: 'blue' } } }")),
+ ['unread-style-object']);
+ // A spread calls the getter as it copies its object, before the later `root` replaces what it returned — by then it has put `bad` in `other`.
+ assert.deepEqual(names(page("{ ...{ get root(): Record<string, string> { Reflect.set(this, 'other', bad); return {}; }, other: { color: 'red' } }, root: { color: 'blue' } }")),
+ ['unread-style-object']);
+ // So does a spread inside a prototype, as the prototype is written, though an own key hides what it copied; and a spread inside a spread.
+ assert.deepEqual(names(page("{ root: { __proto__: { ...{ get color() { return 'red'; } } }, color: 'blue' } }")), ['unread-style-object']);
+ assert.deepEqual(names(page("{ ...{ ...{ get root() { return {}; } } }, root: { color: 'blue' } }")), ['unread-style-object']);
+ // A spread a condition chooses copies, and so runs the getter, whenever it is chosen: uncertain is not "never".
+ assert.deepEqual(names(page("{ ...(c && { get root(): Record<string, string> { Reflect.set(this, 'other', bad); return {}; }, other: { color: 'red' } }), root: { color: 'blue' } }")),
+ ['unread-style-object']);
+ assert.deepEqual(names(page("{ ...(c ? { get root(): Record<string, string> { return {}; } } : {}), root: { color: 'blue' } }")), ['unread-style-object']);
+ // A getter that never runs is not reported.
+ for (const slots of [
+ "{ root: { get color() { return 'red'; }, color: 'blue' } }", // replaced in its own object
+ "{ root: { get color() { return 'red'; }, ...{ color: 'blue' } } }", // … by what a later spread copies into it
+ "{ ...{ get root() { return {}; }, root: { color: 'blue' } } }", // … inside the object a spread copies, before the copy
+ "{ root: { __proto__: { get color() { return 'red'; } }, color: 'blue' } }", // inherited, and an own key hides it
+ "{ ...{ __proto__: { get root() { return {}; } } } }", // a spread copies own keys only
+ ]) assert.deepEqual(names(page(slots)), [], slots);
+ // Nor is one whose object never reaches Griffel, though a spread runs it as the page is built: what it can change there is that object alone.
+ for (const slots of [
+ "{ ...{ root: { ...{ get color() { return 'red'; } } } }, root: { color: 'blue' } }", // in a value a later definition replaces
+ "{ ...{ __proto__: { ...{ get root() { return {}; } } } } }", // in a prototype the spread does not copy
+ "{ root: { animationName: { get from() { return { opacity: 0 }; } } } }", // in an animation's keyframes, which are not style objects
+ ]) assert.deepEqual(names(page(slots)), [], slots);
+ // The problem names the getter and where it is: where Griffel reads it, or where the spread that ran it put it.
+ const [held] = griffelStyleProblems(page("{ root: { get color() { return 'red'; } } }")).problems;
+ assert.deepEqual(held.within, ['root', 'color']);
+ assert.match(held.message, /^"color" is defined by a getter \(get color\(\) \{ return 'red'; \}\), which runs when its object is read/);
+ const [ran] = griffelStyleProblems(page("{ ...{ get root() { return {}; } }, root: { color: 'blue' } }")).problems;
+ assert.deepEqual(ran.within, ['...', 'root']);
+});
+
+// A key is the string JavaScript makes of it, so two keys are taken for one only where they are one. A CR LF or a lone CR written in a template is one LF,
+// however the file ends its lines (the TRV of a LineTerminatorSequence), so it is the key a quoted '\n' names, which replaces it, and not the key '\r\n' or '\r'
+// names, which does not. U+2028 and U+2029 stay as written, in a template and in a string alike: neither is the key '\n' names.
+test('griffel-styles: a line break written in a template key is read as JavaScript reads it', () => {
+ const page = (slots) => styles(slots, `${IMPORT}const bad: Record<string, string> = { borderWidth: '1px' };\n`);
+ assert.deepEqual(names(page("{ ...{ [`a\r\nb`]: bad }, 'a\\r\\nb': { color: 'red' } }")), ['unread-style-object']);
+ assert.deepEqual(names(page("{ ...{ [`a\rb`]: bad }, 'a\\rb': { color: 'red' } }")), ['unread-style-object']);
+ assert.deepEqual(names(page("{ ...{ [`a\r\nb`]: bad }, 'a\\nb': { color: 'red' } }")), []);
+ assert.deepEqual(names(page("{ ...{ [`a\rb`]: bad }, [`a\nb`]: { color: 'red' } }")), []);
+ // The page text below holds U+2028 and U+2029 themselves (the test's own string escapes put them there), not the escape `\u2028`.
+ assert.deepEqual(names(page("{ ...{ [`a\u2028b`]: bad }, 'a\\nb': { color: 'red' } }")), ['unread-style-object']);
+ assert.deepEqual(names(page("{ ...{ [`a\u2029b`]: bad }, 'a\\nb': { color: 'red' } }")), ['unread-style-object']);
+ assert.deepEqual(names(page("{ ...{ [`a\u2029b`]: bad }, 'a\u2029b': { color: 'red' } }")), []);
+ assert.deepEqual(names(page("{ ...{ [`a\u2028b`]: bad }, 'a\\u2028b': { color: 'red' } }")), []);
+ // A backslash before a line break is a continuation, which adds nothing, whichever line break follows it.
+ assert.deepEqual(names(page("{ ...{ [`a\\\r\nb`]: bad }, ab: { color: 'red' } }")), []);
+ assert.deepEqual(names(page("{ ...{ [`a\\\rb`]: bad }, ab: { color: 'red' } }")), []);
+});
+
+// What a spread or a prototype brings into an object is that object's own: slots where it holds slots, keys where it holds keys. `__proto__: …` written as a name
+// or a string sets the prototype, and `for … in` reads what the prototype holds; a computed `['__proto__']` is an ordinary key.
+test('griffel-styles: a spread or a prototype adds members at the level it is written — slots beside slots, keys beside keys', () => {
+ assert.deepEqual(names(styles('{ ...{ root: base } }')), ['unread-style-object']);
+ assert.deepEqual(names(styles("{ ...{ all: { color: 'red' } } }")), [], 'a slot called all, brought in by a spread, is a slot');
+ assert.deepEqual(names(styles("{ ...(c ? { root: { borderColor: 'x' } } : { other: base }) }")), ['borderColor', 'unread-style-object']);
+ assert.deepEqual(names(styles('{ __proto__: { root: base } }')), ['unread-style-object']);
+ assert.deepEqual(names(styles("{ '__proto__': { root: { borderStyle: 'solid' } } }")), ['borderStyle']);
+ assert.deepEqual(names(styles("{ __proto__: null, root: { color: 'red' } }")), []);
+ assert.deepEqual(names(styles("{ root: { __proto__: { borderWidth: '1px' } } }")), ['borderWidth']);
+ assert.deepEqual(names(styles("{ root: { ['__proto__']: { color: 'red' } } }")), []);
+ // A computed `['__proto__']` at the level of slots is a slot of that name, and `all` in its object is a key Griffel drops.
+ assert.deepEqual(names(styles("{ ['__proto__']: { all: { color: 'red' } } }")), ['all']);
+ const [proto] = griffelStyleProblems(styles('{ __proto__: slots }')).problems;
+ assert.match(proto.message, /^the prototype set here \(__proto__: slots\) adds keys the check cannot read/);
+});
+
+// An object holds, for each key, its LAST definition — a later one replaces an earlier one, a spread's keys included — and its own keys hide the prototype's of the
+// same name; a spread copies only its object's own keys. A definition that cannot reach Griffel is not checked; one that may (a spread a condition chooses, a key
+// computed at run time) is never taken to replace anything.
+test('griffel-styles: what an object holds is resolved as JavaScript resolves it — the last definition, own keys before inherited ones', () => {
+ assert.deepEqual(names(styles("{ ...{ root: base }, root: { color: 'red' } }")), [], 'a slot a later one replaces');
+ assert.deepEqual(names(styles("{ __proto__: { root: base }, root: { color: 'red' } }")), [], 'a prototype slot an own one hides');
+ assert.deepEqual(names(styles("{ ...{ __proto__: { root: base }, other: { color: 'red' } } }")), [], 'a spread copies no prototype');
+ assert.deepEqual(names(styles("{ __proto__: { __proto__: { root: base }, root: { color: 'red' } } }")), [], 'a prototype chain');
+ assert.deepEqual(names(styles("{ root: { borderWidth: 1 }, root: { color: 'red' } }")), [], 'a repeated key: the last one');
+ assert.deepEqual(names(styles("{ root: { color: 'red' }, root: { borderWidth: 1 } }")), ['borderWidth']);
+ assert.deepEqual(names(styles("{ ...{ 0x10: base }, '16': { color: 'red' } }")), [], '0x10 and "16" are one key');
+ assert.deepEqual(names(styles("{ root: { __proto__: { borderColor: 'x' }, borderColor: 'y' } }")), ['borderColor'], 'one key, not two');
+ // What may still reach Griffel is checked: a spread a condition chooses replaces nothing, nor does a key computed at run time; a later conditional one is
+ // itself checked.
+ assert.deepEqual(names(styles("{ root: base, ...(c && { root: { color: 'red' } }) }")), ['unread-style-object']);
+ assert.deepEqual(names(styles("{ ...(c && { root: base }), root: { color: 'red' } }")), []);
+ assert.deepEqual(names(styles("{ root: base, [k]: { color: 'red' } }")), ['unread-style-object']);
+ assert.deepEqual(names(styles("{ root: { borderColor: 'x' }, ...(c ? { root: { color: 'red' } } : {}) }")), ['borderColor']);
+ // A ternary whose other branch is a trusted helper spreads one object, but only when the condition holds; a template key, however alike two are, is computed
+ // at run time; and an object in a value the check cannot read (a call's argument) is not certainly spread.
+ assert.deepEqual(names(`${IMPORT.replace('tokens', 'shorthands, tokens')}const useStyles = makeStyles({ root: { ':hover': hover, ...(c ? { ':hover': { color: 'red' } } : shorthands.padding('1px')) } });\n`),
+ ['unread-style-object']);
+ assert.deepEqual(names(styles("{ root: { [`:${s}`]: hover, [`:${s}`]: { color: 'red' } } }")), ['unread-style-object']);
+ assert.deepEqual(names(styles("{ root: base, ...pick({ root: { color: 'red' } }) }")), ['unread-style-object', 'unread-style-object']);
+});
+
+// A computed key names what its expression is at run time, which may be any of the ten — or a selector, whose object Griffel reads. One the check cannot read as a
+// string is held, not guessed at, unless it is a template whose text before its first `${` no one of the ten begins with: then what it is can be told from that start.
+test('griffel-styles: a computed key the check cannot read is held, unless its literal start shows it is none of the ten', () => {
+ const held = [
+ "[prop]: 'x'",
+ "['border' + 'Width']: 'x'",
+ "[('borderWidth')]: 'x'",
+ "[String.raw`borderWidth`]: 'x'",
+ "[`border${side}Width`]: 'x'",
+ "[`${prefix}Color`]: 'x'",
+ "[`\\u0062order${side}`]: 'x'",
+ "[selector]: hover",
+ "[1 + 1]: { color: 'red' }",
+ ];
+ for (const member of held) assert.deepEqual(names(styles(`{ root: { ${member}, color: 'red' } }`)), ['unread-style-object'], member);
+ // A template that starts like a selector or an at-rule may hold a style object: one written inline is read, and one written elsewhere is reported.
+ assert.deepEqual(names(styles("{ root: { [`& .${iconClassName}`]: { borderColor: 'x' }, [`@media (min-width: ${width}px)`]: { color: 'red' } } }")), ['borderColor']);
+ for (const start of [':', '[', '>', '&', '@']) assert.deepEqual(names(styles(`{ root: { [\`${start}\${state}\`]: hover } }`)), ['unread-style-object'], start);
+ // A `\${` is text, not a substitution: the key is that string.
+ assert.deepEqual(names(styles('{ root: { [`--a\\${b}`]: c } }')), []);
+ // A slot's key is not a property, so a computed slot name is not held; its object is read as any slot's is.
+ assert.deepEqual(names(styles("{ [slot]: { color: 'red' }, [`${name}Root`]: { borderStyle: 'solid' } }")), ['borderStyle']);
+ assert.deepEqual(names(styles('{ [slot]: base }')), ['unread-style-object']);
+ // The problem names the key as it is written, and both ways out.
+ const [key] = griffelStyleProblems(styles("{ root: { [selector]: hover } }")).problems;
+ assert.deepEqual(key.within, ['root', '[…]']);
+ assert.match(key.message, /^the key \[selector\] is computed, so the check cannot tell what it names: it may be a property Griffel drops, or a selector/);
+});
+
+// A number is a key too, and a slot may be called by one: its object is read as any slot's is.
+test('griffel-styles: a numeric key is read — as a slot, and as a key that is none of the ten', () => {
+ assert.deepEqual(names(styles("{ 0: { borderWidth: '1px' }, 1.5: hidden }")), ['borderWidth', 'unread-style-object']);
+ assert.deepEqual(names(styles("{ 0x1F: { color: 'red' }, .5: { borderColor: 'x' }, 1_000n: { color: 'red' }, 1e3: { ':hover': { borderStyle: 'solid' } } }")),
+ ['borderColor', 'borderStyle']);
+ assert.deepEqual(names(styles("{ root: { 0: { borderColor: 'x' }, 100: 'red' } }")), ['borderColor']);
+});
+
+test('griffel-styles: the value is never looked at — the key alone is what Griffel refuses', () => {
+ // resolveStyleRules tests the key before the value, so even an empty value is dropped with a console error.
+ for (const value of ["'0'", '0', 'undefined', 'null', 'tokens.strokeWidthThin', '`${x}px`', "cond ? 'a' : 'b'", "fn(1, 'two', [3])", '{ nested: true }']) {
+ assert.deepEqual(names(styles(`{ root: { borderWidth: ${value}, color: 'red' } }`)), ['borderWidth'], value);
+ }
+});
+
+// ─── Depth ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+test('griffel-styles: keys are found at any depth — pseudo selectors, at-rules, child selectors, several slots', () => {
+ const cases = [
+ ["{ root: { ':hover': { borderColor: 'red' } } }", ['borderColor']],
+ ["{ root: { '&:focus-visible': { borderStyle: 'solid' } } }", ['borderStyle']],
+ ["{ root: { '@media (min-width: 600px)': { borderWidth: 1 } } }", ['borderWidth']],
+ ["{ root: { '@media screen': { ':hover': { borderInline: 'x' } } } }", ['borderInline']],
+ ["{ root: { '@supports (display: grid)': { borderBlock: 'x' } } }", ['borderBlock']],
+ ["{ root: { '@container (min-width: 20em)': { borderBlockStart: 'x' } } }", ['borderBlockStart']],
+ ["{ root: { '@layer base': { borderBlockEnd: 'x' } } }", ['borderBlockEnd']],
+ ["{ root: { '& .child': { all: 'unset' } } }", ['all']],
+ ["{ root: { ' > span': { borderInlineStart: 'x' } } }", ['borderInlineStart']],
+ ["{ root: { 'a': { 'b': { 'c': { 'd': { 'e': { borderInlineEnd: 'x' } } } } } } }", ['borderInlineEnd']],
+ ["{ one: { color: 'red' }, two: { padding: 1, ':hover': { borderWidth: 2 } }, three: { borderColor: 'x' } }", ['borderWidth', 'borderColor']],
+ ["{ root: { borderWidth: 1, ':hover': { borderWidth: 2 }, '@media screen': { borderWidth: 3 } } }", ['borderWidth', 'borderWidth', 'borderWidth']],
+ ];
+ for (const [slots, expected] of cases) assert.deepEqual(names(styles(slots)), expected, slots);
+});
+
+test('griffel-styles: an object written in a spread, a ternary or a call argument is a style object once Griffel has it', () => {
+ const cases = [
+ ["{ root: { ...(narrow && { borderColor: 'red' }) } }", ['borderColor']],
+ ["{ root: { ...(narrow ? { borderBlock: 'x' } : { borderInline: 'y' }) } }", ['borderBlock', 'borderInline']],
+ ["{ root: { ...{ borderStyle: 'solid' } } }", ['borderStyle']],
+ // The argument is read; what the call returns is a style object the check cannot see, so that is reported too.
+ ["{ root: { ...pick({ borderWidth: 1 }) } }", ['unread-style-object', 'borderWidth']],
+ ];
+ for (const [slots, expected] of cases) assert.deepEqual(names(styles(slots)), expected, slots);
+});
+
+// A style object the checker cannot see may hold any of the ten, so it is reported wherever it is, never passed as clean: written elsewhere and passed to a slot or a
+// selector, or spread in. Only Fluent's own helpers, imported from a Griffel module, are spread without their keys being read: shorthands.*(…) writes longhands, and
+// typographyStyles.* holds font longhands only.
+test('griffel-styles: a style object the check cannot see is reported — a slot\'s, a selector\'s, a spread — and Fluent\'s imported helpers are not', () => {
+ const HELPERS = "import { makeStyles, shorthands, tokens, typographyStyles } from '@fluentui/react-components';\n";
+ const cases = [
+ ['{ root: base }', ['unread-style-object']],
+ ['{ root }', ['unread-style-object']],
+ ["{ ...baseSlots, root: { color: 'red' } }", ['unread-style-object']],
+ ["{ root: { ':hover': hover } }", ['unread-style-object']],
+ ["{ root: { '@media (min-width: 600px)': wide, '& .row': { color: 'red' } } }", ['unread-style-object']],
+ ['{ root: { ...base } }', ['unread-style-object']],
+ ["{ root: { ...helper('red') } }", ['unread-style-object']],
+ ["{ root: { ...(b || { color: 'red' }) } }", ['unread-style-object']],
+ ["{ root: { ...(b ?? { color: 'red' }) } }", ['unread-style-object']],
+ ["{ root: { ...(n ? base : { color: 'red' }) } }", ['unread-style-object']],
+ ["{ root: { ...(n ? { color: 'red' } : base) } }", ['unread-style-object']],
+ ["{ root: { ...(n && base) } }", ['unread-style-object']],
+ // `a || b && { … }` is `a || (b && { … })`: the value can be `a`.
+ ["{ root: { ...(a || b && { color: 'red' }) } }", ['unread-style-object']],
+ // Read in full: an inline object, or inline objects chosen by a condition, in parentheses or with a TypeScript assertion after one; a property holding a variable is a
+ // value, not a style object, and so is a custom property computed from a template.
+ ["{ root: { ...(n && { color: 'red' }), ...(n ? { color: 'red' } : m ? { color: 'blue' } : { color: 'green' }), ...({ color: 'red' }) } }", []],
+ ["{ root: { color: 'red' } as const, other: { color: 'red' } satisfies GriffelStyle, more: ({ color: 'red' }) }", []],
+ ["{ root: { color: c, '--brand': c, WebkitAppearance: c, '-webkit-tap-highlight-color': c, ':hover': { color: c } } }", []],
+ ['{ root: { [`--${name}`]: c } }', []],
+ // A computed key the check cannot read may be a selector as well as one of the ten: held.
+ ['{ root: { [key]: c } }', ['unread-style-object']],
+ ["{ root: { ...(a || b ? { color: 'red' } : { color: 'blue' }) } }", []],
+ ["{ root: { ...(props?.wide && { color: 'red' }), ...(x?.[0] ? { color: 'red' } : { color: 'blue' }) } }", []],
+ // Fluent's helpers, imported from a Griffel module, are spread as they are…
+ ["{ root: { ...shorthands.borderColor('red'), ...shorthands.border('1px', 'solid', 'red'), ...typographyStyles.body1, ...shorthands.padding(\n tokens.spacingHorizontalS,\n) } }", [], HELPERS],
+ // …and only then: not by a name the page did not import from one, not chained, not at the level of slots.
+ ["{ root: { ...shorthands.borderColor('red'), ...typographyStyles.body1 } }", ['unread-style-object', 'unread-style-object']],
+ ["{ root: { ...shorthands.borderColor('red').x, ...typographyStyles.body1.y, ...typographyStyles['body1'] } }", ['unread-style-object', 'unread-style-object', 'unread-style-object'], HELPERS],
+ ["{ ...shorthands.borderColor('red') }", ['unread-style-object'], HELPERS],
+ ["{ root: { ...shorthands.borderColor('red') } }", ['unread-style-object'], `${HELPERS}import { shorthands } from './mine';\n`],
+ ["{ root: { ...F.shorthands.borderColor('red'), ...F.typographyStyles.body1 } }", [], "import * as F from '@fluentui/react-components';\nimport { makeStyles } from '@fluentui/react-components';\n"],
+ ["{ root: { ...G.shorthands.borderColor('red') } }", ['unread-style-object'], "import * as G from './mine';\nimport { makeStyles } from '@fluentui/react-components';\n"],
+ ];
+ for (const [slots, expected, header] of cases) assert.deepEqual(names(styles(slots, header)), expected, slots);
+ // Each says where it is and what to do: the slot, the selectors and at-rules it sits under, and to write the object inline.
+ const [hover] = griffelStyleProblems(styles("{ root: { ':hover': hover } }")).problems;
+ assert.deepEqual(hover.within, ['root', ':hover']);
+ assert.match(hover.message, /^the style object of ":hover" is not written here \(hover\), so the check cannot read its keys/);
+ const [spread] = griffelStyleProblems(styles('{ root: { ...base } }')).problems;
+ assert.deepEqual(spread.within, ['root', '...']);
+ assert.match(spread.message, /^this spread \(\.\.\.base\) adds keys the check cannot read/);
+ const [slot] = griffelStyleProblems(styles('{ root: base }')).problems;
+ assert.match(slot.message, /^the style object of slot "root" is not written here \(base\)/);
+});
+
+// A helper is trusted by its own export names only. Each is a plain object, so it also answers to every name it inherits from Object.prototype, and those are no
+// helpers: `shorthands.constructor(x)` is `Object(x)`, which hands x back unexpanded, keys, getters and all. (Run against @griffel/core 1.20.3 and
+// @fluentui/react-components 9.74.6: the getter below runs as the spread copies x, and Griffel drops the borderWidth it puts under `:hover`.)
+test('griffel-styles: a Griffel helper is trusted by its own export names only, never by a name it inherits', () => {
+ const HELPERS = "import { makeStyles, shorthands, tokens, typographyStyles } from '@fluentui/react-components';\n";
+ assert.deepEqual(names(styles("{ root: { ...shorthands.constructor({ get color() { Reflect.set(this, ':hover', { borderWidth: '2px', borderTopStyle: 'solid' }); return 'red'; }, ':hover': { color: 'blue' } }) } }", HELPERS)),
+ ['unread-style-object', 'unread-style-object']);
+ // What such a call is given is read as any spread's inline objects are: a shorthand in it is named too.
+ assert.deepEqual(names(styles("{ root: { ...shorthands.constructor({ borderWidth: '2px' }) } }", HELPERS)), ['unread-style-object', 'borderWidth']);
+ // Every name either helper inherits — as this Node defines Object.prototype — by its imported name, an alias or a namespace.
+ for (const name of Object.getOwnPropertyNames(Object.prototype)) {
+ assert.deepEqual(names(styles(`{ root: { ...shorthands.${name}({ color: 'red' }) } }`, HELPERS)), ['unread-style-object'], `shorthands.${name}`);
+ assert.deepEqual(names(styles(`{ root: { ...typographyStyles.${name} } }`, HELPERS)), ['unread-style-object'], `typographyStyles.${name}`);
+ }
+ assert.deepEqual(names(styles("{ root: { ...expand.constructor({ color: 'red' }) } }", "import { makeStyles, shorthands as expand } from '@fluentui/react-components';\n")),
+ ['unread-style-object']);
+ assert.deepEqual(names(styles("{ root: { ...F.shorthands.constructor({ color: 'red' }), ...F.typographyStyles.constructor } }",
+ "import * as F from '@fluentui/react-components';\nimport { makeStyles } from '@fluentui/react-components';\n")), ['unread-style-object', 'unread-style-object']);
+ // A name neither has is held too, until it is added to the list.
+ assert.deepEqual(names(styles("{ root: { ...shorthands.borderBlock('1px'), ...typographyStyles.hero } }", HELPERS)), ['unread-style-object', 'unread-style-object']);
+ // Each of Griffel's 23 helpers and Fluent's 17 typography entries is spread as it is.
+ const helpers = ['border', 'borderLeft', 'borderBottom', 'borderRight', 'borderTop', 'borderColor', 'borderStyle', 'borderRadius', 'borderWidth', 'flex', 'gap',
+ 'gridArea', 'margin', 'marginBlock', 'marginInline', 'padding', 'paddingBlock', 'paddingInline', 'overflow', 'inset', 'outline', 'transition', 'textDecoration'];
+ const entries = ['body1', 'body1Strong', 'body1Stronger', 'body2', 'caption1', 'caption1Strong', 'caption1Stronger', 'caption2', 'caption2Strong', 'subtitle1',
+ 'subtitle2', 'subtitle2Stronger', 'title1', 'title2', 'title3', 'largeTitle', 'display'];
+ const all = [...helpers.map((h) => `...shorthands.${h}('1px')`), ...entries.map((e) => `...typographyStyles.${e}`)].join(', ');
+ assert.deepEqual(names(styles(`{ root: { ${all} } }`, HELPERS)), []);
+ // `transition` given ONE argument that is an array returns what that array's own `reduce` returns (an array can bring its own), so it is trusted only where it
+ // builds its own array: any number of arguments but one, none of them a spread, or one array, string or number written in place. (Run against @griffel/core
+ // 1.20.3: the first page below loses its borderWidth.)
+ const TRANSITION = `${HELPERS}const list: any = [];\nconst c = true;\n`;
+ for (const call of [
+ "shorthands.transition(new (class extends Array { reduce(...args: any[]): any { return { borderWidth: '2px', borderTopStyle: 'solid' }; } })())",
+ "shorthands.transition(Object.setPrototypeOf([], { reduce() { return { color: 'red' }; } }))",
+ 'shorthands.transition(list)',
+ 'shorthands.transition(...list)',
+ "shorthands.transition(...list, '1s')",
+ "shorthands.transition(c ? list : 'inherit')",
+ 'shorthands.transition(list as Map<string, number>)',
+ 'shorthands.transition([list][0])',
+ 'shorthands.transition(list,)',
+ ]) assert.deepEqual(names(styles(`{ root: { ...${call} } }`, TRANSITION)), ['unread-style-object'], call);
+ for (const call of [
+ "shorthands.transition('opacity', '0.2s')",
+ "shorthands.transition('opacity', '0.2s', '0s', 'ease-in')",
+ "shorthands.transition(list, '1s')",
+ "shorthands.transition('inherit')",
+ 'shorthands.transition(`all`)',
+ "shorthands.transition([['opacity', '0.2s'], ['color', '1s', '0s', 'ease']])",
+ "shorthands.transition([['opacity', '0.2s']],)",
+ 'shorthands.transition()',
+ 'shorthands.padding(list)',
+ ]) assert.deepEqual(names(styles(`{ root: { ...${call} } }`, TRANSITION)), [], call);
+});
+
+// What reaches Griffel is the value, whatever wraps it: parentheses, a non-null assertion and a type assertion change nothing at run time, so an object written
+// under them is read — and refused nowhere — while a type after `as` or `satisfies` is never read as a runtime conditional, whatever `?` and `:` it holds.
+test('griffel-styles: the value is read through what changes nothing at run time, and a type never stands for a value', () => {
+ const HELPERS = "import { makeStyles, shorthands, tokens, typographyStyles } from '@fluentui/react-components';\n";
+ const call = (argument, header = HELPERS) => `${header}const useStyles = makeStyles(${argument});\n`;
+ const cases = [
+ // The call's own argument, in parentheses or asserted: read, as written in the call.
+ ["({ root: { color: 'red' } })", []],
+ ["(({ root: { borderWidth: 1 } }))", ['borderWidth']],
+ ["{ root: { color: 'red' } } as const", []],
+ // A non-null assertion.
+ ["{ root: ({ color: 'red' })!, other: { ...({ color: 'red' })! } }", []],
+ // Type arguments after `as`: their commas are the type's, not members of the object (no phantom slot named `boolean`).
+ ["{ root: { color: 'red' } as Style<string, boolean, number>, other: { borderWidth: 1 } as Record<string, Partial<{ a: string }>> }", ['borderWidth']],
+ // A conditional TYPE after `as` or `satisfies` is not a runtime conditional: the value is `hidden`, which the check cannot see.
+ ['{ root: hidden as true extends true ? {} : {} }', ['unread-style-object']],
+ ['{ root: hidden satisfies (true extends true ? {} : {}) }', ['unread-style-object']],
+ // Fluent's helpers compose with what an object does: in parentheses, after a condition, in a branch.
+ ["{ root: { ...(enabled && shorthands.border('1px', 'solid', 'red')), ...(shorthands.padding('4px')), ...(n ? shorthands.borderColor('red') : {}), ...(n ? typographyStyles.body1 : { color: 'red' }) } }", []],
+ // …but a helper is not a slot object.
+ ["{ ...(n && shorthands.borderColor('red')) }", ['unread-style-object']],
+ // A custom property is `--` and any name, and holds a value.
+ ["{ root: { '--brand_color': tokens.colorBrandForeground1, '--x-1_y': c, '--': c } }", []],
+ // The keywords are matched exactly: `Null`, `TRUE`, `False` and `undefined` are names a page can bind to an object.
+ ['{ root: { ...Null, ...TRUE, ...False, ...undefined } }', ['unread-style-object', 'unread-style-object', 'unread-style-object', 'unread-style-object']],
+ ["{ root: { ':hover': 1E3, ':focus': 2e-1, '& .row': null, '@media print': false } }", []],
+ ];
+ for (const [argument, expected] of cases) assert.deepEqual(names(call(argument)), expected, argument);
+});
+
+// A helper is trusted only as Fluent's own, at run time: an import of a type binds nothing then, and a page that declares the name again — a parameter, a variable,
+// a destructured name — has its own object under it, which the check cannot see.
+test('griffel-styles: a helper is trusted only as a value import that the page never declares again', () => {
+ const page = (header, body) => `${header}${body}\n`;
+ const SPREAD = "const useStyles = makeStyles({ root: { ...shorthands.border() } });";
+ const cases = [
+ [page("import { makeStyles, shorthands } from '@fluentui/react-components';\n", SPREAD), []],
+ [page("import type { shorthands } from '@fluentui/react-components';\nimport { makeStyles } from '@fluentui/react-components';\n", SPREAD), ['unread-style-object']],
+ [page("import { makeStyles, type shorthands } from '@fluentui/react-components';\n", SPREAD), ['unread-style-object']],
+ [page("import { makeStyles, shorthands } from '@fluentui/react-components';\n", `function build(shorthands: { border: () => object }) {\n return makeStyles({ root: { ...shorthands.border() } });\n}`), ['unread-style-object']],
+ [page("import { makeStyles, shorthands } from '@fluentui/react-components';\n", `const f = ({ shorthands }) => makeStyles({ root: { ...shorthands.border() } });`), ['unread-style-object']],
+ [page("import { makeStyles, typographyStyles } from '@fluentui/react-components';\n", "const { typographyStyles } = x;\nconst useStyles = makeStyles({ root: { ...typographyStyles.body1 } });"), ['unread-style-object']],
+ // A key of the same name, `{ typographyStyles: t }`, reads like a typed parameter, `(shorthands: T)`, which DOES declare the name: the check does not tell the two
+ // apart, so it takes the trust away for both — the safe answer, which costs a page that does this a rename.
+ [page("import { makeStyles, typographyStyles } from '@fluentui/react-components';\n", "const { typographyStyles: t } = x;\nconst useStyles = makeStyles({ root: { ...typographyStyles.body1 } });"), ['unread-style-object']],
+ // A property of something else named the same is not a declaration of the name.
+ [page("import { makeStyles, shorthands } from '@fluentui/react-components';\n", `const n = theme.shorthands;\n${SPREAD}`), []],
+ // Through a namespace: a value import is trusted, a type-only one is not.
+ [page("import * as F from '@fluentui/react-components';\n", "const useStyles = F.makeStyles({ root: { ...F.shorthands.borderColor('red'), ...F.typographyStyles.body1 } });"), []],
+ [page("import type * as F from '@fluentui/react-components';\nimport { makeStyles } from '@fluentui/react-components';\n", "const useStyles = makeStyles({ root: { ...F.shorthands.border() } });"), ['unread-style-object']],
+ // …and a namespace name the page declares again is no longer the namespace.
+ [page("import * as F from '@fluentui/react-components';\nimport { makeStyles } from '@fluentui/react-components';\n", "const build = (F: any) => makeStyles({ root: { ...F.shorthands.border() } });"), ['unread-style-object']],
+ // `import type from '…'` imports a default named `type`; the clause after it is an ordinary one.
+ [page("import type from './t';\nimport { makeStyles, shorthands } from '@fluentui/react-components';\n", SPREAD), []],
+ ];
+ for (const [source, expected] of cases) assert.deepEqual(names(source), expected, source);
+});
+
+// A cast's type ends where TypeScript ends it, and what follows it is code again: a comparison after a keyword type (`size as number < 10`) is not type
+// arguments and does not swallow the members after it; `X as T && Y` can be Y; a cast in a condition leaves both branches readable; and a read of a helper's name
+// that cannot declare it — a type query, the right of `=` — keeps its trust.
+test('griffel-styles: what follows a cast\'s type is code again, and a read of a helper\'s name keeps its trust', () => {
+ const HELPERS = "import { makeStyles, shorthands, tokens, typographyStyles } from '@fluentui/react-components';\n";
+ const cases = [
+ // A comparison after `as number`, then a spread the check cannot see: still reported, not swallowed into `fontSize`.
+ ["{ root: { fontSize: size as number < 10 ? '12px' : '16px', ...hidden } }", ['unread-style-object']],
+ // A keyword type, a literal type, `this` and `void` take no type arguments, so a `<` after one is a comparison even when a later `>` could close it (here
+ // before a variable named `as`): the members between are read, never jumped as the type's.
+ ["{ root: { fontSize: size as number < 5 ? '12px' : '16px', ...hidden, opacity: 1 > as ? '1' : '0' } }", ['unread-style-object']],
+ ...['number', 'string', 'object', 'undefined', 'null', 'true', 'this'].map((type) => (
+ [`{ root: { fontSize: size as ${type} < 5 ? '12px' : '16px', borderWidth: '1px', opacity: 1 > as ? '1' : '0' } }`, ['borderWidth']])),
+ // …and one followed by a `.` is the first name of a type reference, which does take them.
+ ["{ root: { color: 'red' } as number.Shape<A, B>, other: { borderColor: 'x' } }", ['borderColor']],
+ // After a type NAME, `<` opens type arguments; these are not types, so nothing is jumped, and the selector after them is read.
+ ["{ root: { fontSize: size as Num < 10 ? '12px' : '16px', ':hover': hidden, z: a > b } }", ['unread-style-object']],
+ // `X as T && Y`: the value can be Y.
+ ["{ root: { ...(shorthands.padding('4px') as Record<string, string> && hidden) } }", ['unread-style-object']],
+ ["{ root: { ...(c ? { color: 'red' } : shorthands.padding('1px') as T ? { color: 'blue' } : hidden) } }", ['unread-style-object']],
+ // A cast in a condition, or in a branch: both branches are read.
+ ["{ root: flag as boolean ? { color: 'red' } : { color: 'blue' }, other: c ? { color: 'red' } as T : { color: 'blue' } }", []],
+ ["{ root: { color: 'red' } as const satisfies GriffelStyle }", []],
+ // A cast followed by a comparison is a boolean, not an object.
+ ['{ root: { ...(x as number < 3) } }', ['unread-style-object']],
+ // Only `as const` and a type name, with or without type arguments, are read; any other type makes the value one the check cannot see (no page wrote a cast in
+ // makeStyles at all), and the problem says so.
+ ["{ root: { color: 'red' } as import('x').T<A, B>, other: { color: 'red' } as A | B, more: { color: 'red' } satisfies (typeof x)[] }", ['unread-style-object', 'unread-style-object', 'unread-style-object']],
+ // Text after `as` that is not a type (type arguments that are not types) is never taken for one: what the value is cannot be told.
+ ["{ root: hidden as Num < 10 ? { color: 'red' } : { color: 'blue' } }", ['unread-style-object']],
+ // The comma operator: the value of `({ … } as T, hidden)` is `hidden`.
+ ["{ root: { ...({ color: 'red' } as T, hidden) } }", ['unread-style-object']],
+ ];
+ for (const [slots, expected] of cases) assert.deepEqual(names(styles(slots, HELPERS)), expected, slots);
+ const [cast] = griffelStyleProblems(styles("{ root: { color: 'red' } as A | B }", HELPERS)).problems;
+ assert.match(cast.message, /^the type this value is asserted as \(\{ color: 'red' \} as A \| B\) is not one the check reads — it reads `as const` and a type name/);
+ // A `<` whose `>` comes only after the member's object has closed is no type's: nothing is jumped — the cast is unread, and the member after it is read.
+ assert.deepEqual(names(`${IMPORT}const useStyles = makeStyles({ root: { color: 'red' } as T<A, other: hidden });\nconst later = a > b;\n`),
+ ['unread-style-object', 'unread-style-object']);
+ // Each member is told for its own reason: one after an unread cast is a value written elsewhere, not another cast.
+ const [first, second] = griffelStyleProblems(styles("{ root: { color: 'red' } as A | B, other: hidden }", HELPERS)).problems;
+ assert.match(first.message, /^the type this value is asserted as/);
+ assert.match(second.message, /^the style object of slot "other" is not written here \(hidden\)/);
+ // Type arguments are jumped whole, whatever they hold — a generic function's parameters, a default, a trailing comma.
+ assert.deepEqual(names(styles("{ root: { color: 'red' } satisfies ReturnType<<T extends string>() => { color: T }>, other: { borderWidth: 1 } }", HELPERS)), ['borderWidth']);
+ assert.deepEqual(names(styles("{ root: { color: 'red' } satisfies ReturnType<<T = string,>() => { color: T }> }", HELPERS)), []);
+ // What only looks like the end of a type is not taken for it: a predicate, a constructor, a conditional type — each leaves the value unread, never its type's
+ // `? {} : {}` read as code.
+ for (const type of ['(value: unknown) => value is unknown extends unknown ? {} : {}', 'abstract new () => true extends true ? {} : {}', 'Shape extends infer S extends { color: string } ? S : never']) {
+ assert.deepEqual(names(styles(`{ root: { ...(hidden as unknown as ${type}) } }`, HELPERS)), ['unread-style-object'], type);
+ }
+ // An arrow function's parameter declares its name, whatever comes before it.
+ assert.deepEqual(names(`${HELPERS}const build = (x: unknown) =>\n shorthands => makeStyles({ root: { ...shorthands.border() } });\n`), ['unread-style-object']);
+ assert.deepEqual(names(`${HELPERS}const build: (s: object) => unknown =\n shorthands => makeStyles({ root: { ...shorthands.border() } });\n`), ['unread-style-object']);
+ assert.deepEqual(names(`${HELPERS}const f = (s = shorthands) => s;\nconst useStyles = makeStyles({ root: { ...shorthands.borderColor('red') } });\n`), [], 'a default value is a read');
+ assert.deepEqual(names(`${HELPERS}type Variant = keyof typeof typographyStyles;\nconst useStyles = makeStyles({ root: { ...typographyStyles.body1 } });\n`), [], 'a type query is a read');
+ assert.deepEqual(names("import * as Fluent from '@fluentui/react-components';\nconst { Button } = Fluent;\nconst useStyles = Fluent.makeStyles({ root: { ...Fluent.shorthands.borderColor('red') } });\n"), [],
+ 'the right of `=` is a read');
+});
+
+// The type of an assertion, held against TypeScript's own parser: for each type after `as`, followed by each runtime tail, where TypeScript parses the program
+// without a syntax error, the check either does not read the type (-1: the value is then unread) or ends it exactly where TypeScript's AsExpression type ends —
+// never anywhere else. And the forms it reads (`const`, a name with or without type arguments) are read exactly, before what can follow a type.
+test('griffel-styles: the type of an assertion ends where TypeScript\'s parser ends it', { skip: !process.env.TYPESCRIPT_ORACLE_PATH && 'TYPESCRIPT_ORACLE_PATH is not set' }, () => {
+ const { loadTypescriptOracle } = require('./helpers/typescript-oracle.js');
+ const { assertedTypeEnd } = require('../lib/griffel-styles.js');
+ const ts = loadTypescriptOracle();
+ const TYPES = ['number', 'string', 'boolean', 'any', 'unknown', 'object', 'null', 'undefined', 'void', 'never', 'bigint', 'symbol', 'true', 'false', 'this', 'const',
+ 'number.A', 'number.A<B>', 'T', 'A.B', 'A.B.C<D>', 'Record<string, number>',
+ 'Partial<Record<string, { a?: string; b: number }>>', 'Array<() => void>', 'Map<string, Array<number>>', 'Foo<Bar<Baz>>', 'string[]', 'T[K]', "T['a']",
+ 'Promise<T>[]', 'readonly string[]', '[number, string]', '{ a: string; b?: number }', "'a' | 'b'", "| 'a' | 'b'", 'A & B', 'A & B | C', '& A & B', 'keyof T',
+ 'typeof y', 'typeof y.z', 'keyof typeof y', '(A | B)[]', '() => void', '(a: number) => string', 'new () => T', '<U>(x: U) => U', 'A extends B ? C : D',
+ 'true extends true ? {} : {}', 'A extends B ? C extends D ? E : F : G', '-1', '1e3', '0x1F', '10n', '`t`', 'unique symbol', 'Fluent.GriffelStyle',
+ "Record<'root' | 'item', GriffelStyle>", "Record<'>' | '<', T>", "import('x').T", "import('x').T<A, B>", "import('x')", "typeof import('x')"];
+ // ' < 10 ? a : b, w: 1 > as ? c : d' puts a `>` after the comparison, before a variable named `as`: a type taken to have arguments would close there.
+ const TAILS = ['', ' && y', ' || y', ' ?? y', ' ? a : b', ' < 10 ? a : b', ' < 10 ? a : b, w: 1 > as ? c : d', ' as T', ' satisfies U', ' === y', ' > 2', '\n ',
+ ' /* c */', '\n < 3'];
+ const READ = new Set(['number', 'string', 'boolean', 'any', 'unknown', 'object', 'null', 'undefined', 'void', 'never', 'bigint', 'symbol', 'true', 'false', 'this',
+ 'const', 'number.A', 'number.A<B>', 'T', 'A.B', 'A.B.C<D>',
+ 'Record<string, number>', 'Partial<Record<string, { a?: string; b: number }>>', 'Array<() => void>', 'Map<string, Array<number>>', 'Foo<Bar<Baz>>',
+ 'Fluent.GriffelStyle', "Record<'root' | 'item', GriffelStyle>", "Record<'>' | '<', T>"]);
+ const ENDING = new Set(['', ' && y', ' || y', ' ?? y', ' ? a : b', ' as T', ' satisfies U', '\n ', ' /* c */']);
+ let compared = 0;
+ let exact = 0;
+ for (const type of TYPES) {
+ for (const tail of TAILS) {
+ const code = `const o = { k: x as ${type}${tail}, z: 1 };\n`;
+ const source = ts.createSourceFile('page.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ if (source.parseDiagnostics.length) continue;
+ let cast = null;
+ const visit = (node) => {
+ if (!cast && ts.isAsExpression(node) && node.expression.getText(source) === 'x') cast = node;
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ if (!cast) continue;
+ const end = assertedTypeEnd(code, code.indexOf(' as ') + 3);
+ assert.ok(end === -1 || end === cast.type.end, `${JSON.stringify(code)}: ended at ${end}, TypeScript at ${cast.type.end}`);
+ if (READ.has(type) && ENDING.has(tail)) {
+ assert.strictEqual(end, cast.type.end, `${JSON.stringify(code)}: a form the check reads`);
+ exact += 1;
+ }
+ compared += 1;
+ }
+ }
+ assert.ok(compared >= 400 && exact >= 150, `compared ${compared} programs, ${exact} read exactly`);
+});
+
+// The decisions that settle where a member ends, without the oracle: a form the check reads ends where TypeScript ends it, and anything else is not read (-1).
+test('griffel-styles: an assertion\'s type ends where TypeScript ends it — the cases that decide where a member ends', () => {
+ const { assertedTypeEnd } = require('../lib/griffel-styles.js');
+ const typeOf = (code) => {
+ const from = code.indexOf(' as ') + 3;
+ const end = assertedTypeEnd(code, from);
+ return end === -1 ? -1 : code.slice(from, end).trim();
+ };
+ assert.equal(typeOf('x as Record<string, T> && y'), 'Record<string, T>');
+ assert.equal(typeOf('x as A || y'), 'A', '`||` is code, not a union');
+ assert.equal(typeOf('x as const ? a : b'), 'const', 'a `?` before what can start a type is a runtime conditional');
+ assert.equal(typeOf('x as T ? !a : b'), -1, 'before anything else TypeScript reads the `?` as part of the type');
+ assert.equal(typeOf('x as Fluent.GriffelStyle satisfies U'), 'Fluent.GriffelStyle');
+ assert.equal(typeOf('x as ReturnType<<T extends string = "a",>() => { a: T }>, z'), 'ReturnType<<T extends string = "a",>() => { a: T }>');
+ assert.equal(typeOf('x as T <U>, z'), 'T <U>', 'type arguments may follow a space on the same line');
+ assert.equal(typeOf('x as T\n<U>, z'), -1, 'after a line break TypeScript reads `<` as a comparison, so `<U>` is no part of the type');
+ assert.equal(typeOf("x as Record<'>' | '<', `${'<'}`>, z"), "Record<'>' | '<', `${'<'}`>", 'a quoted `<` or `>` is no bracket');
+ // A keyword type, a literal type, `this` and `void` take no type arguments: a `<` after one is a comparison, and the type ends at the word. A `.` after a keyword
+ // type makes it the first name of a type reference, which takes them.
+ assert.equal(typeOf('x as null, z'), 'null');
+ assert.equal(typeOf('x as this ? a : b'), 'this');
+ assert.equal(typeOf('x as number.A<B>, z'), 'number.A<B>');
+ for (const word of ['number', 'string', 'boolean', 'object', 'undefined', 'never', 'null', 'true', 'false', 'void', 'this', 'const']) {
+ assert.equal(typeOf(`x as ${word} < 10 ? a : b, w: 1 > as ? c : d`), -1, `${word} takes no type arguments`);
+ }
+ // A `<` that a comparison leaves open does not keep a later type's arguments from closing.
+ assert.equal(typeOf('a < b ? c : d; y = x as Map<K, V>, z'), 'Map<K, V>');
+ for (const other of ['x as number < 10 ? a : b', 'x as A | B && y', 'x as T\n < 3', 'x as -1 ? a : b', 'x as A extends B ? C : D, z', 'x as () => void, z',
+ "x as import('y').T<A, B> ? a : b", 'x as Num < 10 ? a : b', 'x as T[]', 'x as T!', 'x as (value: unknown) => value is A']) {
+ assert.equal(typeOf(other), -1, `${JSON.stringify(other)} is not read`);
+ }
+ // Type arguments are a balanced run, read without recursion: deep ones end where they close, and do not exhaust the stack.
+ assert.equal(typeOf(`x as ${'Array<'.repeat(5000)}T${'>'.repeat(5000)}`), `${'Array<'.repeat(5000)}T${'>'.repeat(5000)}`);
+});
+
+// A page nested past anything written by hand still gets an answer — never an exhausted stack or heap: past the depth the check reads, a value is unread and an
+// object is reported as nested too deep.
+test('griffel-styles: a pathologically nested page gets one answer, not an exhausted stack', () => {
+ const deep = 20000;
+ const cases = [
+ `{ root: { color: 'red' } as ${'true extends false ? {} : '.repeat(deep)}{} }`,
+ `{ root: ${'c ? {} : '.repeat(deep)}{} }`,
+ `{ root: ${'('.repeat(deep)}{}${')'.repeat(deep)} }`,
+ `{ root: { ...${'(c && '.repeat(deep)}{}${')'.repeat(deep)} } }`,
+ `{ root: ${"{ ':hover': ".repeat(deep)}{}${' }'.repeat(deep)} }`,
+ ];
+ for (const slots of cases) assert.deepEqual(names(styles(slots)), ['unread-style-object'], slots.slice(0, 60));
+ const [nested] = griffelStyleProblems(styles(`{ root: ${"{ ':hover': ".repeat(100)}{}${' }'.repeat(100)} }`)).problems;
+ assert.match(nested.message, /^this style object is nested deeper than the check reads \(64 levels\)/);
+ assert.deepEqual(names(styles(`{ root: ${"{ ':hover': ".repeat(10)}{ borderWidth: 1 }${' }'.repeat(10)} }`)), ['borderWidth'], 'nesting a page writes is read');
+});
+
+test('griffel-styles: an animation\'s keyframes are not a style object — Griffel serializes them as written', () => {
+ const keyframes = "{ from: { borderColor: 'red' }, to: { borderColor: 'blue' } }";
+ assert.deepEqual(names(styles(`{ root: { animationName: ${keyframes}, animationDuration: '1s' } }`)), []);
+ assert.deepEqual(names(styles(`{ root: { animationName: [${keyframes}, { '0%': { borderWidth: 1 } }], color: 'red' } }`)), []);
+ // …but the key beside it is checked.
+ assert.deepEqual(names(styles(`{ root: { animationName: ${keyframes}, borderColor: 'x' } }`)), ['borderColor']);
+ // A SLOT called animationName is a slot like any other: Griffel reads its object as a style object, so the check does too.
+ assert.deepEqual(names(styles("{ animationName: { borderWidth: '1px' } }")), ['borderWidth']);
+ assert.deepEqual(names(styles('{ animationName: hidden }')), ['unread-style-object']);
+});
+
+test('griffel-styles: a slot may be named like a shorthand — slot names are not properties', () => {
+ assert.deepEqual(names(styles("{ all: { color: 'red' }, borderColor: { padding: 1 }, borderWidth: { margin: 1 } }")), []);
+ assert.deepEqual(names(styles("{ all: { borderWidth: 1 } }")), ['borderWidth']);
+});
+
+// ─── Text is not code ───────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+test('griffel-styles: the same names in a string, comment, template, regex, JSX text or inline style are not reported', () => {
+ const source = [
+ "import * as React from 'react';",
+ "import { makeStyles, tokens } from '@fluentui/react-components';",
+ "import { borderWidth } from './legacy';",
+ '',
+ '// borderWidth: 1 was removed — Griffel drops it',
+ 'const useStyles = makeStyles({',
+ ' root: {',
+ " content: '\"borderWidth\": 1',",
+ " // borderColor: 'red',",
+ " /* borderStyle: 'solid', all: 'unset' */",
+ ' boxShadow: `inset 0 0 0 1px ${tokens.colorNeutralStroke1}`,',
+ " background: 'url(\"borderBlock: x\")',",
+ ' padding: tokens.spacingHorizontalM,',
+ ' },',
+ '});',
+ '',
+ 'const BORDER = /borderWidth:\\s*\\d+/;',
+ 'const theme = { borderColor: "red", borderWidth: 1 };',
+ 'const inline: React.CSSProperties = { borderStyle: "solid", all: "unset" };',
+ `const note = \`borderWidth: \${theme.borderWidth} borderColor: x\`;`,
+ '',
+ 'export default function Page() {',
+ ' const styles = useStyles();',
+ ' return (',
+ ' <div className={styles.root} style={{ borderColor: tokens.colorBrandStroke1, borderWidth: 2, borderBlock: "1px solid" }}>',
+ ' borderWidth: 1 and borderColor: red are text here',
+ ' <span style={{ all: "unset" }}>{BORDER.test(note) ? "borderStyle: dashed" : null}</span>',
+ ' </div>',
+ ' );',
+ '}',
+ '',
+ ].join('\n');
+ const result = griffelStyleProblems(source);
+ assert.equal(result.calls, 1);
+ assert.deepEqual(result.problems, []);
+});
+
+test('griffel-styles: a page with no makeStyles reports nothing, whatever else it holds', () => {
+ const source = "const theme = { borderColor: 'red', borderWidth: 1, all: 'x' };\nexport default function P() { return <div style={theme} />; }\n";
+ assert.deepEqual(griffelStyleProblems(source), { calls: 0, frontier: null, problems: [] });
+ assert.deepEqual(griffelStyleProblems('').problems, []);
+ assert.deepEqual(griffelStyleProblems(null).problems, []);
+});
+
+// ─── Which makeStyles ───────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+test('griffel-styles: makeStyles imported under another name, or as a namespace, from a Griffel module is read', () => {
+ const body = "{ root: { borderWidth: 1 } }";
+ const cases = [
+ ["import { makeStyles as ms } from '@fluentui/react-components';\n", `const s = ms(${body});`],
+ ["import { makeStyles as ms, tokens } from '@griffel/react';\n", `const s = ms(${body});`],
+ ['import { makeStyles as styles } from "@griffel/core";\n', `const s = styles(${body});`],
+ ["import {\n tokens,\n type GriffelStyle,\n makeStyles as ms,\n} from '@fluentui/react-components';\n", `const s = ms(${body});`],
+ ["import * as Fluent from '@fluentui/react-components';\n", `const s = Fluent.makeStyles(${body});`],
+ ["import * as Fluent from '@fluentui/react-components';\n", `const s = Fluent?.makeStyles(${body});`],
+ ["import * as Fluent from '@griffel/react';\n", `const s = Fluent . makeStyles (${body});`],
+ ["import './global.css'\nimport { makeStyles } from '@fluentui/react-components'\n", `const s = makeStyles(${body})`],
+ ['', `const s = makeStyles(${body});`],
+ [IMPORT, `const s = makeStyles<'root'>(${body});`],
+ [IMPORT, `const s = makeStyles <'root' | 'other'> (${body});`],
+ [IMPORT, `export const useStyles = makeStyles(\n ${body},\n);`],
+ ];
+ for (const [header, call] of cases) assert.deepEqual(names(`${header}${call}\n`), ['borderWidth'], `${header}${call}`);
+});
+
+test('griffel-styles: a makeStyles that is somebody else\'s is left alone', () => {
+ const body = "{ root: { borderWidth: 1 } }";
+ const cases = [
+ ["import { makeStyles } from './styles';\n", `const s = makeStyles(${body});`],
+ ["import { makeStyles } from '@mui/styles';\n", `const s = makeStyles(${body});`],
+ ["import { makeStyles as ms } from '@mui/styles';\n", `const s = ms(${body});`],
+ ["import * as Mui from '@mui/styles';\n", `const s = Mui.makeStyles(${body});`],
+ ["import * as Fluent from '@fluentui/react-components';\n", `const s = other.makeStyles(${body});`],
+ ["import * as Fluent from '@fluentui/react-components';\n", `const s = x.Fluent.makeStyles(${body});`],
+ [IMPORT, `const s = this.makeStyles(${body});`],
+ [IMPORT, `const s = notmakeStyles(${body});`],
+ [IMPORT, `const s = makeStylesX(${body});`],
+ [IMPORT, `const s = import('@fluentui/react-components').makeStyles${body};`],
+ ];
+ for (const [header, call] of cases) assert.deepEqual(names(`${header}${call}\n`), [], `${header}${call}`);
+ // A declaration of a function with that name is not a call, whatever its parameters look like.
+ assert.deepEqual(
+ griffelStyleProblems(`${IMPORT}function makeStyles({ borderWidth }) { return 1; }\nfunction* makeStyles({ all }) { yield all; }\n`),
+ { calls: 0, frontier: null, problems: [] },
+ );
+ // Importing the bare name from elsewhere does not hide Griffel's under an alias.
+ const both = "import { makeStyles } from './local';\nimport { makeStyles as real } from '@griffel/react';\n";
+ assert.deepEqual(found(`${both}const a = makeStyles(${body});\nconst b = real(${body});\n`), ['borderWidth@4:26']);
+});
+
+// makeResetStyles takes ONE style object, not slots. The work item names it, but Griffel does not drop these keys there: resolveResetStyleRules writes each key into a
+// single CSS rule as it stands (createStringFromStyles) and never consults UNSUPPORTED_CSS_PROPERTIES, which only resolveStyleRules (makeStyles) does. Running both
+// over `borderColor: 'red'` gives `border-color:red;` for makeResetStyles and a dropped key plus a console error for makeStyles. Refusing a page that works would be a
+// false positive, so the checker leaves it alone; if a Griffel release starts dropping them, add `makeResetStyles` to STYLE_FUNCTIONS (it carries `slots: false`).
+test('griffel-styles: makeResetStyles is not checked, because Griffel does not drop these keys there', () => {
+ assert.deepEqual([...STYLE_FUNCTIONS.keys()], ['makeStyles']);
+ const source = "import { makeResetStyles } from '@fluentui/react-components';\nconst r = makeResetStyles({ borderColor: 'red', borderWidth: 1, ':hover': { borderStyle: 'solid' } });\n";
+ assert.deepEqual(griffelStyleProblems(source), { calls: 0, frontier: null, problems: [] });
+});
+
+test('griffel-styles: several calls are all read, and the problems come in source order', () => {
+ const source = [
+ IMPORT.trimEnd(),
+ "const a = makeStyles({ root: { borderStyle: 'solid' } });",
+ "const b = makeStyles({ root: { padding: 1 } });",
+ "const c = makeStyles({",
+ " root: { ':hover': { borderWidth: 1 }, borderColor: 'x' },",
+ '});',
+ '',
+ ].join('\n');
+ const { calls, problems } = griffelStyleProblems(source);
+ assert.equal(calls, 3);
+ assert.deepEqual(problems.map((p) => `${p.property}@${p.line}:${p.column}`), ['borderStyle@2:32', 'borderWidth@5:23', 'borderColor@5:41']);
+});
+
+// ─── Positions ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+test('griffel-styles: a position is the line and column an editor shows — any line ending, a tab is one column, UTF-16 units, no byte order mark', () => {
+ const lines = [IMPORT.trimEnd(), 'const useStyles = makeStyles({', '\troot: {', '\t\tborderWidth: 1,', '\t},', '});', ''];
+ for (const eol of ['\n', '\r\n', '\r']) assert.deepEqual(found(lines.join(eol)), ['borderWidth@4:3'], JSON.stringify(eol));
+ assert.deepEqual(found(`\uFEFF${lines.join('\r\n')}`), ['borderWidth@4:3'], 'a byte order mark is not a column');
+ assert.deepEqual(found(`\uFEFFconst useStyles = makeStyles({ root: { borderWidth: 1 } });`), ['borderWidth@1:40'], 'nor on the first line, where it would shift the column');
+ // 58 characters before the key, and each of the two emoji is two UTF-16 units: column 62 in an editor, where counting code points would say 60.
+ const astral = `${IMPORT}const label = '😀😀'; const useStyles = makeStyles({ root: { borderWidth: 1 } });\n`;
+ assert.deepEqual(found(astral), ['borderWidth@2:62']);
+});
+
+// ─── What cannot be read ────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+test('griffel-styles: a call whose style object is built elsewhere is reported, never passed as clean', () => {
+ const source = `${IMPORT}const base = { root: { borderWidth: 1 } };\nconst useStyles = makeStyles(base);\nconst other = makeStyles(cond ? a : b);\n`;
+ const result = griffelStyleProblems(source);
+ assert.equal(result.calls, 0);
+ assert.equal(result.notRead, undefined, 'no list of calls left for someone to check by eye');
+ assert.deepEqual(result.problems.map((p) => `${p.code}@${p.line}:${p.column}`), ['unread-style-object@3:19', 'unread-style-object@4:15']);
+ assert.match(result.problems[0].message, /^this makeStyles call is given a style object written elsewhere, so the check cannot read its keys[\s\S]*makeStyles\(\{ … \}\)/);
+ assert.deepEqual(griffelStyleProblems(`${IMPORT}const s = makeStyles();\n`).problems, [], 'a call with no argument has nothing to read');
+});
+
+test('griffel-styles: a call that never closes is reported, not skipped', () => {
+ for (const tail of ["makeStyles({ root: { borderWidth: 1 }", "makeStyles({ root: { borderWidth: 1 } }", 'makeStyles({ root: { color: "red" }, ']) {
+ const result = griffelStyleProblems(`${IMPORT}const useStyles = ${tail}\n`);
+ assert.deepEqual(result.problems.map((p) => `${p.code}@${p.line}:${p.column}`), ['unbalanced-style-call@2:19'], tail);
+ assert.equal(result.calls, 0);
+ }
+});
+
+// The lexer says where it guessed what a `/` or `<` is (source-literals.js, onAmbiguity). `{a: 1} / 2; … /re/` reads as a regex after a block's `}` and as a division
+// after an object literal's, and the lexer takes the regex: everything up to the next `/` on the line is blanked, a makeStyles call included. So nothing at or after
+// the first guess is trusted, as in the navigation oracle (pageref-resolver.js) — a key there is neither reported nor passed.
+const CALL = "const useStyles = makeStyles({ root: { borderWidth: 1 } });";
+const GUESS = 'const o = {a: 1} / 2; const x = /re/;';
+
+test('griffel-styles: a call that lies entirely before the lexer\'s first guess is read as usual', () => {
+ const result = griffelStyleProblems(`${IMPORT}${CALL}\n${GUESS}\n`);
+ assert.equal(result.frontier.kind, 'brace');
+ assert.equal(result.calls, 1);
+ assert.deepEqual(result.problems.map((p) => `${p.property}@${p.line}:${p.column}`), ['borderWidth@2:40']);
+});
+
+test('griffel-styles: a call at or after the first guess cannot be checked for certain', () => {
+ const cases = [
+ ['visible after the guess', `${IMPORT}${GUESS}\n${CALL}\n`, 'unverifiable-style-call@3:19'],
+ ['blanked by the wrong guess', `${IMPORT}const o = {a: 1} / 2; ${CALL} const x = /re/;\n`, 'unverifiable-style-call@2:41'],
+ ['the guess inside the call', `${IMPORT}const useStyles = makeStyles({ root: { width: ({a: 1} / 2) + 'px', borderWidth: 1 } }); const x = /re/;\n`, 'unverifiable-style-call@2:19'],
+ ];
+ for (const [label, source, expected] of cases) {
+ const result = griffelStyleProblems(source);
+ assert.deepEqual(result.problems.map((p) => `${p.code}@${p.line}:${p.column}`), [expected], label);
+ assert.equal(result.calls, 0, label);
+ assert.match(result.problems[0].message, /cannot (?:be checked for certain|tell for certain)/, label);
+ assert.match(result.problems[0].message, /put an operand in parentheses/, label);
+ assert.match(result.problems[0].message, /move the makeStyles call above it/, label);
+ }
+});
+
+test('griffel-styles: a page the lexer guessed on is clean when it holds no makeStyles at all', () => {
+ const result = griffelStyleProblems(`${GUESS}\nexport default function P() { return <div />; }\n`);
+ assert.equal(result.frontier.kind, 'brace');
+ assert.deepEqual(result.problems, []);
+});
+
+// A gate that throws leaves the orchestrator with a stack trace and no JSON, so a page cut off mid-write or garbled anywhere must still get a well-formed answer.
+test('griffel-styles: a page cut off or garbled at any offset still gets a well-formed answer', () => {
+ const page = [
+ IMPORT.trimEnd(),
+ 'const useStyles = makeStyles({',
+ " root: { ':hover': { borderColor: 'red' }, padding: `${a}px`, ...(b && { all: 'unset' }) },",
+ " other: { content: '\"x\"', animationName: { from: { borderWidth: 0 } }, [`border${side}`]: 1 },",
+ '});',
+ 'const re = /a\\/b/g;',
+ 'export default function P() { return <div className={useStyles().root} style={{ borderColor: "red" }}>{`t ${1}`}</div>; }',
+ '',
+ ].join('\n');
+ const noise = ['{', '}', '(', ')', '[', ']', '<', '/', "'", '"', '`', '\\', '$'];
+ const wellFormed = (result, source) => {
+ const lines = source.split(/\r\n|\r|\n/).length;
+ assert.equal(typeof result.calls, 'number');
+ assert.ok(Array.isArray(result.problems));
+ for (const p of result.problems) {
+ assert.ok(Number.isInteger(p.line) && p.line >= 1 && p.line <= lines, `line ${p.line} of ${lines}`);
+ assert.ok(Number.isInteger(p.column) && p.column >= 1, `column ${p.column}`);
+ }
+ for (const p of result.problems) assert.ok(typeof p.code === 'string' && typeof p.message === 'string');
+ };
+ for (let i = 0; i <= page.length; i += 1) {
+ for (const source of [page.slice(0, i), ...noise.map((ch) => page.slice(0, i) + ch + page.slice(i))]) wellFormed(griffelStyleProblems(source), source);
+ }
+});
+
+// ─── Where a key is, and a page against the version that is deployed ──────────────────────────────────────────────────────────────
+
+const within = (source) => griffelStyleProblems(source).problems.map((p) => [p.property, p.within]);
+
+test('griffel-styles: each key reports the slot, selectors and at-rules it sits under — a spread as `...`, a computed key that is not a string as `[…]`', () => {
+ const source = styles("{ root: { borderWidth: 1, ':hover': { borderColor: 'red', '@media (min-width: 1px)': { borderStyle: 'solid' } } }, card: { ...(flag && { borderBlock: 'x' }), '& .child': { all: 'unset' }, [`:focus`]: { borderInline: 'y' }, [name]: { borderBlockEnd: 'z' } } }");
+ assert.deepEqual(within(source), [
+ ['borderWidth', ['root']],
+ ['borderColor', ['root', ':hover']],
+ ['borderStyle', ['root', ':hover', '@media (min-width: 1px)']],
+ ['borderBlock', ['card', '...']],
+ ['all', ['card', '& .child']],
+ ['borderInline', ['card', ':focus']],
+ // The computed key itself is held (it may be one of the ten), and the object written under it is still read.
+ [undefined, ['card', '[…]']],
+ ['borderBlockEnd', ['card', '[…]']],
+ ]);
+ // Two calls, each with its own slots.
+ assert.deepEqual(within(`${styles('{ a: { all: 1 } }')}${styles('{ b: { all: 1 } }').replace(IMPORT, '')}`), [['all', ['a']], ['all', ['b']]]);
+});
+
+test('griffel-styles: griffelProblemsNotIn tells the keys a deployed page already had from the new ones — the same key in the same place first, then the same key anywhere that nothing else has claimed', () => {
+ const found = (source) => griffelStyleProblems(source).problems;
+ const split = (local, deployed) => {
+ const { added, inherited } = griffelProblemsNotIn(found(local), found(deployed));
+ return { added: added.map((p) => `${p.property}@${p.line}`), inherited: inherited.map((p) => `${p.property}@${p.line}`) };
+ };
+ const deployed = styles("{\n root: { borderWidth: 1 },\n hover: { ':hover': { borderColor: 'red' } },\n}");
+ // The page as it is: every key is already there, and nothing is new.
+ assert.deepEqual(split(deployed, deployed), { added: [], inherited: ['borderWidth@3', 'borderColor@4'] });
+ // A key in a place the deployed page had none: the new one, and only it. The keys that were there are inherited whatever line they are on now.
+ assert.deepEqual(split(styles("{\n card: { borderStyle: 'solid' },\n root: { borderWidth: 1 },\n hover: { ':hover': { borderColor: 'red' } },\n}"), deployed), { added: ['borderStyle@3'], inherited: ['borderWidth@4', 'borderColor@5'] });
+ // A slot renamed, a rule moved under another selector: the same key, still dropped, still not new.
+ assert.deepEqual(split(styles("{\n container: { borderWidth: 1 },\n hover: { ':focus': { borderColor: 'red' } },\n}"), deployed), { added: [], inherited: ['borderWidth@3', 'borderColor@4'] });
+ // A second key where there was one is new — and in-place matching takes the key that is where the deployed one was, so the new one is the one named, wherever it comes.
+ assert.deepEqual(split(styles("{\n root: { borderWidth: 1 },\n card: { borderWidth: 2 },\n hover: { ':hover': { borderColor: 'red' } },\n}"), deployed), { added: ['borderWidth@4'], inherited: ['borderWidth@3', 'borderColor@5'] });
+ assert.deepEqual(split(styles("{\n card: { borderWidth: 2 },\n root: { borderWidth: 1 },\n hover: { ':hover': { borderColor: 'red' } },\n}"), deployed), { added: ['borderWidth@3'], inherited: ['borderWidth@4', 'borderColor@5'] });
+ // The same key twice in one object is ONE property — JavaScript keeps the last definition — so it is one key, with the last value: the value the deployed page
+ // had is not new, and another value is. (That each deployed key is spent once is held by the two-hooks case below, and by two slots each with the key.)
+ assert.deepEqual(split(styles("{ root: { borderWidth: 1, borderWidth: 1 } }"), styles("{ root: { borderWidth: 1 } }")), { added: [], inherited: ['borderWidth@2'] });
+ assert.deepEqual(split(styles("{ root: { borderWidth: 2, borderWidth: 1 } }"), styles("{ root: { borderWidth: 1 } }")), { added: [], inherited: ['borderWidth@2'] });
+ assert.deepEqual(split(styles("{ root: { borderWidth: 1, borderWidth: 2 } }"), styles("{ root: { borderWidth: 1 } }")), { added: ['borderWidth@2'], inherited: [] });
+ // The same slot in two makeStyles hooks: counted across the calls, the earlier one is the deployed one.
+ const hook = "{ root: { borderColor: 'red' } }";
+ assert.deepEqual(split(`${styles(hook)}${styles(hook, '')}`, styles(hook)), { added: ['borderColor@3'], inherited: ['borderColor@2'] });
+ // Among keys that cannot be told apart by place, the earlier one is taken as the deployed one: each deployed key is spent once.
+ assert.deepEqual(split(styles("{\n a: { borderWidth: 1 },\n b: { borderWidth: 2 },\n}"), styles("{ root: { borderWidth: 1 } }")), { added: ['borderWidth@4'], inherited: ['borderWidth@3'] });
+ // Nothing deployed (or nothing known of it): every key is new.
+ for (const none of [[], undefined, null]) assert.deepEqual(griffelProblemsNotIn(found(deployed), none).inherited, []);
+ assert.equal(griffelProblemsNotIn(found(deployed), []).added.length, 2);
+ // A key the deployed page had of ANOTHER property does not stand in for it.
+ assert.deepEqual(split(styles("{ root: { borderStyle: 'solid' } }"), styles("{ root: { borderWidth: 1 } }")), { added: ['borderStyle@2'], inherited: [] });
+});
+
+test('griffel-styles: a call the checker cannot read is never "already there", whatever the deployed page had — what it hides cannot be compared', () => {
+ const unreadable = `${IMPORT}${GUESS}\n${CALL}\n`;
+ const problems = griffelStyleProblems(unreadable).problems;
+ assert.deepEqual(problems.map((p) => p.code), ['unverifiable-style-call']);
+ const { added, inherited } = griffelProblemsNotIn(problems, problems);
+ assert.deepEqual(added.map((p) => p.code), ['unverifiable-style-call']);
+ assert.deepEqual(inherited, []);
+ // Mixed with a key, the key can be inherited and the call is still held.
+ const mixed = [...griffelStyleProblems(styles("{ root: { borderWidth: 1 } }")).problems, ...problems];
+ const split = griffelProblemsNotIn(mixed, mixed);
+ assert.deepEqual(split.inherited.map((p) => p.property), ['borderWidth']);
+ assert.deepEqual(split.added.map((p) => p.code), ['unverifiable-style-call']);
+});
+
+const valuesOf = (source) => griffelStyleProblems(source).problems.map((p) => [p.property, p.value]);
+
+test('griffel-styles: each key reports the value it is set to as written — a quoted string by its text, whichever quotes; anything else as its source text with the white space collapsed', () => {
+ // Plain strings: the quotes do not matter, and nor do the comments around the value.
+ assert.deepEqual(valuesOf(styles("{ a: { borderColor: 'red', borderStyle: \"red\", borderWidth: /* c */ 'red' /* d */, all: 'x' } }")), [
+ ['borderColor', '"red"'], ['borderStyle', '"red"'], ['borderWidth', '"red"'], ['all', '"x"'],
+ ]);
+ // An escaped quote is read as the character: 'a\'b' and "a'b" are one string.
+ assert.deepEqual(valuesOf(styles("{ a: { borderColor: 'a\\'b', borderStyle: \"a'b\" } }")), [['borderColor', '"a\'b"'], ['borderStyle', '"a\'b"']]);
+ // Everything else is its text, white space collapsed: nothing is evaluated, so a token is that text whatever it resolves to and a variable is its name.
+ assert.deepEqual(valuesOf(styles("{ a: { borderColor: tokens.colorBrandStroke1, borderStyle:\n tokens .\n colorNeutralStroke1,\n borderWidth: 1, all: `1px ${x}`, borderBlock: 'a' + 'b' } }")), [
+ ['borderColor', 'tokens.colorBrandStroke1'], ['borderStyle', 'tokens . colorNeutralStroke1'], ['borderWidth', '1'], ['all', '`1px ${x}`'], ['borderBlock', "'a' + 'b'"],
+ ]);
+ // A shorthand member writes no value: it is the variable of the same name.
+ assert.deepEqual(valuesOf(styles('{ a: { borderColor } }')), [['borderColor', 'borderColor']]);
+ // A value that is a string with a different meaning is not equal to the text of an expression: "red" the string is not red the variable.
+ assert.notDeepEqual(valuesOf(styles("{ a: { borderColor: 'red' } }")), valuesOf(styles('{ a: { borderColor: red } }')));
+});
+
+test('griffel-styles: a key given ANOTHER value is a new key — a reformat of it, or the same key and value moved to another slot, is not', () => {
+ const found = (source) => griffelStyleProblems(source).problems;
+ const split = (local, deployed) => {
+ const { added, inherited } = griffelProblemsNotIn(found(local), found(deployed));
+ return { added: added.map((p) => `${p.property}@${p.line}`), inherited: inherited.map((p) => `${p.property}@${p.line}`) };
+ };
+ const hover = (value, slot = 'row') => styles(`{\n ${slot}: { ':hover': { borderColor: ${value} } },\n}`);
+ const deployed = hover("'red'");
+ // Another value, in the same place: Griffel drops it just the same, so the page would show none of the change — a new key.
+ for (const value of ["'blue'", 'tokens.colorBrandStroke1', "'red' + x", '`red`', 'red']) assert.deepEqual(split(hover(value), deployed), { added: ['borderColor@3'], inherited: [] }, value);
+ // The same value, written another way: not a change.
+ for (const value of ['"red"', "'red' /* now blue */", "\n 'red'", "'\\x72ed'"]) assert.deepEqual(split(hover(value), deployed), { added: [], inherited: ['borderColor@3'] }, value);
+ // A slot renamed, or the rule moved under another selector, with the value kept: the same key. With the value changed as well: new.
+ assert.deepEqual(split(hover("'red'", 'container'), deployed), { added: [], inherited: ['borderColor@3'] });
+ assert.deepEqual(split(hover("'blue'", 'container'), deployed), { added: ['borderColor@3'], inherited: [] });
+ // Two slots whose values were exchanged: each value is still there once.
+ const two = (a, b) => styles(`{\n a: { borderColor: ${a} },\n b: { borderColor: ${b} },\n}`);
+ assert.deepEqual(split(two("'blue'", "'red'"), two("'red'", "'blue'")), { added: [], inherited: ['borderColor@3', 'borderColor@4'] });
+ // A value used once before and twice now: the second is new, whichever slot it is in.
+ assert.deepEqual(split(two("'red'", "'red'"), styles("{\n a: { borderColor: 'red' },\n}")), { added: ['borderColor@4'], inherited: ['borderColor@3'] });
+});
+
+test('griffel-styles: a refusal and a warning say what a key is, both ways out, and — for a call that cannot be read — that it could not be read', () => {
+ const keys = griffelStyleProblems(styles("{ root: { borderWidth: 1 } }")).problems;
+ const unreadable = griffelStyleProblems(`${IMPORT}${GUESS}\n${CALL}\n`).problems;
+ const command = 'node scripts/check-griffel-styles.js --file <page.tsx>';
+ const build = { surface: 'build', subject: 'page "Detail"', command };
+ const refusal = describeGriffelRefusal(keys, 'detail.tsx', build);
+ assert.ok(refusal.startsWith('page "Detail" writes CSS that Griffel drops at runtime, so the page would deploy without it — detail.tsx:2:'), refusal);
+ assert.ok(refusal.includes(SHORTHAND_REMEDIES));
+ assert.ok(refusal.endsWith('Fix it in the page\'s source (`node scripts/check-griffel-styles.js --file <page.tsx>` lists every one), then re-run.'), refusal);
+ // A note goes before the way on.
+ assert.ok(describeGriffelRefusal(keys, 'detail.tsx', { ...build, note: 'Because.' }).endsWith('Because. Fix it in the page\'s source (`node scripts/check-griffel-styles.js --file <page.tsx>` lists every one), then re-run.'));
+ // The upload's wording, for the same keys.
+ assert.ok(describeGriffelRefusal(keys, 'x.tsx', { surface: 'upload', subject: 'x.tsx', command: 'cmd' }).startsWith('x.tsx writes CSS that Griffel drops at runtime, so the page would deploy without it — refusing to upload. x.tsx:2:'));
+ // Only calls it could not read: no word about CSS that is dropped, and nothing to delete.
+ const onlyUnreadable = describeGriffelRefusal(unreadable, 'detail.tsx', build);
+ assert.ok(onlyUnreadable.startsWith('page "Detail" has makeStyles calls the Griffel check could not read, so it cannot tell whether the page writes CSS that Griffel drops at runtime — detail.tsx:'), onlyUnreadable);
+ assert.doesNotMatch(onlyUnreadable, /Deleting a key|would deploy without it/);
+ assert.ok(onlyUnreadable.endsWith('Change the page\'s source as that says (`node scripts/check-griffel-styles.js --file <page.tsx>` shows what it cannot read), then re-run.'), onlyUnreadable);
+ // Both: the keys first, then the calls — and "them".
+ const both = describeGriffelRefusal([...keys, ...unreadable], 'detail.tsx', build);
+ assert.ok(both.indexOf('`borderWidth` is not supported') < both.indexOf('It also has makeStyles calls the check could not read'), both);
+ assert.ok(both.endsWith('Fix them in the page\'s source (`node scripts/check-griffel-styles.js --file <page.tsx>` lists every one), then re-run.'), both);
+ // The warnings: why the run goes on, per standing.
+ const stands = (standing, surface = 'build') => describeGriffelWarning(keys, 'detail.tsx', { ...build, surface, standing });
+ assert.ok(stands('unchanged').startsWith('page "Detail" is already deployed, and its source is the one the last build recorded for it, so this build sends it again as it is and goes on. It writes CSS that Griffel drops at runtime, so the page renders without it as it does today: detail.tsx:2:'));
+ assert.ok(stands('unrecorded').startsWith('page "Detail" is already deployed, and this workspace holds no record of what the last build sent for it, so the build cannot tell whether this send changes it; it goes on, as builds did before this check. '));
+ assert.ok(stands('inherited', 'upload').startsWith('page "Detail" updates a page that is already deployed, and the deployed page already had these, set the same, so the upload goes on. '));
+ assert.ok(stands('undetermined', 'upload').startsWith('page "Detail" updates a page that is already deployed, and the deployed page could not be read to tell which of these it already had, so the upload goes on. '));
+ for (const [standing, next] of [
+ ['unchanged', 'once the page\'s source changes, the build holds it to the check and stops on anything the check still reports.'],
+ ['unrecorded', 'once a build has recorded this page, a change to its source is held to the check, and the build stops on anything the check still reports.'],
+ ]) assert.ok(stands(standing).includes(SHORTHAND_REMEDIES) && stands(standing).endsWith(`lists every one); ${next}`), standing);
+ for (const [standing, next] of [
+ ['inherited', 'an upload that adds anything the check reports, or sets one of these to another value, is refused.'],
+ ['undetermined', 'when the deployed page can be read, an upload that adds anything the check reports is refused.'],
+ ]) assert.ok(stands(standing, 'upload').endsWith(`lists every one); ${next}`), standing);
+ // A page with only a call the check cannot read has no key to delete, and is told to make the code readable.
+ const readOnly = describeGriffelWarning(unreadable, 'detail.tsx', { ...build, standing: 'unchanged' });
+ assert.ok(readOnly.includes('It has makeStyles calls the Griffel check could not read, so it cannot tell whether the page writes CSS that Griffel drops at runtime: detail.tsx:'), readOnly);
+ assert.doesNotMatch(readOnly, /Deleting a key|renders without it as it does today/);
+ assert.ok(readOnly.endsWith('Edit the page\'s source to make the code readable (`node scripts/check-griffel-styles.js --file <page.tsx>` shows what it cannot read); once the page\'s source changes, the build holds it to the check and stops on anything the check still reports.'), readOnly);
+ // A page with both says so: the keys first, then the calls whose contents it cannot tell.
+ const mixed = describeGriffelWarning([...keys, ...unreadable], 'detail.tsx', { ...build, standing: 'unchanged' });
+ assert.ok(mixed.indexOf('`borderWidth` is not supported') < mixed.indexOf('It also has makeStyles calls the Griffel check could not read, so it cannot tell whether they hold more: detail.tsx:'), mixed);
+ assert.ok(mixed.includes(SHORTHAND_REMEDIES) && mixed.includes('Edit the page\'s source to do either'), mixed);
+});
+
+// ─── The CLI ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+function withPage(source, fn) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'griffel-styles-'));
+ try {
+ const file = path.join(dir, 'page.tsx');
+ fs.writeFileSync(file, source, 'utf8');
+ return fn(file, dir);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+}
+const runCli = (...args) => spawnSync(process.execPath, [SCRIPT, ...args], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
+
+test('check-griffel-styles CLI: exit 0 and one JSON line for a page with nothing unsupported', () => {
+ withPage(styles("{ root: { padding: 1, borderTopWidth: 1, ':hover': { borderBottomColor: 'red' } } }"), (file) => {
+ const res = runCli('--file', file);
+ assert.equal(res.status, 0, res.stderr);
+ assert.equal(res.stdout.split('\n').length, 2, 'one line and its newline');
+ assert.deepEqual(JSON.parse(res.stdout), { ok: true, filePath: path.resolve(file), calls: 1, problems: [] });
+ assert.equal(res.stderr, '');
+ });
+});
+
+test('check-griffel-styles CLI: a style object written elsewhere fails the check (exit 3), never a pass', () => {
+ withPage(`${IMPORT}const styles = { root: { borderWidth: '1px' } };\nconst useStyles = makeStyles(styles);\n`, (file) => {
+ const res = runCli('--file', file);
+ assert.equal(res.status, 3, res.stderr);
+ const out = JSON.parse(res.stdout);
+ assert.equal(out.ok, false);
+ assert.deepEqual(out.problems.map((p) => `${p.code}@${p.line}:${p.column}`), ['unread-style-object@3:19']);
+ });
+});
+
+test('check-griffel-styles CLI: exit 3 with each key\'s property, line, column and longhands', () => {
+ const source = `${IMPORT}const useStyles = makeStyles({\n root: {\n borderWidth: 1,\n ':hover': { borderInline: 'x' },\n },\n});\n`;
+ withPage(source, (file) => {
+ const res = runCli('--file', file);
+ assert.equal(res.status, 3, res.stderr);
+ const out = JSON.parse(res.stdout);
+ assert.equal(out.ok, false);
+ assert.equal(out.filePath, path.resolve(file));
+ assert.equal(out.calls, 1);
+ assert.deepEqual(out.problems.map(({ code, property, line, column, longhands, within, value }) => ({ code, property, line, column, longhands, within, value })), [
+ { code: 'unsupported-shorthand', property: 'borderWidth', line: 4, column: 5, longhands: TEN[3][1], within: ['root'], value: '1' },
+ { code: 'unsupported-shorthand', property: 'borderInline', line: 5, column: 17, longhands: TEN[7][1], within: ['root', ':hover'], value: '"x"' },
+ ]);
+ for (const p of out.problems) assert.equal(typeof p.message, 'string');
+ });
+});
+
+test('check-griffel-styles CLI: a relative path works and the result names the absolute one', () => {
+ withPage(styles("{ root: { borderColor: 'red' } }"), (file, dir) => {
+ const res = spawnSync(process.execPath, [SCRIPT, '--file', 'page.tsx'], { encoding: 'utf8', cwd: dir });
+ assert.equal(res.status, 3);
+ const { filePath } = JSON.parse(res.stdout);
+ assert.ok(path.isAbsolute(filePath), filePath);
+ // The temp folder may be reached through a link or a short name (macOS /var, Windows 8.3), so compare what the two paths resolve to.
+ assert.equal(fs.realpathSync.native(filePath), fs.realpathSync.native(file));
+ });
+});
+
+test('check-griffel-styles CLI: exit 1 when there is no file to check', () => {
+ const missing = path.join(os.tmpdir(), 'griffel-styles-does-not-exist', 'page.tsx');
+ for (const args of [[], ['--file'], ['--file', missing], ['--page', missing]]) {
+ const res = runCli(...args);
+ assert.equal(res.status, 1, JSON.stringify(args));
+ const out = JSON.parse(res.stdout);
+ assert.equal(out.ok, false);
+ assert.equal(typeof out.error, 'string');
+ }
+ assert.match(JSON.parse(runCli().stdout).error, /--file is required/);
+ assert.match(JSON.parse(runCli('--file', missing).stdout).error, /could not be read.*ENOENT/);
+ withPage('', (file, dir) => {
+ const res = runCli('--file', dir);
+ assert.equal(res.status, 1, 'a folder is not a page');
+ assert.equal(JSON.parse(res.stdout).ok, false);
+ });
+});
+
+test('check-griffel-styles CLI: a long result is one complete JSON line — the exit does not cut the output off', () => {
+ // Far more than the 64 KiB a pipe holds: on POSIX, where a pipe's writes are queued, a process.exit() straight after the write would lose the tail.
+ const slots = Array.from({ length: 800 }, (_, i) => `s${i}: { borderWidth: ${i} }`).join(',\n ');
+ withPage(styles(`{\n ${slots},\n}`), (file) => {
+ const res = runCli('--file', file);
+ assert.equal(res.status, 3, res.stderr);
+ assert.ok(res.stdout.length > 200 * 1024, `${res.stdout.length} bytes`);
+ assert.equal(res.stdout.indexOf('\n'), res.stdout.length - 1, 'one line');
+ assert.equal(JSON.parse(res.stdout).problems.length, 800);
+ });
+});
+
+test('check-griffel-styles CLI: checkGriffelStyles returns the exit code and the result the script prints', () => {
+ withPage(styles("{ root: { all: 'unset' } }"), (file) => {
+ const { exit, result } = checkGriffelStyles({ filePath: file });
+ assert.equal(exit, 3);
+ assert.equal(result.ok, false);
+ assert.deepEqual(result.problems.map((p) => p.property), ['all']);
+ });
+ assert.equal(checkGriffelStyles({}).exit, 1);
+ withPage(styles("{ root: { padding: 1 } }"), (file) => assert.equal(checkGriffelStyles({ filePath: file }).exit, 0));
+});
+
+test('check-griffel-styles CLI: a call the checker cannot read for certain fails the check rather than passing it', () => {
+ withPage(`${IMPORT}${GUESS}\n${CALL}\n`, (file) => {
+ const res = runCli('--file', file);
+ assert.equal(res.status, 3);
+ assert.deepEqual(JSON.parse(res.stdout).problems.map((p) => p.code), ['unverifiable-style-call']);
+ });
+});
+
+// ─── Real pages ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+function walk(dir, suffix, out = []) {
+ if (!fs.existsSync(dir)) return out;
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) walk(full, suffix, out);
+ else if (entry.name.endsWith(suffix)) out.push(full);
+ }
+ return out;
+}
+
+// Markdown fences: ``` or ~~~ (three or more), closed by the same fence. The plugin teaches by example, so a sample that put one of these keys in a
+// makeStyles call would be the page-builder copying what this gate then refuses.
+function fencedBlocks(markdown) {
+ const blocks = [];
+ const lines = markdown.split(/\r?\n/);
+ for (let i = 0; i < lines.length; i += 1) {
+ const open = /^\s*(`{3,}|~{3,})/.exec(lines[i]);
+ if (!open) continue;
+ const start = i + 1;
+ let end = start;
+ while (end < lines.length && !lines[end].trimStart().startsWith(open[1])) end += 1;
+ blocks.push({ line: start, body: lines.slice(start, end).join('\n') });
+ i = end;
+ }
+ return blocks;
+}
+
+test('griffel-styles: no code sample in the plugin\'s own instructions teaches a shorthand the gate refuses', () => {
+ let styled = 0;
+ for (const dir of ['references', 'skills', 'agents']) {
+ for (const file of walk(path.join(PLUGIN, dir), '.md')) {
+ for (const block of fencedBlocks(fs.readFileSync(file, 'utf8'))) {
+ if (!/\bmakeStyles\b/.test(block.body)) continue;
+ styled += 1;
+ const { problems } = griffelStyleProblems(block.body);
+ assert.deepEqual(problems.map((p) => `${p.property || p.code}@${p.line}:${p.column}`), [], `${path.relative(PLUGIN, file)}:${block.line}`);
+ }
+ }
+ }
+ assert.ok(styled > 0, 'the plugin has makeStyles samples to check');
+});
+
+test('griffel-styles: the committed pages — every sample the builder copies passes the gate, and the fixtures hold the keys the old `borderWidth` grep missed', (t) => {
+ // Through `git ls-files`, not a directory walk: capture-fixture.test.js creates and deletes transient fixture folders while the suite runs (as source-literals.test.js notes).
+ let pages;
+ try {
+ pages = execFileSync('git', ['ls-files', '-z', '*.tsx'], { cwd: REPO, encoding: 'utf8' }).split('\0').filter(Boolean);
+ } catch {
+ t.skip('not a git checkout');
+ return;
+ }
+ assert.ok(pages.length >= 60, `expected a real corpus, found ${pages.length}`);
+ const oldGrep = /['"]?borderWidth['"]?\s*:/g;
+ const tenNames = new Set(TEN.map(([property]) => property));
+ let keys = 0;
+ let grepHits = 0;
+ const byFile = {};
+ for (const page of pages) {
+ const source = fs.readFileSync(path.join(REPO, page), 'utf8');
+ const { problems } = griffelStyleProblems(source);
+ // A sample is what the page builder is told to copy, so a refusal there would be the plugin teaching what its own gate refuses — or blocking a page that is fine.
+ if (page.startsWith('plugins/model-apps/')) assert.deepEqual(problems, [], page);
+ for (const p of problems) {
+ assert.equal(p.code, 'unsupported-shorthand', `${page}: ${p.message}`);
+ assert.ok(tenNames.has(p.property), `${page}: ${p.property}`);
+ keys += 1;
+ (byFile[page] ||= []).push(p.property);
+ }
+ grepHits += (source.match(oldGrep) || []).length;
+ }
+ // Captured as the model wrote them, so these pages are what the gate is for: the sales dashboard drops four keys (one of them the only one the old grep sees) and the
+ // case wizard a `borderBlockEnd`, which no grep for `borderWidth` could.
+ const dashboard = pages.find((page) => page.endsWith('2-mock-dashboard-real/sales-dashboard.tsx'));
+ const wizard = pages.find((page) => page.endsWith('4-case-wizard/page.tsx'));
+ assert.ok(dashboard && wizard, 'the two captured pages are committed');
+ assert.deepEqual(byFile[dashboard].sort(), ['borderColor', 'borderColor', 'borderColor', 'borderWidth']);
+ assert.deepEqual(byFile[wizard], ['borderBlockEnd']);
+ assert.ok(keys > grepHits, `${keys} keys found, ${grepHits} matched by the old grep`);
+});
+
+// What genpage-upload.js does with a real page: it compares the file with the version that is deployed. A page is never new against itself, however many keys it has and wherever they
+// are, and a key added to it is the one thing that is — checked on the committed pages that hold keys, which are as the model wrote them.
+test('griffel-styles: griffelProblemsNotIn on the committed pages that hold keys — a page is never new against itself, and a key added to it is the only new one', (t) => {
+ let pages;
+ try {
+ pages = execFileSync('git', ['ls-files', '-z', '*.tsx'], { cwd: REPO, encoding: 'utf8' }).split('\0').filter(Boolean);
+ } catch {
+ t.skip('not a git checkout');
+ return;
+ }
+ let held = 0;
+ for (const page of pages) {
+ const source = fs.readFileSync(path.join(REPO, page), 'utf8');
+ const { problems } = griffelStyleProblems(source);
+ if (!problems.length) continue;
+ held += 1;
+ const same = griffelProblemsNotIn(problems, problems);
+ assert.deepEqual(same.added, [], `${page}: nothing is new against itself`);
+ assert.equal(same.inherited.length, problems.length, page);
+ const grown = `${source}\nconst addedStyles = makeStyles({ added: { borderStyle: 'solid' } });\n`;
+ const { added, inherited } = griffelProblemsNotIn(griffelStyleProblems(grown).problems, problems);
+ assert.deepEqual(added.map((p) => [p.property, p.within]), [['borderStyle', ['added']]], `${page}: only the key that was added`);
+ assert.equal(inherited.length, problems.length, `${page}: every key it already had is still its own`);
+ }
+ assert.ok(held >= 2, 'the two captured pages hold keys');
+});
+
+// ─── Size ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+test('griffel-styles: the time grows with the page, not with its square', (t) => {
+ // Each shape at a small and an 8x larger size. The casts: a keyword type before a comparison, a type name whose `<` never closes (TypeScript reads it as type
+ // arguments that never close), and a run of them — each cast's type arguments are looked up, not scanned for to the end of the object, which made these quadratic.
+ const SHAPES = [
+ ['slots', 250, (n) => styles(`{\n${Array.from({ length: n }, (_, i) => (
+ ` s${i}: { color: tokens.colorNeutralForeground${i % 7}, padding: tokens.spacingHorizontalM, margin: tokens.spacingVerticalS, ':hover': { color: tokens.colorBrandForeground1 } },`
+ )).join('\n')}\n}`)],
+ ['casts before a comparison', 500, (n) => styles(`{ root: { ${Array.from({ length: n }, (_, i) => `'--v${i}': size as number < 10 ? '12px' : '16px'`).join(', ')} } }`)],
+ ['unclosed type arguments', 500, (n) => styles(`{ root: { ${Array.from({ length: n }, (_, i) => `'--v${i}': size as Num < 10 ? '12px' : '16px'`).join(', ')} } }`)],
+ ['a run of unclosed casts', 1000, (n) => styles(`{ root: x ${'as T<'.repeat(n)} }`)],
+ ];
+ const medianMs = (fn, runs) => {
+ const times = [];
+ for (let i = 0; i < runs; i += 1) {
+ const start = process.hrtime.bigint();
+ fn();
+ times.push(Number(process.hrtime.bigint() - start) / 1e6);
+ }
+ return times.sort((a, b) => a - b)[Math.floor(runs / 2)];
+ };
+ const calibration = medianMs(() => griffelStyleProblems(SHAPES[0][2](60)), 3);
+ if (calibration > 400) { t.skip(`host too slow to judge scaling (60 slots took ${calibration.toFixed(0)} ms)`); return; }
+ for (const [shape, size, page] of SHAPES) {
+ const small = page(size);
+ const large = page(size * 8);
+ griffelStyleProblems(large);
+ // 8x the size is 8x the time when linear and about 64x when quadratic (a member access that re-reads the text before it did exactly that); the wide margin keeps
+ // the two apart on a busy host, and a pause on one run gets two more tries.
+ let ratio = Infinity;
+ let timings = '';
+ for (let attempt = 0; attempt < 3 && !(ratio < 25); attempt += 1) {
+ const [tSmall, tLarge] = [medianMs(() => griffelStyleProblems(small), 5), medianMs(() => griffelStyleProblems(large), 5)];
+ ratio = tLarge / Math.max(tSmall, 2);
+ timings = `${tSmall.toFixed(1)} -> ${tLarge.toFixed(1)} ms`;
+ }
+ assert.ok(ratio < 25, `${shape}: 8x the size took ${ratio.toFixed(1)}x the time (${timings})`);
+ }
+ assert.equal(griffelStyleProblems(SHAPES[0][2](2000)).calls, 1);
+});
diff --git a/plugins/model-apps/scripts/tests/hardening2-real-bundle.test.js b/plugins/model-apps/scripts/tests/hardening2-real-bundle.test.js
index 6ac07b532..e51c6401b 100644
--- a/plugins/model-apps/scripts/tests/hardening2-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/hardening2-real-bundle.test.js
@@ -29,10 +29,19 @@ async function freshSdk(capture, meta) {
tempDirs.push(dir);
const httpClient = {
get: async (url) => {
- // EntityDefinitions attribute metadata lookup (drives classId/label defaulting on push).
+ // EntityDefinitions attribute metadata lookup (drives classId/label defaulting on push). The SDK reads
+ // only the columns a form binds, as a filtered collection —
+ // EntityDefinitions(LogicalName='new_customer')/Attributes?$select=LogicalName,AttributeType,DisplayName
+ // &$filter=LogicalName eq 'new_name' or LogicalName eq 'new_ownerid'
+ // — answered `{ value: [...] }`; older bundles read the whole entity (`Attributes` on the entity body).
+ // Both shapes are answered so the test pins the defaulting, not the request form.
const m = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);
if (m && meta && meta[m[1]]) {
const attrs = Object.entries(meta[m[1]]).map(([logicalName, AttributeType]) => ({ LogicalName: logicalName, AttributeType }));
+ if (/\)\/Attributes\?/.test(url)) {
+ const asked = [...decodeURIComponent(url).matchAll(/LogicalName eq '([^']+)'/g)].map((x) => x[1]);
+ return { status: 200, headers: {}, body: { value: attrs.filter((a) => asked.includes(a.LogicalName)) } };
+ }
return { status: 200, headers: {}, body: { LogicalName: m[1], EntitySetName: `${m[1]}s`, Attributes: attrs } };
}
return { status: 200, headers: {}, body: {} };
diff --git a/plugins/model-apps/scripts/tests/helpers/angle-frames.js b/plugins/model-apps/scripts/tests/helpers/angle-frames.js
index 87b3f41be..77446ad3b 100644
--- a/plugins/model-apps/scripts/tests/helpers/angle-frames.js
+++ b/plugins/model-apps/scripts/tests/helpers/angle-frames.js
@@ -242,13 +242,39 @@ function signaturePage(frame, head, ending, decoy = DECOYS.string) {
}
const signaturePages = (endings, decoy = DECOYS.string) => SIGNATURE_FRAMES.flatMap(([frameName, frame]) => SIGNATURE_HEADS.flatMap((head) => endings.map((ending) => ({ ...signaturePage(frame, head, ending, decoy), label: `${frameName} / ${head} / ${JSON.stringify(ending)}` }))));
-// The places an element stands.
+// The places an element stands. The third entry says whether a member of a type may begin there (after a `{`, a `,`, a `;`, `return`, `default`, a `?`): where none can — after an `=`, a `(`, a `[`, a `:` or an `=>` — the text of a head
+// with a parameter list that neither `=>` nor `:` follows is an element, for certain, whatever it holds (source-literals.js, NO_MEMBER_BEFORE).
const ELEMENT_FRAMES = [
- ['a declaration', 'const e = @;'], ['an argument', 'f(@);'], ['a property', 'const o = { k: @ };'], ['a child', 'const p = <p>{@}</p>;'], ['a return', 'function g() { return @; }'],
- ['a default export', 'export default @;'], ['a conditional', 'const k = c ? @ : null;'], ['an arrow body', 'const m = items.map((x) => @);'], ['a block', 'if (a) { @ }'], ['an array', 'const l = [@];'],
+ ['a declaration', 'const e = @;', false], ['an argument', 'f(@);', false], ['a property', 'const o = { k: @ };', false], ['a child', 'const p = <p>{@}</p>;', true], ['a return', 'function g() { return @; }', true],
+ ['a default export', 'export default @;', true], ['a conditional', 'const k = c ? @ : null;', true], ['an arrow body', 'const m = items.map((x) => @);', false], ['a block', 'if (a) { @ }', true], ['an array', 'const l = [@];', false],
// A quote on the line after the element: the apostrophe in its text is no string that this quote could close.
- ['a conditional with a string', "const k = c ? @ : 'none';"], ['a template', 'const k = `${@}`;'],
+ ['a conditional with a string', "const k = c ? @ : 'none';", true], ['a template', 'const k = `${@}`;', true],
];
+// The frames where a member of a type may begin at the head, and where none can.
+const MEMBER_ELEMENT_FRAMES = ELEMENT_FRAMES.filter(([, , member]) => member);
+const NO_MEMBER_ELEMENT_FRAMES = ELEMENT_FRAMES.filter(([, , member]) => !member);
+// A tag that no type has — an attribute with a value, an attribute that `extends` does not introduce, a dotted name with an attribute, a fragment — is an element to every reading, and its text opens nothing: a URL, an apostrophe, a back-tick or a
+// comment opener in it, and the elements in it, are text. What stands after its closing tag is read as the code it follows, which is where the nested element's own text must not reach (a link in a hint is one).
+const JSX_ONLY_ELEMENTS = [
+ '<p>(a); <a href="/x">see https://x.y</a></p>', '<p>(a)\n <a href="/x">it\'s https://x.y</a> and <b d="1">that\'s</b>\n</p>', '<p>(a), <a href="/x">`t</a> `u` done</p>', '<p>(a); <a href="/x">/* c</a> more</p>',
+ '<p>(a); <a href="/x">// c</a> more</p>', '<p>(a); <>x // y</> more</p>', '<p>(a)\n <b d>see https://x.y</b>\n</p>', '<p>(a), <A.B x>see https://x.y</A.B></p>', '<p>(a); <a href="/x"><b>https://x.y</b></a></p>',
+ '<p>(a); <a href="/x">x <i>y // z</i> w</a></p>', '<p>(a); <Link href={url}>https://x.y</Link></p>', '<p>(a), <a href="/x">it\'s</a> <a href="/y">https://x.y</a></p>', '<p>(a);\n <a href="/x">https://x.y</a>\n /b</p>',
+ '<p>(a); <a href="/x">x</a> + 1</p>', "<p>(a), <a href='/x'>'q</a> 'r</p>", '<p>(a)\n <a href={url}>https://x.y</a> // not a comment\n</p>',
+ // A keyword that has a value is an attribute: no type has `type="button"`, `for="x"` or `as="span"`, so a link or a button keeps its text JSX text, as a tag with an attribute that is no keyword does.
+ '<p>(a); <button type="button">see https://x.y</button></p>', '<p>(a)\n <label for="x">it\'s https://x.y</label>\n</p>', '<p>(a), <Link as="span" href="/x">`t</Link> `u` done</p>', '<p>(a); <a href="/x" default="y">/* c</a> more</p>',
+ '<p>(a); <Text in="x" weight={w}>// c</Text> more</p>', '<p>(a);\n <button type={kind}>https://x.y</button>\n /b</p>', '<p>(a); <A.B as="x">see https://x.y</A.B></p>',
+];
+// The same, from every keyword TypeScript has (`keywords`, which the oracle lists): a keyword that is the name of an attribute with a value is an attribute's, whatever word comes before it, since no parameter list of a
+// type has a name that another follows without a comma — so no type has the tag, and its text is JSX text.
+function valuedKeywordElements(keywords) {
+ const elements = [];
+ for (const word of keywords) {
+ elements.push(`<p>(a); <a ${word}="v">see https://x.y</a></p>`, `<p>(a), <a ${word}={v}>it's \`t</a> done</p>`, `<p>(a)\n <A.B x ${word}="1">/* c</A.B>\n</p>`, `<p>(a);\n <a x="v" ${word}={v}>// c</a>\n /b</p>`,
+ // In an expression of a member the reading of the text cannot decide for the tag: it is the tag's own words that say whether the text after it is code.
+ `<p>(a); m(b = <a ${word}="v">it's https://x.y</a>)</p>`, `<p>(a); [<A.B x ${word}={v}>\`t</A.B>]: string</p>`);
+ }
+ return elements;
+}
// The elements that stay certain: JSX text that starts with a parenthesis, in every place an element stands, wherever the lexer can tell. The token after the `)` or the closing tag the text reaches says so
// — and a container that holds a string (`{t("label")}`) is no obstacle.
const CERTAIN_ELEMENTS = [
@@ -266,23 +292,202 @@ const CERTAIN_ELEMENTS = [
'<p>(a); // c\n</p>', '<p>(a);\n /* c */ more /* d */</p>', '<p>(a); {t("x")} a/b</p>', "<p>(a); it's a/b</p>", '<p>(a)\n {/* c */}\n</p>', '<p>(a);\n <b>x</b> and/or <i>y</i></p>',
// Prose that no type holds the members of — two names on a line, a name and a `/` — leaves no type for the closing tag to be hidden in, whatever it holds after it.
'<p>(a), see https://x.y</p>', '<p>(a), a b // c </p>', '<p>(a), 1 2 `x ${y} </p>', '<p>(a), see a/b = /re/ </p>',
- // A template or a regex where a member would begin, which no member does (TS1131), and a list that holds no parameters (TS1003 in every signature).
- '<p>(a); `x ${y} </p>', '<p>(a);\n /x </p>', '<li>(1): first</li>', '<p>("a"); // c </p>',
+ // A template or a regex where a member would begin, which no member does (TS1131), a sign or an `=` there, and a list that holds no parameters (TS1003 in every signature).
+ '<p>(a); `x ${y} </p>', '<p>(a);\n /x </p>', '<p>(a), = /re/ </p>', '<p>(a); || /x </p>', '<li>(1): first</li>', '<p>("a"); // c </p>',
// A `/` in the list that divides, or a regex that holds nothing the parenthesis scan misreads; text whose parameters fail before a type, a default or a pattern.
'<span>({done}/{total})</span>', '<span>(press [/] to search)</span>', '<p>(see @/components)</p>',
+ // A label and a type that fails at its second token — a number and a word, an object type whose member is no member, `new` and `import` where a type must follow, an `=` before a closing tag — and an
+ // initializer whose first token is a regex, an element, a template or a division: the `)` that ends the list is found exactly, and a closing tag follows it.
+ '<p>(Size: 10 MB max, <a href="/x">upgrade</a>)</p>', '<p>(Size: -5 px, <b>x</b>)</p>', '<p>(Name: {user.name}, <a href={profile}>edit</a>)</p>', '<p>(Count: {items.length + 1}, <b>x</b>)</p>', '<p>(Mode: new <a href="/x">beta</a>)</p>',
+ '<p>(Mode: new feature, <b>x</b>)</p>', '<p>(Hint: import <a href="/x">docs</a>)</p>', '<p>(Hint: import from <b>CSV</b>)</p>', '<p>(Tip: use <code>=</code>)</p>', '<p>(Tip: <b>a</b> <code>=</code> <b>b</b>)</p>',
+ '<p>(a = /x/)</p>', '<p>(a = /[)]/)</p>', '<p>(a = b/(c))</p>', '<p>(score = 3/5)</p>', '<p>(a = <b>c</b>)</p>', '<p>(Status = <Badge>OK</Badge>)</p>', '<p>(a = `x`)</p>',
+ ...JSX_ONLY_ELEMENTS,
];
-// The same, where the closing tag could be inside a comment, a template or a regex that the text opens, and is not closed before it, and the text before it could be the members of a type: a guess.
-// (A template after a member's colon is a type: `m: \`a${string}\``.) And where the text holds an `=` or a `[` before its `)`, which may start an expression in a parameter list: a guess.
-const GUESSED_ELEMENTS = ['<p>(a); // c </p>', '<p>(a);\n /* c </p>', '<p>(a); m: `x ${y} </p>', '<p>(a), = /re/ </p>', '<p>(a), x // c </p>', '<p>(a),\n see\n x // c </p>', '<p>(a), readonly x // c </p>', '<p>(a);\n see /* c </p>',
- '<p>(a = b/(c))</p>', '<p>(a = /x/)</p>'];
+// The same, where the closing tag could be inside a comment, a template or a regex that the text opens, and is not closed before it, and the text before it could be the members of a type: a guess where a member of a type may begin at the head
+// (MEMBER_ELEMENT_FRAMES), and an element for certain where none can (NO_MEMBER_ELEMENT_FRAMES). A guess in every place: where the text holds an `=` or a `[` before its `)`, which may start an expression in a parameter list.
+// (A template after a member's colon is a type: `m: \`a${string}\``.)
+const HIDDEN_TEXT_ELEMENTS = ['<p>(a); // c </p>', '<p>(a);\n /* c </p>', '<p>(a); m: `x ${y} </p>', '<p>(a), x // c </p>', '<p>(a),\n see\n x // c </p>', '<p>(a), readonly x // c </p>', '<p>(a);\n see /* c </p>'];
+const UNREAD_LIST_ELEMENTS = [
+ // A default whose regex, element or template is not its first token, or a division after something that is no name or number: the scan cannot say where the list ends.
+ '<p>(a = f(/x/))</p>', '<p>(a = (b)/c)</p>', '<p>(a = typeof /x/)</p>', '<p>(a = <b>c</b> / 2)</p>', '<p>(a = `${b}`)</p>'];
+const GUESSED_ELEMENTS = [...HIDDEN_TEXT_ELEMENTS, ...UNREAD_LIST_ELEMENTS];
function elementPage(frame, element, decoy = DECOYS.string) {
const name = /^<([\w.]+)>/.exec(element)[1];
return { code: `${frame.replace('@', element)}\n${decoy.replaceAll('NAME', name)}\n${CALL};\n`, at: frame.indexOf('@'), name };
}
-const elementPages = (elements, decoy = DECOYS.string) => ELEMENT_FRAMES.flatMap(([frameName, frame]) => elements.map((element) => ({ ...elementPage(frame, element, decoy), label: `${frameName} / ${JSON.stringify(element)}` })));
+const elementPages = (elements, decoy = DECOYS.string, frames = ELEMENT_FRAMES) => frames.flatMap(([frameName, frame]) => elements.map((element) => ({ ...elementPage(frame, element, decoy), label: `${frameName} / ${JSON.stringify(element)}` })));
+
+// ─── A parameter list that fails, and a default value that the scan reads exactly ──────────────────────────────────────────────────────────────────────────────
+//
+// The texts that JSX may have after a parenthesis and a label, which a parameter list shares the start of, and that TypeScript rejects as one in a call signature, a construct signature and a function type alike (a number and
+// a word, an object type that is none, `new` and `import` where a type must follow, an `=` before a closing tag); and the defaults whose first token is a regex or an element, a division of a name or a number, and a template with no
+// `${`, which the scan of a parameter list reads exactly (genericFunctionTypeFollows in lib/source-literals.js). Each is put in an element and in a type, with a decoy after it, and TypeScript says which are pages.
+
+// The lists, from every keyword TypeScript has (`keywords`), white space of every kind it skips, and the characters that follow a name in an object type.
+function failingLists(keywords) {
+ const words = [...keywords, 'MB', 'max', 'user', 'count', '\u00e9'];
+ const gaps = [' ', '\n', '\u00a0', '\u0085', '\u2028', '/* c */'];
+ const lists = [];
+ for (const number of ['10', '1.5', '-5']) for (const word of words) lists.push(`Size: ${number} ${word}, <a href="/x">upgrade</a>`);
+ for (const gap of gaps) for (const word of ['MB', 'max', 'in', 'extends']) lists.push(`Size:${gap}10${gap}${word}${gap}max, <b>x</b>`);
+ for (const name of ['user', 'a', 'readonly', 'get', 'set', 'new', 'static', 'break', 'this']) for (const junk of ['.', '+', '-', '*', '%', '&', '|', '^', '!', '~', '/']) lists.push(`Name: {${name}${junk}b}, <a href={profile}>edit</a>`);
+ for (const gap of gaps) for (const junk of ['.', '+', '/']) lists.push(`Name: {a${gap}${junk}${gap}b}, <b>x</b>`);
+ for (const head of ['new', 'import']) {
+ for (const follow of [...words, '<a href="/x">beta</a>', '<a b>', '<a href=', ')', ',', '=', '[', '{', '.meta', '*', '/', '|', '&', '?', ':', '1', '"x"', '`x`']) lists.push(`Mode: ${head} ${follow}, <b>x</b>`);
+ for (const gap of gaps) lists.push(`Mode: ${head}${gap}feature, <b>x</b>`, `Mode: ${head}${gap}<a href="/x">beta</a>`);
+ }
+ for (const gap of gaps) for (const before of ['a = ', 'a: T = ', 'a?: T = ', 'a, b = ', 'Tip: use <code>=', 'Tip: <b>a</b> <code>=']) for (const tag of ['</code>', '</x>', '</ x>', '</>', '</b>']) lists.push(`${before}${gap}${tag}`);
+ return lists;
+}
+// The failing lists that the scan still leaves a guess, and why: a number followed by `extends` (a conditional type, which TypeScript reads on) or by a name that is not ASCII, and a `/` after a modifier (the text of the list
+// is scanned as code, where a regex may follow a contextual word).
+const LEFT_LISTS = /^Size: -?[\d.]+ (?:extends|\u00e9),|^Name: \{(?:readonly|get|set|static)\//;
+
+// Defaults the scan reads exactly, by what their first token is, and the defaults it leaves.
+const EXACT_DEFAULTS = {
+ regex: ['/x/', '/[)]/', '/\\)/', '/(x)/', '/(/', '/[(]/', "/'/", '/"/', '/`/', '/[/]/', '/a\\/b/', '/=/', '/=x/', '/ /', '/\\//', '/x/g', '/x/in', '/x/\u00e9', '/x/*2', '/[/*]/', '/\\/*/',
+ '\n/x/', ' /* c */ /x/', ' // c\n/x/'],
+ element: ['<b>c</b>', '<b/>', '<b />', '<b>)</b>', "<b>it's</b>", '<b>(</b>', '<b x="1">y</b>', '<b x=")">y</b>', '<b x={1}>y</b>', '<b x={")"}>y</b>', '<A.B>y</A.B>', '<b>{")"}</b>', '<b><i>x</i></b>', '<b>`</b>', '<b>/</b>',
+ '<b>//</b>', '<b>/*</b>', '<b x="\\" y=")" />', '<b>\n x\n</b>', "<b x='\"'>y</b>",
+ // A `<` that TypeScript's rule for a `.tsx` file leaves an element whatever follows it: a reserved word, an `extends` and a `>`, a name with an attribute, a name and a `>` and text that starts with a parenthesis.
+ '<class>x</class>', '<this>x</this>', '<T extends>x</T>', '<const T>x</const>', '<b>(x) y</b>'],
+ // An element whose text starts with a parenthesis and a colon: the list is read exactly, but a page that holds it as the code of a signature (`interface I { <T>(a = <b>(x): y</b>) }`) is a guess, because the scan
+ // of the page reads an element there as a call signature that a colon follows, which compiles as JSX text does.
+ elementText: ['<b>(x): y</b>'],
+ template: ['`x`', '`)`', '`(`', '`\\``', '`a b`', '`/`'],
+ division: ['b/(c)', 'b/c', '1/2', 'a/b/c', 'b / c', 'a.b/c', 'a?.b/c', 'x\n/y', '1.5/2'],
+};
+// ... and the defaults the scan leaves: a regex or an element that is not the first token, a `/` after what is no name or number (a comment between them included: a block comment, or a line comment and a line
+// break, where the comment may end in a word and the regex that follows is not the division of it — `1 + // c` and `/[)]/`), a template with a `${`, and anything after a `{`;
+// and an element whose `<` TypeScript reads as the type parameters of a generic arrow (`<T,>`, `<T = X>`, `<T extends X>`, `<const T,>`), where the arrow's own parameter list may hold a closing tag in a string.
+const UNREAD_DEFAULTS = ['f(/x/)', '(b)/c', 'typeof /x/', '<b>c</b> / 2', '/x/ / 2', '`${b}`', 'x ? /y/ : z', '[/x/]', 'b + /x/', '{ k: 1 }/2', '() => { x/2 }', 'function () { x/2 }', 'a[0]/2', 'f()/2', '"s"/2', 'a /* c */ / b',
+ '1 + // c\n/[)]/', 'x || // c\n/\\)/',
+ 'of/x/', 'yield/x/', 'new/x/', 'in/x/', 'return/x/', '<T,>(x) => x', '<T extends X>(x: T) => x', '<await>x</await>', '<b>c</b> + <d/>', '/x/ + /y/',
+ '<T extends X>(x: T = "</T>") => x', '<T,>(x: T = "</T>") => x', '<T = "s">(x: T = "</T>") => x', '<const T,>(x: T = "</const>") => x', '<const T extends X>(x: T = "</const>") => x', '<T extends X = Y>(x: T = "</T>") => x',
+ '<await extends X>(x: T = "</await>") => x', '<yield>x</yield>', '<>x</>', '< b>c</b>'];
+// A regex that its line does not close (TS1161): no program that parses has it as a default, so a list that holds one is JSX text, for certain, in an element and in a type alike.
+const UNTERMINATED_DEFAULTS = ['/x\n', '/x)\n', '/[)\n', '/>\n', '/ x\n', '/\\\n', '/(\n', '/x\r\n', '/x\u2028'];
+// The lists that hold a default, from every default above and the places a default stands, with the text after the list that JSX may have and a type may not, and the endings that a type may have.
+const DEFAULT_LABELS_EXACT = ['a = ', 'a: T = ', 'a?: T = ', 'a, b = ', 'a=', '{ a }: P = ', 'see = '];
+function defaultLists() {
+ const values = [...Object.values(EXACT_DEFAULTS).flat(), ...UNREAD_DEFAULTS, ...UNTERMINATED_DEFAULTS, '/x', '/x)', '/[)', '/>', '/x/)', '/ x', '<b', '`x', '`x${', '"x'];
+ const lists = [];
+ for (const value of values) for (const label of [...DEFAULT_LABELS_EXACT, 'a: A<B> = ', 'cb: <U = ']) lists.push(`${label}${value}`);
+ for (const value of values) lists.push(`a = ${value}, b = ${value}`, `a = 1, b = ${value}`, `a = ${value}, b`, `a = x ${value}`, `a = ${value} y`);
+ return lists;
+}
+// The lists whose default the scan reads exactly (or whose regex it knows is unterminated): the first `=` of the list has the default, and no `<` stands before it.
+const exactDefaultLists = () => DEFAULT_LABELS_EXACT.flatMap((label) => [...Object.values(EXACT_DEFAULTS).flat(), ...UNTERMINATED_DEFAULTS].map((value) => `${label}${value}`));
+
+// ─── A regex after a line comment ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+//
+// The scan of a parameter list reads a `/` after a name or a number as a division, and a block comment ends in a `/`, so a `/` after one stays a possible regex. A line comment ends in whatever its text does, though, and
+// TypeScript skips it as trivia: after `a = 1 + // fallback` and a line break the last word is `fallback`, a name, and the last token is the `+` — so the `/` that begins the next line is a regex, whose `)` is not the one
+// that ends the list:
+// interface I { <T>(a = 1 + // fallback
+// /[)]/); m: '</T>;navigateTo(…);//' }
+// A scan that took that `/` for a division ended the list at the `)` in the regex, and read the string after it as code (lib/source-literals.js, slashFollowsAnOperand). The values below put every place a regex may follow an
+// operator, a keyword or a bracket — and a division after a name or a number, which is as valid — behind a line comment and a line break (`@` is where they go), the comment ending in a name, a number, a `$`, a letter beyond
+// ASCII, a sign, or nothing at all, and the line break of every kind TypeScript has. The regexes hold a `)`, a `>` or a closing tag, which ends a list or an element that took them for code.
+const LINE_COMMENT_GAPS = [' // c\n', ' // x1\n', ' // $\n', ' // 1\n', ' // \u00e9\n', ' //\n', ' // c.\n', ' // a/b\n', ' // c\r\n', ' // c\r', ' // c\u2028', ' // c\u2029', ' /* a */ // b\n', '\n// c\n', ' // c\n // d\n',
+ ' // c /* d\n'];
+const REGEXES_AFTER_COMMENT = ['1 +@/[)]/', 'x ||@/\\)/', 'x &&@/(x)/', 'x ??@/x)/', '!@/[)]/', '-@/\\)/', 'typeof@/[)]/', 'void@/>)/', 'f(@/[)]/)', '(@/[)]/)', 'x ? y :@/\\)/', 'x ?@/[)]/ : y', '[@/\\)/]', 'a, b =@/[)]/'];
+const DIVISIONS_AFTER_COMMENT = ['b@/ (c)', '1@/ 2', 'a.b@/ c', 'f()@/ 2', 'x@/ y / z'];
+const commentedValues = (shapes, gaps = LINE_COMMENT_GAPS) => shapes.flatMap((shape) => gaps.map((gap) => shape.replace('@', gap)));
+// The lists of a parameter list that hold such a default (after a label, and as a second default), and a regex that is the constraint of a function type in a parameter's type: `<U extends /x)/>(b: U) => U` is a type, whose
+// constraint starts no type and is read as an expression.
+const commentedDefaultLists = () => commentedValues([...REGEXES_AFTER_COMMENT, ...DIVISIONS_AFTER_COMMENT]).flatMap((value) => ['a = ', 'a: T = ', 'a?: string, re = '].map((label) => `${label}${value}`));
+const commentedConstraintLists = () => LINE_COMMENT_GAPS.flatMap((gap) => ['/x)/', '/[)]/', '/\\)/', '/>(b: U) => U)/'].map((regex) => `a: <U extends${gap}${regex}>(b: U) => U`));
+// The text after a call signature with no return type is read up to a closing tag (readChildren), where a later member's default holds a regex after a line comment, and the regex — a class holds the `/` of a closing
+// tag — holds the closing tag of the head and the text of a call (`</T>` stands for the head's closing tag, as in the other endings).
+const HOLDING_REGEXES_AFTER_COMMENT = ['1 +@/[</T>;CALL//]/', 'x ||@/[</T>;CALL]/g', 'typeof@/[^</T>;CALL]/', 'x ? y :@/[</T>;CALL//]/'];
+const commentedMemberEndings = () => commentedValues(HOLDING_REGEXES_AFTER_COMMENT).flatMap((value) => [`;\n m(a = ${value.replaceAll('CALL', CALL)}): void`, `\n <U>(a = ${value.replaceAll('CALL', CALL)})`]);
+// Generic arrows after a token that leaves a `<` undecided (`>=`, `in`, `void` and a line break, `<`), whose lists hold such a default: the head is `<T extends X>`, so the arrow or the text of an element is read by the scan.
+const commentedArrowContinuations = () => {
+ const continuations = {};
+ for (const value of commentedValues([...REGEXES_AFTER_COMMENT, ...DIVISIONS_AFTER_COMMENT], [' // c\n', ' // $\n', ' // 1\n', ' // c\r\n', ' // c\u2028'])) {
+ continuations[`an arrow / ${JSON.stringify(value)}`] = `<T extends X>(a = ${value}) => MARK`;
+ continuations[`an arrow with a return type / ${JSON.stringify(value)}`] = `<T extends X>(a = ${value}): T => MARK`;
+ }
+ return continuations;
+};
+
+// ─── Prose with a comment in it ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+//
+// JSX text that starts with a parenthesis and runs over several lines, one of them with a `//` in it — a URL on a line of its own, a label and a URL, a name and a note — and then a line that starts with a `/`, a path:
+// const e = <p>(optional);
+// https://contoso.com
+// /docs</p>;
+// A type that has this text for its members reads `//` as a comment, which is trivia, so the `/` on the last line follows what stands before the comment: the `:` of `https:`, where a type must follow (TS1110), or a name, which a
+// `/` divides in an expression and no type has before a `/` (lib/source-literals.js, typeMembersFail and slashFollowsAnOperand). A lexer that took the last word of the comment for what the `/` follows read the name-and-note lines
+// as a division (the base does), and one that gave up at the comment read every one as a regex that may hold the closing tag, and refused a page that only compiles as an element.
+const PROSE_LEADS = [';', ',', ';\n ', ',\n ', '\n ', '; ', ', '];
+const PROSE_URLS = ['https://contoso.com', 'http://x.y/z', 'ftp://host'];
+// The words before a URL's colon, and before a note: names and keywords. A modifier (`readonly`, `static`, `abstract`) is a name before a `:`, and is read as one wherever a `:` follows it.
+const PROSE_LABELS = ['Docs', 'See', 'url', 'link', 'ref', 'type', 'from', 'as', 'of', 'is', 'new', 'static', 'readonly', 'abstract', 'default', 'in', 'get', '\u00e9'];
+const PROSE_NAMES = ['b', 'name', 'a1', '$x', '_y', '\u00e9', '\u65e5\u672c', '1', 'type', 'from', 'as', 'of', 'is', 'new', 'return', 'typeof', 'void', 'delete', 'else', 'extends', 'implements', 'await', 'yield', 'case', 'do',
+ 'throw', 'instanceof', 'get', 'static', 'readonly'];
+const PROSE_PATHS = ['/b', '/docs', '/ x', '/a/b/c more text'];
+// A line that holds a `//`, by what stands before it: nothing but a URL's scheme and its colon, a label and then a URL, a name and a note.
+const PROSE_COMMENT_LINES = [
+ ...PROSE_URLS,
+ ...PROSE_LABELS.map((label) => `${label}: ${PROSE_URLS[0]}`),
+ ...PROSE_NAMES.flatMap((name) => [`${name} // note`, `${name}// note`]),
+ 'a: b // c', 'x // c // d', 'x /* c */ // d', 'x /* c\n */ // d', 'https://x.y // z',
+];
+// The same text with a first line that holds what the reading of the members of a type reads token by token (typeMembersFail), by what stands before the `//`: it begins with a parenthesis, a bracket, a quote, a tag, an operator or a
+// number with a `.` or an exponent sign, ends in a postfix `!`, a call or an index, or starts with a modifier. In a type each fails where a member begins (TS1131), after a name (TS1005) or at the `/` after the comment (TS1110, TS1131),
+// so only the element compiles, and the base resolved every one of them by the word that ends the comment.
+const PROSE_LINE_CLASSES = {
+ parenthesis: ['(x) // c', '() // c', '(x, y) // c', 'see (x) // c', 'Label: (x) // c', '(x): https://x.y', '(x?: y) // c', '(x = 1) // c', '(...x) // c', '(x)(y) // c', '(a, (b)) // c'],
+ // A `(` that no `)` closes on the line, at a member's start or after a name: a parameter list that no parameter starts (a `/` after the comments, a number, a string), or whose first parameters fail (two names, a name and a `,` and then a
+ // `/`), so no signature has it (TS1138, TS1003, TS1005; parameterListMayStart, parameterSyntaxFails).
+ unclosedParenthesis: ['foo( // note', 'see foo( // note', 'f( // c', '( // c', 'a( // c', 'if ( // c', 'new ( // c', 'readonly ( // c', 'Total (x y // c', 'foo(1 // c', "foo('a' // c", 'f(a b // c', 'f(see docs // c', 'f(a, // c',
+ 'Call api.get( // returns JSON', '(a // c', 'f(x, // c'],
+ // A `=` right after a name, a number, a string or a signature on its line: no member of a type has one (`m = 1` is TS1131, and `m(x) = 1` TS1005; with a `?`, a type or a line break before the `=` the initializer is kept for the checker). The text
+ // after the `=` is read as no member's, whatever it holds.
+ initializer: ['x = // note', '1.5 = // note', "'a' = // note", 'a = b + // note', 'a = b || // note', 'x = [ // note', 'x = (a, // note', 'total = price * qty // per line', 'm(x) = // note', 'type = // note', 'new = // note'],
+ bracket: ['[x] https://contoso.com', '[x] // c', '[] // c', '[1, 2] // c', 'see [x] // c', '[x] y // c', '[x]: https://x.y', '[k: string]: https://x.y', '[x]?: https://x.y', '[x](y) // c', '[a.b] https://x.y',
+ // An index signature starts with a `[`, a name and a `,` or a `:`, whatever follows (isUnambiguouslyIndexSignature), and neither a parameter nor a type starts with a `/`.
+ '[ a, // c', '[ k: // c', '[a,\n // c'],
+ quote: ["'x' // c", '"x" // c', "'x': https://x.y", "'x // c", '"x // c', "'x' y // c", "'a b': https://x.y", '"x"(y) // c', "'it\\'s' // c"],
+ tag: ['<b/> // c', '<b>y</b> // c', '<>y</> // c', '<b /> // c', 'see <b/> // c', '<b>y</b> https://x.y', 'new (x) // c', '<b>(x)</b> // c', '<b>y</b> (x): https://x.y'],
+ operator: ['|| // c', '&& // c', '| // c', '& // c', '= // c', '== // c', '! // c', '? // c', '?? // c', '... // c', '. // c', '@ // c', '# // c', '{} // c', '{ a } // c', '=== x // c', '> // c', '=> // c', '#x // c'],
+ postfix: ['x! // c', 'f() // c', 'x[0] // c', '!x https://x.y', 'x = 1 https://x.y', 'x! y // c', 'x!! // c', 'a[] // c', 'x ! // c', 'x = a b // c', "x = 'a' 'b' // c"],
+ number: ['1.5 https://x.y', '.5 https://x.y', '1. // c', '1e+5 https://x.y', '1.5e+3 // c', '1e-5: https://x.y', '0.5 // c', '1E+3 // c', '1_0e+1 https://x.y', '.5e-3 // c'],
+ modifier: ['readonly https://contoso.com', 'static https://x.y', 'in // note', 'default // note', 'get // note', 'set https://x.y', 'abstract // c', 'declare\n https://x.y', 'readonly static x // c', 'const // c', 'out https://x.y', 'export // c'],
+ // What goes on over a line break, or after a type: `&` and `|` at the start of a line go on a type and not a name or a signature, a `:` there is a type's or TS1005, a type goes on with `.`, `|` and `&`, and a keyword,
+ // a sign or a `,` after a type or where a type must be is TS1005 or TS1110.
+ continuation: ['m\n &"x" // c', '(b, c)\n &"x" // c', '"x" // n\r!\r"x" // n', 'https://x.y\r||\nhttps://x.y/z', "'s'\r\n||\rhttps://x.y", 'in @ // c', 'typeof\r\n:https://x.y', 'm\n : https://x.y', 'a: A\n : B // c', 'a: A\n ? B // c', 'a: A.B, // c', 'a: A | B; // c',
+ 'a: A default // c', 'a: A in // c', 'a:, b // c', 'a: ; b // c', 'a: = 1 // c', 'a: -1, // c', 'a: keyof T, // c', 'a: unique symbol, // c', 'a: A | // c', 'a: A & // c', 'a: A\n || b // c', 'a: ||', 'readonly . // c', 'static * // c'],
+ // A `[` after a `:` or a type, on its line, opens a tuple or an indexed access, whose first type is no `/` (TS1110): the path on the next line is no type's, and no regex that holds the closing tag begins there.
+ tuple: ['Total: [ // note', 'a: A[ // c', 'm: A | [ // c', 'Total: [ /* c */', 'a: B.C[ // c', 'Range: [ // inclusive', 'a?: [ // c', 'a(): [ // c'],
+};
+const PROSE_SHAPED_LINES = Object.values(PROSE_LINE_CLASSES).flat();
+// The lines whose `//` stands behind a token after which a regex may begin and that a type's members can have there: an `[` that nothing closes (a computed name), an initializer's `=` after a `?` or a type (`x? =`, `x: A =`, which the checker, not the
+// parser, objects to) or in a parameter list (`f(a =`), or an operator or a `,` in such an expression. A regex may begin at the `/` of the next line, and the closing tag of the head may be inside it (`<p>(a); [ // note` and a line break, then
+// `/[</p>;navigateTo(…)//]/]: string`: a type, and `<p>(a); [ // note⏎ /[` then `</p>` and the call: an element). Both compile, so the page is a guess where a member of a type may begin at the head, and an element for certain where none can
+// (source-literals.js, NO_MEMBER_BEFORE). The base read the word that ends the comment for the token before the `/`, and resolved them.
+const PROSE_OPEN_LINES = ['[ // note', 'f(a = // note', 'x: A = // note', 'x? = // note', '[ x = // note', 'x: A = b + // note'];
+// The elements: `(a)`, a separator, the line, a path on the next line, and the closing tag after it, on its line or the next.
+const PROSE_ENDS = ['</p>', '\n</p>'];
+function* proseElements({ leads = PROSE_LEADS, lines = PROSE_COMMENT_LINES, paths = PROSE_PATHS, ends = PROSE_ENDS } = {}) {
+ for (const lead of leads) for (const line of lines) for (const path of paths) for (const end of ends) yield `<p>(a)${lead}${line}\n ${path}${end}`;
+}
+// Where the closing tag could be inside the comment, which a type with the same text for its members could hold it in: a guess.
+const PROSE_HIDING_ELEMENTS = ['<p>(a);\n https://x.y</p>', '<p>(a), see: // c </p>', '<p>(a);\n type: // c </p>', '<p>(a)\n b // c </p>', '<p>(a);\n default: // c </p>'];
+// ... and the members of a type that hold the closing tag of the head (`</T>`) in a comment after a name or a label, with a line after it that makes it a type: both programs compile.
+const PROSE_HIDING_ENDINGS = [';\n https: // </T>\n string', ',\n see: // </T>\n T', ';\n name // </T>\n m: 1', ';\n type: // </T>\n string', ';\n default: // </T>\n string', '\n b // </T>\n m: 1', ';\n new // </T>\n m: T',
+ ';\n readonly // </T>\n m: T', ';\n a:\n // </T>\n string', ';\n a: /* </T> */ string', ';\n a: b // </T>\n c: d', ';\n a:\n /* c\n </T> */ b'];
+// Members of a type that read like the prose above and compile, with no closing tag: the type is code, for certain.
+const PROSE_TYPE_ENDINGS = [';\n https: // c\n string', ',\n see: // c\n T', ';\n name // c\n m: T', ';\n a: b // c\n c: d', ';\n type: // c\n string', '\n b\n // c\n m: T'];
module.exports = {
REGEX_BODY, AFTER, AFTER_WITH_CALL, CONTINUATIONS, SEPARATORS, TRIVIA_SEPARATORS, FRAMES, PRODUCER_FRAMES, tokenVocabulary, programsFor, cleanSourceFile, readingAt, isElement,
- CALL, SIGNATURE_FRAMES, SIGNATURE_HEADS, SIGNATURE_ENDINGS, HIDING_ENDINGS, DECOYS, signaturePage, signaturePages, ELEMENT_FRAMES, CERTAIN_ELEMENTS, GUESSED_ELEMENTS, elementPage, elementPages,
+ CALL, SIGNATURE_FRAMES, SIGNATURE_HEADS, SIGNATURE_ENDINGS, HIDING_ENDINGS, DECOYS, signaturePage, signaturePages, ELEMENT_FRAMES, MEMBER_ELEMENT_FRAMES, NO_MEMBER_ELEMENT_FRAMES, JSX_ONLY_ELEMENTS, valuedKeywordElements, CERTAIN_ELEMENTS, GUESSED_ELEMENTS,
+ HIDDEN_TEXT_ELEMENTS, UNREAD_LIST_ELEMENTS, elementPage, elementPages,
+ failingLists, LEFT_LISTS, EXACT_DEFAULTS, UNREAD_DEFAULTS, UNTERMINATED_DEFAULTS, defaultLists, exactDefaultLists,
+ LINE_COMMENT_GAPS, commentedDefaultLists, commentedConstraintLists, commentedMemberEndings, commentedArrowContinuations,
+ PROSE_LEADS, PROSE_URLS, PROSE_LABELS, PROSE_NAMES, PROSE_PATHS, PROSE_COMMENT_LINES, PROSE_LINE_CLASSES, PROSE_SHAPED_LINES, PROSE_OPEN_LINES, PROSE_HIDING_ELEMENTS, PROSE_HIDING_ENDINGS, PROSE_TYPE_ENDINGS, proseElements,
};
diff --git a/plugins/model-apps/scripts/tests/helpers/fake-dataverse.js b/plugins/model-apps/scripts/tests/helpers/fake-dataverse.js
new file mode 100644
index 000000000..ee71aca84
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/fake-dataverse.js
@@ -0,0 +1,301 @@
+'use strict';
+// A small STATEFUL stand-in for the slice of Dataverse that a rebuild of views, charts and forms touches, to be
+// handed to the REAL vendored SDK as its `httpClient`. A test then asserts on what actually went over the wire —
+// request counts by kind, the rows left behind, what was published — rather than on which SDK methods a mock saw.
+//
+// It models just enough of the platform's behaviour for the SDK's own concurrency checks to hold:
+// * every row carries a version; `etag` is `W/"<version>"`, and a PATCH whose `If-Match` is not the current one
+// answers 412, so a write built on a stale copy fails here as it would live;
+// * a row records the version last PUBLISHED (`publishedVersion`), set by a `PublishXml` that names its table, so
+// "was every saved change published?" is a question a test can ask (`unpublished()`);
+// * `solutioncomponents` rows are the components AddSolutionComponent was called for (or seeded), plus one row per
+// table the solution holds (`heldTables`), and the collection pages when `pageSize` is set. The rows are shaped,
+// and left out, the way the platform does it:
+// - a table row is `{ componenttype: 1, objectid: <the table's MetadataId>, rootcomponentbehavior: 0|1|2 }`
+// (0 Include Subcomponents, 1 Do not include subcomponents, 2 Include As Shell Only); any other row carries
+// `rootcomponentbehavior: null`;
+// - the views, forms and charts of a table held with ALL its subcomponents (0) are members without a row of
+// their own — an AddSolutionComponent for one succeeds and leaves nothing behind (measured live: a rebuild of
+// a build-created table found no row for them, and the SDK's own solution reader documents the same);
+// - a table held at 1 or 2, or not held at all, lists such a component only once it was added on its own;
+// - `$select` is honoured, so a read that forgets to select `rootcomponentbehavior` is not handed it.
+//
+// Anything it does not model throws, naming the request — a new SDK read shows up as a loud failure in the test that
+// first needs it, not as a silently empty answer.
+//
+// Wire shapes mirrored (abridged):
+// GET /savedqueries(<id>)?$select=savedqueryid -> ETag header (the row token)
+// GET /savedqueries(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=… -> the row + "@odata.etag"
+// GET /EntityDefinitions(LogicalName='x')?$select=MetadataId,EntitySetName -> the table's metadata
+// GET /solutioncomponents?$select=objectid,componenttype,rootcomponentbehavior&$filter=_solutionid_value eq <id> and (componenttype eq 26 or …)
+// PATCH /savedqueries(<id>)?$select=savedqueryid If-Match, Prefer: return=representation -> 200 + ETag
+// POST /AddSolutionComponent { ComponentId, ComponentType, SolutionUniqueName }
+// POST /PublishXml { ParameterXml: "<importexportxml><entities><entity>x</entity></entities>…" }
+const { randomUUID } = require('node:crypto');
+
+const GUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
+const clone = (value) => JSON.parse(JSON.stringify(value));
+
+// Entity sets the SDK resolves through EntityDefinitions(LogicalName='x')?$select=EntitySetName.
+const SET_NAMES = {
+ savedquery: 'savedqueries',
+ savedqueryvisualization: 'savedqueryvisualizations',
+ systemform: 'systemforms',
+ solution: 'solutions',
+ solutioncomponent: 'solutioncomponents',
+};
+
+// How each row type names its table and its id, so the generic handlers below serve all three.
+const KINDS = {
+ savedqueries: { id: 'savedqueryid', entity: 'returnedtypecode', published: 'view' },
+ systemforms: { id: 'formid', entity: 'objecttypecode', published: 'form' },
+ savedqueryvisualizations: { id: 'savedqueryvisualizationid', entity: 'primaryentitytypecode', published: 'chart' },
+};
+
+// The solution component type of each row type: Saved Query, System Form, Saved Query Visualization.
+const COMPONENT_KIND = { 26: 'savedqueries', 60: 'systemforms', 59: 'savedqueryvisualizations' };
+
+function createFakeDataverse({ entities = {}, solution = { uniqueName: 'ContosoSD' }, pageSize, failSolutionComponentReads = false, heldTables = {}, failTableIdReads = false } = {}) {
+ const solutionId = solution.id || randomUUID();
+ const tables = { savedqueries: new Map(), systemforms: new Map(), savedqueryvisualizations: new Map() };
+ const members = new Set(); // `${componentType}:${lower-case id}`
+ const held = new Map(Object.entries(heldTables)); // table logical name -> rootcomponentbehavior the solution holds it at
+ const entityIds = new Map(); // table logical name -> its MetadataId
+ const requests = [];
+ const publishes = []; // entity logical names, one array entry per PublishXml entity element
+ let denyWrites = null; // (request) => HTTP status | undefined — lets a test make a write fail
+ let failTableIds = failTableIdReads; // answers 500 to a metadata read that asks for `MetadataId`, and to no other
+
+ const entityIdOf = (logical) => {
+ if (!entityIds.has(logical)) entityIds.set(logical, randomUUID());
+ return entityIds.get(logical);
+ };
+
+ const etagOf = (row) => `W/"${row.version}"`;
+ const reply = (status, body, headers = {}) => ({ status, headers, body });
+ const notFound = () => reply(404, { error: { code: '0x80040217', message: 'Does Not Exist' } });
+ const normId = (id) => String(id || '').replace(/[{}]/g, '').toLowerCase();
+
+ // `field eq 'text'` / `field eq 12` / `field eq <guid>` joined by `and`. Parenthesised `or` groups are only
+ // used by the solution-component query, which has its own reader below.
+ function matches(row, filter) {
+ if (!filter) return true;
+ return filter.split(/\s+and\s+/i).every((clause) => {
+ const m = /^\s*([A-Za-z_][\w]*)\s+eq\s+(?:'((?:[^']|'')*)'|(true|false)|(-?\d+)|(\S+))\s*$/.exec(clause);
+ if (!m) throw new Error(`fake-dataverse: cannot evaluate filter clause '${clause}'`);
+ const [, field, text, bool, num, bare] = m;
+ const actual = row[field];
+ if (text !== undefined) return String(actual) === text.replace(/''/g, "'");
+ if (bool !== undefined) return actual === (bool === 'true');
+ if (num !== undefined) return Number(actual) === Number(num);
+ return normId(actual) === normId(bare);
+ });
+ }
+
+ function page(path, rows, query) {
+ if (!pageSize) return reply(200, { value: rows });
+ const skip = Number(query.get('$skiptoken') || 0);
+ const slice = rows.slice(skip, skip + pageSize);
+ if (skip + pageSize >= rows.length) return reply(200, { value: slice });
+ // An ABSOLUTE same-origin link, as Dataverse emits: the SDK refuses to follow a cross-origin one.
+ const next = new URLSearchParams(query);
+ next.set('$skiptoken', String(skip + pageSize));
+ return reply(200, { value: slice, '@odata.nextLink': `${path.base}/api/data/v9.0${path.pathname}?${next.toString()}` });
+ }
+
+ // The solution's rows, shaped as the platform returns them (see the header): one per table it holds, then one per
+ // component that was added on its own. `$select` narrows the columns, and the primary key is always returned.
+ function solutionComponentRows(filter, select) {
+ const solutionMatch = new RegExp(`_solutionid_value eq (${GUID})`, 'i').exec(filter || '');
+ if (!solutionMatch || normId(solutionMatch[1]) !== normId(solutionId)) return [];
+ const types = [...String(filter).matchAll(/componenttype eq (\d+)/g)].map((m) => Number(m[1]));
+ const listed = [
+ ...[...held].map(([logical, behavior]) => ({ objectid: entityIdOf(logical), componenttype: 1, rootcomponentbehavior: behavior })),
+ ...[...members].map((key) => { const [type, id] = key.split(':'); return { objectid: id, componenttype: Number(type), rootcomponentbehavior: null }; }),
+ ];
+ const columns = select ? String(select).split(',').map((name) => name.trim()).filter(Boolean) : null;
+ return listed
+ .filter((row) => !types.length || types.includes(row.componenttype))
+ .map((row) => {
+ const full = { solutioncomponentid: randomUUID(), ...row };
+ if (!columns) return full;
+ return Object.fromEntries(Object.entries(full).filter(([name]) => name === 'solutioncomponentid' || columns.includes(name)));
+ });
+ }
+
+ // The table a view, form or chart belongs to, by the component type AddSolutionComponent was given.
+ function tableOfComponent(type, id) {
+ const kind = COMPONENT_KIND[Number(type)];
+ const row = kind && tables[kind].get(normId(id));
+ return row ? row.data[KINDS[kind].entity] : undefined;
+ }
+
+ function get(path, query) {
+ const p = path.pathname;
+ let m;
+ if ((m = /^\/EntityDefinitions\(LogicalName='([^']+)'\)$/.exec(p))) {
+ // Only a read that asks for the table's MetadataId fails: the rest of the build reads the same endpoint for
+ // attributes and entity sets, and a test about the membership lookup must not break the build around it.
+ if (failTableIds && /(^|,)MetadataId(,|$)/.test(query.get('$select') || '')) return reply(500, { error: { code: '0x80040E14', message: 'simulated failure' } });
+ const logical = m[1];
+ const known = entities[logical] || {};
+ const attributes = Object.entries(known.attributes || {}).map(([LogicalName, AttributeType]) => ({
+ LogicalName, AttributeType, DisplayName: { UserLocalizedLabel: { Label: LogicalName, LanguageCode: 1033 } },
+ }));
+ return reply(200, { LogicalName: logical, MetadataId: entityIdOf(logical), EntitySetName: SET_NAMES[logical] || known.entitySetName || `${logical}s`, ObjectTypeCode: known.objectTypeCode || 10001, Attributes: attributes });
+ }
+ if ((m = new RegExp(`^/(savedqueries|systemforms|savedqueryvisualizations)\\((${GUID})\\)(/Microsoft\\.Dynamics\\.CRM\\.RetrieveUnpublished\\(\\))?$`, 'i').exec(p))) {
+ const row = tables[m[1]].get(normId(m[2]));
+ if (!row) return notFound();
+ const body = { ...clone(row.data), '@odata.etag': etagOf(row) };
+ if (m[3]) return reply(200, body, { etag: etagOf(row) });
+ return reply(200, { [KINDS[m[1]].id]: row.data[KINDS[m[1]].id], '@odata.etag': etagOf(row) }, { etag: etagOf(row) });
+ }
+ if ((m = /^\/(savedqueries|systemforms|savedqueryvisualizations)$/.exec(p))) {
+ const rows = [...tables[m[1]].values()].map((row) => clone(row.data)).filter((data) => matches(data, query.get('$filter')));
+ return page(path, rows, query);
+ }
+ if (p === '/solutions') {
+ return reply(200, { value: matches({ uniquename: solution.uniqueName, solutionid: solutionId }, query.get('$filter')) ? [{ solutionid: solutionId, uniquename: solution.uniqueName }] : [] });
+ }
+ if (p === '/solutioncomponents') {
+ if (failSolutionComponentReads) return reply(500, { error: { code: '0x80040E14', message: 'simulated failure' } });
+ return page(path, solutionComponentRows(query.get('$filter'), query.get('$select')), query);
+ }
+ return null;
+ }
+
+ function create(kind, body, headers) {
+ const idField = KINDS[kind].id;
+ const id = normId(body[idField]) || randomUUID();
+ if (tables[kind].has(id)) return reply(412, { error: { code: '0x80060892', message: 'A record with matching key values already exists.' } });
+ // `canbedeleted`, `formactivationstate` and `createdon` are platform-owned: the platform fills them in.
+ const data = { ...clone(body), [idField]: id, createdon: new Date(0).toISOString(), formactivationstate: kind === 'systemforms' ? 1 : undefined };
+ if (data.formactivationstate === undefined) delete data.formactivationstate;
+ const row = { data, version: 1, publishedVersion: null };
+ tables[kind].set(id, row);
+ const echo = /return=representation/i.test((headers && headers.Prefer) || '');
+ return reply(echo ? 201 : 204, echo ? { [idField]: id, '@odata.etag': etagOf(row) } : {}, { etag: etagOf(row), 'odata-entityid': `https://fake/api/data/v9.0/${kind}(${id})` });
+ }
+
+ function patch(kind, id, body, headers) {
+ const row = tables[kind].get(normId(id));
+ if (!row) return notFound();
+ const ifMatch = headers && (headers['If-Match'] || headers['if-match']);
+ if (ifMatch && ifMatch !== etagOf(row)) return reply(412, { error: { code: '0x80060882', message: 'The version of the existing record doesn\'t match the RowVersion property provided.' } });
+ Object.assign(row.data, clone(body));
+ row.version += 1;
+ const echo = /return=representation/i.test((headers && headers.Prefer) || '');
+ return reply(echo ? 200 : 204, echo ? { [KINDS[kind].id]: normId(id), '@odata.etag': etagOf(row) } : {}, { etag: etagOf(row) });
+ }
+
+ function post(path, body, headers) {
+ const p = path.pathname;
+ let m;
+ if ((m = /^\/(savedqueries|systemforms|savedqueryvisualizations)$/.exec(p))) return create(m[1], body, headers);
+ if (p === '/AddSolutionComponent') {
+ // A table the solution holds with ALL its subcomponents already counts its views, forms and charts: the add
+ // succeeds and records nothing (see the header). Held at any other behavior, or not held, the add is the row.
+ const owner = tableOfComponent(body.ComponentType, body.ComponentId);
+ if (!(owner && held.get(owner) === 0)) members.add(`${Number(body.ComponentType)}:${normId(body.ComponentId)}`);
+ return reply(200, { id: randomUUID() });
+ }
+ if (p === '/PublishXml') {
+ const xml = String(body.ParameterXml || '');
+ for (const entity of [...xml.matchAll(/<entity>([^<]+)<\/entity>/g)].map((x) => x[1])) {
+ publishes.push(entity);
+ for (const kind of Object.keys(tables)) {
+ for (const row of tables[kind].values()) if (row.data[KINDS[kind].entity] === entity) row.publishedVersion = row.version;
+ }
+ }
+ return reply(204, {});
+ }
+ return null;
+ }
+
+ function dispatch(method, url, body, options) {
+ const u = new URL(url);
+ const path = { pathname: decodeURIComponent(u.pathname.replace(/^.*\/api\/data\/v[\d.]+/, '')), base: u.origin };
+ const headers = (options && options.headers) || {};
+ const entry = { method, path: path.pathname, query: Object.fromEntries(u.searchParams), body: body === undefined ? undefined : clone(body), headers };
+ requests.push(entry);
+ if (method !== 'GET' && denyWrites) {
+ const status = denyWrites(entry);
+ if (status) return reply(status, { error: { code: '0x80040E14', message: `simulated ${status}` } });
+ }
+ let response = null;
+ if (method === 'GET') response = get(path, u.searchParams);
+ else if (method === 'POST') response = post(path, body, headers);
+ else if (method === 'PATCH') {
+ const m = new RegExp(`^/(savedqueries|systemforms|savedqueryvisualizations)\\((${GUID})\\)$`, 'i').exec(path.pathname);
+ if (m) response = patch(m[1], m[2], body, headers);
+ }
+ if (!response) throw new Error(`fake-dataverse: unhandled ${method} ${path.pathname}${u.search}`);
+ return response;
+ }
+
+ const httpClient = {
+ get: async (url, options) => dispatch('GET', url, undefined, options),
+ post: async (url, body, options) => dispatch('POST', url, body, options),
+ patch: async (url, body, options) => dispatch('PATCH', url, body, options),
+ put: async (url) => { throw new Error(`fake-dataverse: unexpected PUT ${url}`); },
+ delete: async (url) => { throw new Error(`fake-dataverse: unexpected DELETE ${url}`); },
+ };
+
+ // `METHOD resource` per write ("PATCH savedqueries", "POST PublishXml"), so a test reads like the measurement
+ // that motivated it. `since` limits it to the requests after a `mark()`.
+ const resourceOf = (entry) => entry.path.replace(/^\//, '').replace(/\([^)]*\)/g, '').split('/')[0];
+ function writeCounts(since = 0) {
+ const counts = {};
+ for (const entry of requests.slice(since)) {
+ if (entry.method === 'GET') continue;
+ const key = `${entry.method} ${resourceOf(entry)}`;
+ counts[key] = (counts[key] || 0) + 1;
+ }
+ return counts;
+ }
+
+ return {
+ httpClient,
+ requests,
+ solutionId,
+ solutionUniqueName: solution.uniqueName,
+ // The platform's own "Active <Plural>" / "Inactive <Plural>" pair for a table, as it ships: not deletable, one
+ // `statecode` condition, created together. The SDK's default-view enrichment finds the pair by that shape.
+ seedDefaultViews(entity, plural) {
+ const grid = (primary) => `<grid name="resultset" object="10001" jump="${primary}" select="1" icon="1" preview="1"><row name="result" id="${entity}id"><cell name="${primary}" width="300"/></row></grid>`;
+ for (const [name, state] of [[`Active ${plural}`, 0], [`Inactive ${plural}`, 1]]) {
+ const id = randomUUID();
+ tables.savedqueries.set(id, {
+ data: { savedqueryid: id, name, description: '', returnedtypecode: entity, querytype: 0, isdefault: state === 0, canbedeleted: { Value: false }, createdon: new Date(0).toISOString(),
+ fetchxml: `<fetch version="1.0" mapping="logical"><entity name="${entity}"><attribute name="${entity}_name"/><filter type="and"><condition attribute="statecode" operator="eq" value="${state}"/></filter></entity></fetch>`,
+ layoutxml: grid(`${entity}_name`) },
+ version: 1, publishedVersion: 1,
+ });
+ }
+ },
+ mark: () => requests.length,
+ since: (mark) => requests.slice(mark),
+ writeCounts,
+ // Writes carrying a document (a form's formxml, a view's layoutxml) are SAVES; the others PATCH one flag.
+ saves: (since = 0) => requests.slice(since).filter((e) => e.method === 'PATCH' && e.body && (e.body.formxml || e.body.layoutxml || e.body.fetchxml)),
+ reads: (pattern, since = 0) => requests.slice(since).filter((e) => e.method === 'GET' && pattern.test(e.path)),
+ members,
+ removeMember: (type, id) => members.delete(`${Number(type)}:${normId(id)}`),
+ publishes,
+ rows: (kind) => [...tables[kind].values()],
+ // Rows whose latest saved version is not the one last published.
+ unpublished: () => Object.keys(tables).flatMap((kind) => [...tables[kind].values()]
+ .filter((row) => row.publishedVersion !== row.version)
+ .map((row) => ({ kind, id: row.data[KINDS[kind].id], name: row.data.name }))),
+ failWritesWhen: (fn) => { denyWrites = fn; },
+ // What the solution holds of each table (logical name -> rootcomponentbehavior), and the MetadataId the table
+ // row and the table's metadata carry. `holdTable` changes it between builds, as a maker would.
+ heldTables: held,
+ holdTable: (logical, behavior) => { held.set(logical, behavior); },
+ entityId: entityIdOf,
+ failTableIdReads: (fails) => { failTableIds = fails; },
+ };
+}
+
+module.exports = { createFakeDataverse };
diff --git a/plugins/model-apps/scripts/tests/helpers/fake-org-languages-preload.js b/plugins/model-apps/scripts/tests/helpers/fake-org-languages-preload.js
new file mode 100644
index 000000000..29215b4e1
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/fake-org-languages-preload.js
@@ -0,0 +1,39 @@
+'use strict';
+// A `node --require` preload for END-TO-END runs of scripts/list-languages.js. It swaps the az-token HTTP client for a
+// fake Dataverse that answers the three reads the SDK's `getEnvironmentLanguages()` makes, so a real child process runs
+// the real script, the real bundle, the real culture table and the real `emitResult` — with no Azure CLI and no network.
+//
+// The fake org comes from the environment variable FAKE_ORG_LANGUAGES, a JSON object:
+// { "base": 1033, "provisioned": [1033, 1025], "available": [1033, 1025] } the three answers, as the SDK measured them
+// { "refuse": { "status": 403, "message": "…" } } the organization read answers that instead
+//
+// Measured shapes (see list-languages-real-bundle.test.js for the same three):
+// GET organizations?$select=languagecode -> { value: [ { languagecode: <LCID> } ] }
+// GET RetrieveProvisionedLanguages() -> { RetrieveProvisionedLanguages: [<LCID>, ...] }
+// GET RetrieveAvailableLanguages() -> { LocaleIds: [<LCID>, ...] }
+const path = require('node:path');
+
+const client = require(path.resolve(__dirname, '..', '..', 'lib', 'sdk-http-client.js'));
+const org = JSON.parse(process.env.FAKE_ORG_LANGUAGES || '{}');
+
+const answer = (status, body) => ({ status, headers: { 'content-type': 'application/json' }, body });
+const refused = () => { throw new Error('this fake org answers only the three language reads'); };
+
+// The script destructures `createAzHttpClient` when it is loaded, which is after this preload, so replacing the export
+// here is what it receives.
+client.createAzHttpClient = () => ({
+ get: async (url) => {
+ const where = decodeURIComponent(String(url));
+ if (/\/organizations\?\$select=languagecode$/.test(where)) {
+ if (org.refuse) return answer(org.refuse.status, { error: { message: org.refuse.message } });
+ return answer(200, { value: [{ languagecode: org.base }] });
+ }
+ if (/\/RetrieveProvisionedLanguages\(\)$/.test(where)) return answer(200, { RetrieveProvisionedLanguages: org.provisioned });
+ if (/\/RetrieveAvailableLanguages\(\)$/.test(where)) return answer(200, { LocaleIds: org.available });
+ throw new Error(`unexpected request: GET ${where}`);
+ },
+ post: refused,
+ patch: refused,
+ put: refused,
+ delete: refused,
+});
diff --git a/plugins/model-apps/scripts/tests/helpers/form-store-harness.js b/plugins/model-apps/scripts/tests/helpers/form-store-harness.js
new file mode 100644
index 000000000..c23b3c99e
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/form-store-harness.js
@@ -0,0 +1,130 @@
+'use strict';
+// Shared REAL-BUNDLE harness for the form-layout tests that need the SDK's own serializer and fetch:
+// the vendored SDK against a stub HTTP client that stores ONE systemform row. A form "exists" once it has
+// formxml (the fixture's, or one the engine created), so the same harness serves a create and a rebuild.
+//
+// The stub answers only what a `forms`-phase build and `--verify` read; anything else fails the test, so a
+// new request a change introduces shows up here instead of being silently absorbed.
+const assert = require('node:assert');
+const fs = require('node:fs');
+const os = require('node:os');
+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 guid = (n) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;
+const clone = (v) => JSON.parse(JSON.stringify(v));
+const NOTES_CLASS_ID = '06375649-C143-495E-A496-C962E5B4488E';
+const SUBGRID_CLASS_ID = 'E7A81278-8635-4D9E-8D4D-59480B391C5B';
+const VIEW_ID = guid(7777);
+const DEFAULT_ATTRIBUTES = { new_name: 'String', new_code: 'String', new_notes: 'Memo', new_area: 'String', new_extra: 'String' };
+
+function createHarness({ formId = guid(1), entity = 'new_ticket', formName = 'Main', attributes = DEFAULT_ATTRIBUTES } = {}) {
+ const dirs = [];
+ const store = { row: { formid: formId, name: formName, objecttypecode: entity, type: 2, isdefault: true } };
+ const writes = [];
+ const reads = [];
+ let revision = 1;
+ const response = (body, status = 200) => ({ status, headers: { etag: `W/"${revision}"` }, body });
+ const httpClient = {
+ get: async (url) => {
+ reads.push(url);
+ const decoded = decodeURIComponent(url);
+ if (decoded.includes(`EntityDefinitions(LogicalName='${entity}')`)) {
+ return response({ LogicalName: entity, EntitySetName: `${entity}s`,
+ Attributes: Object.entries(attributes).map(([LogicalName, AttributeType]) => ({ LogicalName, AttributeType })) });
+ }
+ if (/EntityDefinitions\(LogicalName='systemform'\)/.test(decoded)) return response({ EntitySetName: 'systemforms' });
+ if (/systemforms\(/i.test(url)) {
+ assert.ok(store.row.formxml, 'a fetch reads a form that has been serialized');
+ return response(clone(store.row));
+ }
+ if (/\/systemforms(?:\?|$)/i.test(url)) return response({ value: store.row.formxml ? [clone(store.row)] : [] });
+ assert.fail(`unexpected GET: ${url}`);
+ },
+ post: async (url, body) => {
+ writes.push({ method: 'post', url, body: clone(body) });
+ if (/\/systemforms(?:\?|$)/i.test(url)) {
+ store.row = { ...store.row, ...body, formid: formId };
+ return { ...response({}, 204), headers: { 'odata-entityid': `https://contoso.crm.dynamics.com/api/data/v9.2/systemforms(${formId})` } };
+ }
+ if (/\/(?:PublishXml|AddSolutionComponent)(?:\?|$)/.test(url)) return response({}, 204);
+ assert.fail(`unexpected POST: ${url}`);
+ },
+ patch: async (url, body) => {
+ assert.match(url, /\/systemforms\(/i);
+ writes.push({ method: 'patch', url, body: clone(body) });
+ store.row = { ...store.row, ...body };
+ revision += 1;
+ return response({}, 204);
+ },
+ put: async (url) => assert.fail(`unexpected PUT: ${url}`),
+ delete: async (url) => assert.fail(`unexpected DELETE: ${url}`),
+ };
+ // A new SDK over a new workspace: a second apply must not lean on the first one's local copy.
+ const 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),
+ instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });
+ await sdk.initWorkspace();
+ const mutations = [];
+ // These wrappers record calls and delegate every one to the real bundle.
+ for (const method of ['createArtifact', 'addElement', 'updateElement', 'moveElement', 'removeElement', 'updateRecord', 'setFormSecurityRoles']) {
+ const original = sdk[method].bind(sdk);
+ sdk[method] = async (...args) => {
+ mutations.push({ method, args: clone(args) });
+ return original(...args);
+ };
+ }
+ // A sub-grid embeds the id of its child table's view, which the build looks up with a query of its own (the
+ // table's default public view); the stub answers it with one view and delegates every other query.
+ const queryRecords = sdk.queryRecords.bind(sdk);
+ sdk.queryRecords = async (set, options) => (set === 'savedquery' ? [{ savedqueryid: VIEW_ID, isdefault: true }] : queryRecords(set, options));
+ return { 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 };
+}
+
+// Put a form on the server the way the engine's create does — a minimal artifact, each compiled tab added
+// whole, the seed tab dropped, one push — from the given tabs. Returns the server's form id.
+async function seedForm(h, tabs, { name = 'Main', entity = h.entity } = {}) {
+ const seed = await h.freshSdk();
+ const art = await seed.sdk.createArtifact('form', { name, entityLogicalName: entity, formType: 'Main' });
+ for (const tab of tabs) await seed.sdk.addElement('form', art.id, '/tabs', tab);
+ await seed.sdk.removeElement('form', art.id, '/tabs/0');
+ const pushed = await seed.sdk.pushArtifact('form', art.id);
+ assert.ok(pushed && pushed.saved !== false, `the fixture form is pushed: ${JSON.stringify(pushed && pushed.error)}`);
+ return h.formId;
+}
+
+// `--verify` over what the server holds, through the plugin's own reader (the published formxml query).
+async function verifyForms(h, spec) {
+ const fetched = await h.freshSdk();
+ const live = readerFor(fetched.sdk, spec.app.uniqueName);
+ const read = {
+ findTable: async () => ({ logicalName: h.entity }),
+ findColumns: async () => Object.keys(h.attributes).map((logicalName) => ({ logicalName })),
+ sitemapXml: async () => '',
+ queryRecords: live.queryRecords,
+ formTopology: live.formTopology,
+ };
+ return verifySpec(spec, read);
+}
+
+// The FormXML of the section `name`.
+function sectionXml(formxml, name) {
+ const at = formxml.indexOf(`name="${name}"`);
+ assert.ok(at > 0, `section ${name} is in the formxml`);
+ const start = formxml.lastIndexOf('<section', at);
+ const end = formxml.indexOf('</section>', at) + '</section>'.length;
+ return formxml.slice(start, end);
+}
+
+// A run of empty rows written as a count — `<row />×22` — so a test can state the exact shape of a
+// timeline host without a 22-row literal.
+const collapseEmptyRows = (xml) => String(xml).replace(/(?:<row \/>)+/g, (run) => `<row />×${run.length / '<row />'.length}`);
+
+module.exports = { guid, clone, createHarness, seedForm, verifyForms, sectionXml, collapseEmptyRows, NOTES_CLASS_ID, SUBGRID_CLASS_ID, VIEW_ID, DEFAULT_ATTRIBUTES };
diff --git a/plugins/model-apps/scripts/tests/helpers/hidden-closing-pages.js b/plugins/model-apps/scripts/tests/helpers/hidden-closing-pages.js
new file mode 100644
index 000000000..4c68b26b6
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/hidden-closing-pages.js
@@ -0,0 +1,495 @@
+'use strict';
+
+// Programs for the sweeps of what a signature's text can hide (ambiguity-sweep.test.js): `<T>(x)` and what stands after its `)`, read to the closing tag `</T>`, which a type with the same text
+// may hold in a string, a template, a comment or a regex, so that the text of a call after it is data — and which an element ends at, so that the call is real. TypeScript says which programs
+// are pages and which tokens are data; a lexer that reads the text wrongly rewrites the token of a call that is not one.
+//
+// Eleven families, each drawn from a seeded generator (a failure is reproducible) and exhaustive where the family is small:
+// - a member named by a number: a decimal literal with a signed exponent is ONE token to the scanner, `1e-5`, so `1e` and a sign are not two names (numberedMemberPages);
+// - an expression in a member — a default value, a computed name, an initializer — that holds a nested element, whose text is JSX text to a type that reads the element and code to a reading that
+// does not, after which a string, a template or a regex holds the closing tag (nestedTextPages);
+// - a literal in such an expression that holds the text of an element, in one literal or across two (`<b>` in a string and `</b>` in the next): the type reads the literals as tokens, and the tags in them are no
+// element's (literalTagPages);
+// - a nested element whose text is a soup of quotes, back-ticks, comment openers, tags and containers, with the same decoys after it (nestedSoupPages);
+// - a nested tag that is no element — the type arguments of a name, a comparison, the type parameters of a signature or a method — whose closing tag a string before it holds, so that the quote that ends the string is
+// the start of the one that holds the closing tag of the head (nestedCodePages);
+// - a nested tag whose words are TypeScript's own — a modifier, an operator, a keyword, a dotted or dashed name, a value — with a line break of any kind before its `=`, and a fragment after an operand and a line comment of any
+// ending, in every place a tag can stand: drawn from the whole vocabulary, whether or not the lexer's rule calls the tag code, so that a rule that is wrong about a word is met (nestedTagPages);
+// - two or three nested elements, each with a comment opener, a quote or a back-tick in its text, whose regions end at one place (nestedPairPages);
+// - the same type arguments, comparison or type parameters, then strings and elements that hold tags — fragments, tags with an attribute, closing tags — which are text to the type, and which an element reading pairs the
+// quotes around differently (taggedStringPages);
+// - the lines that an element can have after `(a);` — a bracket, a quote, a tag, an operator, a number, a modifier, a postfix, a comment — placed in an expression of a type, where a regex after the
+// comment may hold the closing tag, which is the shape that a lexer that takes the last word of a comment for the token before a `/` reads wrong (expressionLinePages);
+// - an import type, `typeof import` and `import`, with a line terminator, a space or a comment between its tokens, whose `(` stands on a later line (importTypePages);
+// - an accessor, `get` or `set`, or another word before a computed name that holds a comma and a regex, which holds the closing tag (accessorNamePages).
+
+const { CALL } = require('./angle-frames.js');
+const { mulberry32 } = require('./jsx-element-fuzz.js');
+
+const pick = (rng, options) => options[Math.floor(rng() * options.length)];
+const chance = (rng, p) => rng() < p;
+
+// The call as a type's string holds it, with the closing tag before it.
+const HOLDING = `'</T>;${CALL};//'`;
+const HOLDING_BODY = `</T>;${CALL};//`;
+
+// ─── A member named by a number ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+// Every spelling of a decimal literal that takes an exponent: a main part, a fraction, an `e` or `E`, a sign, digits, separators. Those with a signed exponent are one numeric literal to the scanner (scanNumber).
+const MANTISSAS = ['1', '12', '1_0', '1.5', '.5', '1.', '0', '1.5_5'];
+const EXPONENTS = ['e5', 'E5', 'e+5', 'e-5', 'E+3', 'E-3', 'e+0', 'e-0', 'e+10', 'e+1_0', 'e-0_1', 'e+', 'e-', 'e+x', 'e', 'e1n'];
+const NUMBER_NAMES = MANTISSAS.flatMap((mantissa) => EXPONENTS.map((exponent) => `${mantissa}${exponent}`));
+const MEMBER_HEADS = ['<T>(x)', 'new <T>(x)', '<T>()'];
+const MEMBER_FRAMES = [
+ (member) => `interface I { ${member} }`,
+ (member) => `type L = { ${member} };`,
+ (member) => `let v: { ${member} } = f;`,
+ (member) => `function p(x: { ${member} }) {}`,
+];
+const MEMBER_SEPARATORS = [';', ',', '\n', ';\n ', ',\n ', ' // c\n', ' /* c */ ', '\r\n', '\u2028'];
+// What follows the name: a type that holds the closing tag in a string, a template or a comment, which is how a type hides it.
+const MEMBER_TAILS = [`: ${HOLDING}`, `?: ${HOLDING}`, `: \`</T>;${CALL};//\``, `(): ${HOLDING}`, `: { a: ${HOLDING} }`, ` // </T>;${CALL};\n m: T`, ` /* </T>;${CALL}; */ m: T`, `: A\n | ${HOLDING}`];
+function numberedMemberPages() {
+ const pages = [];
+ for (const frame of MEMBER_FRAMES) {
+ for (const head of MEMBER_HEADS) {
+ for (const name of NUMBER_NAMES) {
+ MEMBER_SEPARATORS.forEach((separator, index) => {
+ const tail = MEMBER_TAILS[(index + name.length) % MEMBER_TAILS.length];
+ pages.push({ code: `${frame(`${head}${separator}${name}${tail}`)}\n${CALL};\n`, label: `${frame('…')} / ${head} / ${JSON.stringify(separator)} / ${name} / ${JSON.stringify(tail)}`, name });
+ });
+ }
+ }
+ }
+ return pages;
+}
+
+// ─── The text of a nested element in an expression of a member ────────────────────────────────────────────────────────────────────────────────────────
+const NESTED_TEXTS = ['x // y', 'x /* y', "'x", '"x', '`x', "it's", 'https://x.y', 'a / b', 'see: // c', '// c', 'x', '', 'a, b', "x 'y", '5" wide', 'x /* y */ z', 'r/e/', 'x /* y\n */ z', '(x) // c', "'x' // c"];
+const NESTED_TAGS = ['b', 'i', 'span', 'A.B'];
+const NESTED_OPERATORS = [' +', ' ||', ' &&', ' ??', ' ,', ' ?', ' :', ' =', ' (', ' [', '', ' in', ' instanceof', ' -', ' *'];
+const NESTED_BREAKS = ['\n', '\r\n', '\r', '\u2028', '\u2029', ' ', '\n // more\n', ' /* c */ ', '\n\n'];
+const NESTED_DECOYS = [`/[</T>;${CALL}//]/`, `\`</T>;${CALL};//\``, `'</T>;${CALL};//'`, `"</T>;${CALL};//"`, `/[</T>;${CALL}//]/.source`];
+const NESTED_SEPARATORS = [';', ',', '\n', '; '];
+const nestedElement = (rng) => {
+ const roll = rng();
+ const text = pick(rng, NESTED_TEXTS);
+ if (roll < 0.15) return `<>${text}</>`;
+ const tag = pick(rng, NESTED_TAGS);
+ if (roll < 0.25) return `<${tag}>${text}<i/>${pick(rng, NESTED_TEXTS)}</${tag}>`;
+ if (roll < 0.32) return `<${tag}>${text}<i>${pick(rng, NESTED_TEXTS)}</i></${tag}>`;
+ return `<${tag}>${text}</${tag}>`;
+};
+const NESTED_FRAMES = [
+ (separator, value) => `interface I { <T>(x)${separator}m(a = ${value}): void }`,
+ (separator, value) => `interface I { <T>(x)${separator}[${value}]: string }`,
+ (separator, value) => `type L = { <T>(x)${separator}m(a?: string, b = ${value}): void };`,
+ (separator, value) => `interface C { new <T>(x)${separator}m(a = ${value}): void }`,
+ (separator, value) => `interface I { <T>(x)${separator}<U>(a = ${value}): void }`,
+ (separator, value) => `interface I { <T>(x)${separator}m = ${value} }`,
+];
+function nestedTextPages(seed, count) {
+ const rng = mulberry32(seed);
+ const pages = [];
+ const seen = new Set();
+ for (let i = 0; i < count; i += 1) {
+ let value = nestedElement(rng);
+ if (chance(rng, 0.3)) value = `f(${value})`;
+ if (chance(rng, 0.3)) value = `${pick(rng, ['1', 'x', '[', '('])}${pick(rng, NESTED_OPERATORS)} ${value}`;
+ value += pick(rng, NESTED_OPERATORS) + pick(rng, NESTED_BREAKS);
+ if (chance(rng, 0.2)) value += `${pick(rng, NESTED_OPERATORS)} `;
+ value += pick(rng, NESTED_DECOYS);
+ if (chance(rng, 0.4)) value += pick(rng, [')', ']', ' : 1', '])', ')]']);
+ const code = `${pick(rng, NESTED_FRAMES)(pick(rng, NESTED_SEPARATORS), value)}\n${CALL};\n`;
+ if (seen.has(code)) continue;
+ seen.add(code);
+ pages.push({ code, label: `nested text / ${JSON.stringify(value)}` });
+ }
+ return pages;
+}
+
+// ─── The lines of a prose element, in an expression of a type ──────────────────────────────────────────────────────────────────────────────────────────
+// `<p>(a);` and a line that holds a `//`, then a line that starts with a `/`, is an element, for certain, where no type can have its text (typeMembersFail). The same lines in an expression of a type — a default
+// value, a computed name, an initializer, after `m: A` and a line break — are where a regex after the comment may hold the closing tag: the token before the comment says whether the `/` divides or begins one.
+const EXPRESSION_TAILS = [' // note', '// note', ' https://x.y', ' /* c */ // d', ' // c1\n // c2'];
+const EXPRESSION_DECOYS = [`/[</T>;${CALL}//]/`, `/[</T>;${CALL}//]/g`, `/[</T>;${CALL}//]/.source`];
+const EXPRESSION_FRAMES = [
+ (line, tail, br, decoy) => `interface I { <T>(x); m(a = q${br} ${line}${tail}${br}${decoy}): void }`,
+ (line, tail, br, decoy) => `interface I { <T>(x); m(a = ${line}${tail}${br}${decoy}): void }`,
+ (line, tail, br, decoy) => `interface I { <T>(x); [q${br} ${line}${tail}${br}${decoy}]: string }`,
+ (line, tail, br, decoy) => `interface I { <T>(x); [${line}${tail}${br}${decoy}]: string }`,
+ (line, tail, br, decoy) => `interface I { <T>(x); m(a = q ? r${br} ${line}${tail}${br}${decoy}): void }`,
+ (line, tail, br, decoy) => `interface I { <T>(x); m(a = q${br} ${line}${tail}${br}${decoy} : 1): void }`,
+ (line, tail, br, decoy) => `interface I { <T>(x); m(a = [q,${br} ${line}${tail}${br}${decoy}]): void }`,
+ (line, tail, br, decoy) => `interface I { <T>(x); m = q${br} ${line}${tail}${br}${decoy}.source }`,
+ (line, tail, br, decoy) => `interface I { <T>(x); m: A${br} = q${br} ${line}${tail}${br}${decoy}.source }`,
+ // A line after `m: A` or `m` and a line break, which a member's initializer, type or optional mark may go on: where the line begins with `|`, `&`, `=`, `?` or `:` the type or member before it goes on, and a regex after the
+ // comment may be the initializer's.
+ (line, tail, br, decoy) => `interface I { <T>(x); m: A${br} ${line}${tail}${br}${decoy} }`,
+ (line, tail, br, decoy) => `interface I { <T>(x); m${br} ${line}${tail}${br}${decoy} }`,
+ (line, tail, br, decoy) => `interface I { <T>(x); readonly${br} ${line}${tail}${br}${decoy} }`,
+];
+const EXPRESSION_BREAKS = ['\n', '\r\n', '\r', '\u2028', '\u2029'];
+function expressionLinePages(lines, seed, count) {
+ const rng = mulberry32(seed);
+ const pages = [];
+ const seen = new Set();
+ for (let i = 0; i < count; i += 1) {
+ const line = pick(rng, lines);
+ const code = `${pick(rng, EXPRESSION_FRAMES)(line, pick(rng, EXPRESSION_TAILS), pick(rng, EXPRESSION_BREAKS), pick(rng, EXPRESSION_DECOYS))}\n${CALL};\n`;
+ if (seen.has(code)) continue;
+ seen.add(code);
+ pages.push({ code, label: `an expression / ${JSON.stringify(line)}` });
+ }
+ return pages;
+}
+
+// ─── The tags that a literal holds ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+// A string, a template, a regex or a comment that holds the text of an element — `'<b>c</b>'`, or `<b>` in one and `</b>` in the next — in a default value or a computed name, then an operator and a decoy that holds the closing
+// tag of the head. The element reading takes the tags in the literals for an element's, which opens in one literal and closes in another; the type reads the literals as tokens, and the decoy holds the closing tag and the text of a call.
+const TAG_LITERALS = ["'<b>c</b>'", '"<b>c</b>"', '`<b>c</b>`', '`<b>${x}</b>`', "'<b>'", "'</b>'", "'<>'", "'</>'", "'<b/>'", "'<b>c</b> d <i>e</i>'", '/<b>/', '/<\\/b>/', '/<b>c<\\/b>/', '/* <b>c</b> */', '/* <b> */', '/* </b> */',
+ '// <b>c</b>\n', '// <b>\n', '// </b>\n', "'a <b>'", "'</b> a'", '`</b>`', '`<b>`', "'<b>c'", "'c</b>'", "'x // <b>y</b>'", "'x /* <b>y</b> */'", '`<b>\n</b>`', '`a ${b} <i>c</i>`', "'<b x=\"1\">c</b>'", "'<b x={1}>c</b>'",
+ '<b>c</b>', '<b>x</b>', '<>c</>', "<b>'</b>", '<b>"</b>', '<b>`</b>'];
+const TAG_OPERATORS = [' +', ' ||', ' &&', ' ??', ' ,', ' ?', ' :', ' =', ' (', ' [', '', ' in', ' instanceof', ' -', ' *', ' ==', ' <', ' >'];
+const TAG_BREAKS = ['\n', '\r\n', ' ', '\n // more\n', ' /* c */ ', '\n\n', '\u2028'];
+const TAG_DECOYS = [`'</T>;${CALL}//'`, `\`</T>;${CALL};//\``, `/[</T>;${CALL}//]/`, `/[</T>;${CALL}//]/.source`, `\`\n</T>;${CALL}//\``];
+const TAG_FRAMES = [
+ (value) => `interface I { <T>(x); m(a = ${value}): void }`,
+ (value) => `interface I { <T>(x); [${value}]: string }`,
+ (value) => `type L = { <T>(x); m(a?: string, b = ${value}): void };`,
+ (value) => `interface C { new <T>(x); m(a = ${value}): void }`,
+ (value) => `interface I { <T>(x); m: A = ${value} }`,
+ (value) => `interface I { <T>(x); <U>(a = ${value}): void }`,
+];
+function literalTagPages(seed, count) {
+ const rng = mulberry32(seed);
+ const pages = [];
+ const seen = new Set();
+ for (let i = 0; i < count; i += 1) {
+ let value = pick(rng, TAG_LITERALS);
+ if (chance(rng, 0.3)) value = `f(${value})`;
+ if (chance(rng, 0.3)) value = `${pick(rng, ['1', 'x', '(', '['])}${pick(rng, TAG_OPERATORS)} ${value}`;
+ value += pick(rng, TAG_OPERATORS) + pick(rng, TAG_BREAKS);
+ if (chance(rng, 0.2)) value += `${pick(rng, TAG_LITERALS)}${pick(rng, TAG_OPERATORS)} `;
+ value += pick(rng, TAG_DECOYS);
+ if (chance(rng, 0.4)) value += pick(rng, [')', ']', ' : 1', '])', ')]']);
+ const code = `${pick(rng, TAG_FRAMES)(value)}\n${CALL};\n`;
+ if (seen.has(code)) continue;
+ seen.add(code);
+ pages.push({ code, label: `literal tags / ${JSON.stringify(value)}` });
+ }
+ return pages;
+}
+
+// ─── The text of a nested element, as a soup ─────────────────────────────────────────────────────────────────────────────────────────────────────────
+// A nested element — or two — whose text is a draw of quotes, back-ticks, comment openers, tags, containers and words, in a default value or a computed name, then an operator and a decoy that holds the closing tag of the head.
+// The text is JSX text to a type that reads the element, and code to a reading that does not, and the tags in it may be a tag in one and a token's in the other: what the text opens ends with its element in the one and goes on in
+// the other, and the scan must hold the closing tag hidden where either hides it (nestedSoupPages).
+const SOUP = ['x', 'y z', "'", '"', '`', '//', '/*', '*/', '<i>', '</i>', '<b/>', '<i/>', '{y}', "'<i>'", "it's", 'https://x.y', '\n', ' ', '&amp;', '(', ')', '[', ']', 'a/b', '/', '</>', '<>', "'a'", '`t`', '"q"', '// c\n', '/* c */', '{z}'];
+const SOUP_FRAMES = [
+ (value) => `interface I { <T>(x); m(a = ${value}): void }`,
+ (value) => `interface I { <T>(x); [${value}]: string }`,
+ (value) => `type L = { <T>(x); m(a?: string, b = ${value}): void };`,
+ (value) => `interface C { new <T>(x); m(a = ${value}): void }`,
+ (value) => `interface I { <T>(x); m: A = ${value} }`,
+];
+function nestedSoupPages(seed, count) {
+ const rng = mulberry32(seed);
+ const element = () => {
+ const tag = pick(rng, ['b', 'i', 'span', '']);
+ const text = Array.from({ length: 1 + Math.floor(rng() * 6) }, () => pick(rng, SOUP)).join(pick(rng, ['', ' ']));
+ return tag === '' ? `<>${text}</>` : `<${tag}>${text}</${tag}>`;
+ };
+ const pages = [];
+ const seen = new Set();
+ for (let i = 0; i < count; i += 1) {
+ let value = element();
+ if (chance(rng, 0.25)) value = `${value}${pick(rng, TAG_OPERATORS)} ${element()}`;
+ if (chance(rng, 0.3)) value = `f(${value})`;
+ if (chance(rng, 0.3)) value = `${pick(rng, ['1', 'x', '(', '['])}${pick(rng, TAG_OPERATORS)} ${value}`;
+ value += pick(rng, TAG_OPERATORS) + pick(rng, TAG_BREAKS);
+ if (chance(rng, 0.2)) value += `${pick(rng, ["'a <i>'", '`</i>`', "'</i>'", '/* <i> */'])}${pick(rng, TAG_OPERATORS)} `;
+ value += pick(rng, TAG_DECOYS);
+ if (chance(rng, 0.4)) value += pick(rng, [')', ']', ' : 1', '])', ')]']);
+ const code = `${pick(rng, SOUP_FRAMES)(value)}\n${CALL};\n`;
+ if (seen.has(code)) continue;
+ seen.add(code);
+ pages.push({ code, label: `nested soup / ${JSON.stringify(value)}` });
+ }
+ return pages;
+}
+
+// ─── A nested tag that no element has ────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+// A nested `<b>…</b>` in the text is an element to a reading that takes the head for one, and to a type that reads an element in an expression. To a type it may be anything else: the type arguments of a name (`Array<b>`),
+// a comparison (`a<b>c`), the type parameters of a signature (`<b>(y): T`, `<U extends A>(y): T`) or of a method (`m<b>(y)`). The text after its `>` is code there, and what looks like its closing tag is in a string that stands
+// before it, so that the quote that ends that string is the start of the next — the one that holds the closing tag of the head and the text of a call. Where the head is an element, the nested closing tag closes the nested
+// element, and the quote after it is text: the same page, with the call in the string read as code (nestedCodePages).
+const CODE_TAGS = ['b', 'U', 'span', 'A.B', 'in', 'T1'];
+const codeLiterals = (tag) => [`'</${tag}>'`, `"</${tag}>"`, `\`</${tag}>\``, `'a </${tag}> b'`, `'<${tag}></${tag}>'`, `'x'`, `'</${tag}>x'`, `\`\n</${tag}>\``];
+const CODE_BREAKS = ['', ' ', '\n', '\r\n', ' /* c */ ', ' // c\n', '\u2028', '\n '];
+const CODE_UNIONS = [' |', ' &', ' |\n ', ' | '];
+const CODE_OPERATORS = [' +', ' ||', ' &&', ' ??', ' ,', ' :', ' ?', ' ==', ' in', ' instanceof'];
+const CODE_DECOYS = [HOLDING, `\`</T>;${CALL};//\``, `\`\n</T>;${CALL};//\``, `"</T>;${CALL};//"`, `/[</T>;${CALL}//]/`, `/[</T>;${CALL}//]/.source`];
+const CODE_FRAMES = [
+ (separator, member) => `interface I { <T>(x)${separator}${member} }`,
+ (separator, member) => `type L = { <T>(x)${separator}${member} };`,
+ (separator, member) => `interface C { new <T>(x)${separator}${member} }`,
+ (separator, member) => `declare const v: { <T>(x)${separator}${member} };`,
+ (separator, member) => `function f(a: { <T>(x)${separator}${member} }) {}`,
+];
+function nestedCodePages(seed, count) {
+ const rng = mulberry32(seed);
+ const pages = [];
+ const seen = new Set();
+ for (let i = 0; i < count; i += 1) {
+ const tag = pick(rng, CODE_TAGS);
+ const literal = pick(rng, codeLiterals(tag));
+ const decoy = pick(rng, CODE_DECOYS);
+ const gap = pick(rng, CODE_BREAKS);
+ const operator = pick(rng, CODE_OPERATORS);
+ const union = pick(rng, CODE_UNIONS);
+ const member = [
+ `m: Array<${tag}> =${gap} ${literal}${operator}${gap} ${decoy}`,
+ `m: A<${tag}>;${gap} n: ${literal}${union}${gap} ${decoy}`,
+ `m: A = a<${tag}>c;${gap} n: ${literal}${union}${gap} ${decoy}`,
+ `m(a = x < ${tag} > y, c = ${literal}${operator}${gap} ${decoy}): void`,
+ `<${tag}>(y): ${literal};${gap} q: ${decoy}`,
+ `<${tag} extends A>(y): ${literal};${gap} q: ${decoy}`,
+ `m<${tag}>(y): ${literal};${gap} q: ${decoy}`,
+ `m: Array<${tag}>${gap} = f(${literal}, ${decoy})`,
+ `m: Array<${tag}> =${gap} [${literal}${operator}${gap} ${decoy}]`,
+ `[k: ${literal}]: Array<${tag}>;${gap} q: ${decoy}`,
+ ][Math.floor(rng() * 10)];
+ const code = `${pick(rng, CODE_FRAMES)(pick(rng, NESTED_SEPARATORS), member)}\n${CALL};\n`;
+ if (seen.has(code)) continue;
+ seen.add(code);
+ pages.push({ code, label: `nested code tag / ${JSON.stringify(member)}` });
+ }
+ return pages;
+}
+
+// ─── Tags that stand in strings ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+// After type arguments, a comparison or the type parameters of a signature, the text is code, and a string, a template or a comment that holds tags — a fragment, a tag with an attribute, an element with none, their closing
+// tags — holds them as text. The element reading takes them for tags, and a closing tag in the next string cuts that string: the quote that ends it, which the type pairs with the one that opened it, then opens a string, and
+// the string that holds the closing tag of the head is read as code. The operands are literals and elements — with an attribute, plain, a fragment — whose text holds quotes, back-ticks, comment openers and tags
+// (taggedStringPages); one literal holds the closing tag of the head and the text of a call.
+const STRING_PIECES = ['<>', '</>', '<a href="x">', '</a>', '<i d="1">', '</i>', '<b>', '</b>', '<b d>', '<A.B x>', '</A.B>', 'x', ' ', 'it', '<i>', '<U extends A>', '</U>', '<>x</>', '<a href="x">y</a>', '</b></T>', '</T>', '<T>'];
+const ELEMENT_TEXTS = ['x', "it's", '"', "'", '`', '// c', '/* c', 'https://x.y', '</i>', '<i>', '<>', '</>', '<a href="x">', '</a>', ' '];
+const STRING_OPERATORS = [' +', ' |', ' ||', ' &&', ' ,', ' ?', ' ??'];
+const STRING_GAPS = ['', ' ', '\n', ' // c\n'];
+const STRING_HEADS = ['m: Array<b> =', 'm: A<b> =', 'm: A = a<b>c +', 'm(a = x < b > y,', 'm<b>(y): void; n =', 'm: A<b>; n: A =', 'm: Array<i> ='];
+const STRING_FRAMES = [
+ (member) => `interface I { <T>(x); ${member} }`,
+ (member) => `type L = { <T>(x); ${member} };`,
+ (member) => `interface C { new <T>(x); ${member} }`,
+];
+function taggedStringPages(seed, count) {
+ const rng = mulberry32(seed);
+ const stringOf = (withBody) => {
+ const quote = pick(rng, ["'", '"', '`']);
+ let inner = Array.from({ length: 1 + Math.floor(rng() * 3) }, () => pick(rng, STRING_PIECES)).join(chance(rng, 0.3) ? ' ' : '');
+ if (withBody) inner = chance(rng, 0.5) ? `${inner}${HOLDING_BODY}` : `${HOLDING_BODY}${inner}`;
+ if (quote === '"') inner = inner.replace(/"/g, '\\"');
+ return `${quote}${inner}${quote}`;
+ };
+ const elementOf = () => {
+ const inner = Array.from({ length: 1 + Math.floor(rng() * 3) }, () => pick(rng, ELEMENT_TEXTS)).join('');
+ const roll = rng();
+ if (roll < 0.35) return `<a href="x">${inner}</a>`;
+ if (roll < 0.7) return `<b>${inner}</b>`;
+ if (roll < 0.85) return `<>${inner}</>`;
+ return `<i d="1">${inner}</i>`;
+ };
+ const pages = [];
+ const seen = new Set();
+ for (let i = 0; i < count; i += 1) {
+ const operands = 2 + Math.floor(rng() * 3);
+ const at = Math.floor(rng() * operands);
+ let value = '';
+ for (let k = 0; k < operands; k += 1) {
+ value += k !== at && chance(rng, 0.25) ? elementOf() : stringOf(k === at);
+ if (k < operands - 1) value += pick(rng, STRING_OPERATORS) + pick(rng, STRING_GAPS);
+ }
+ let member = `${pick(rng, STRING_HEADS)} ${value}`;
+ if (member.startsWith('m(a')) member += '): void';
+ const code = `${pick(rng, STRING_FRAMES)(member)}\n${CALL};\n`;
+ if (seen.has(code)) continue;
+ seen.add(code);
+ pages.push({ code, label: `tags in strings / ${JSON.stringify(member)}` });
+ }
+ return pages;
+}
+
+// ─── The words of a nested tag ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+// A tag in the text of a member is an element to one reading of a type, and to another it is code, by the words in it: the type parameters of a signature (`<public U>(y): T`, `<in out U>`, `m<static U>(y)`), the type arguments
+// of a name (`Array<keyof X>`), a comparison or a tagged template with type arguments (`x <a in b> y`, `x <typeof U> \`t\``), empty angle brackets after a name, a call or a bracket, or before a parenthesis (`f(x)<>`,
+// `a[0]<>`, `<>(y)`, `m<>(y)`). The tags are drawn from every word TypeScript has — keywords, modifiers, operators, names — joined with a name, a dot, a dash or a value, and from the tags that no type has (a word that is given a value,
+// a link): where the words say that no type has the tag, the text is JSX text and the page is read exactly, and where one has it, the text after its `>` is code and a string there holds the closing tag. The tag is the whole of the
+// vocabulary, not the tags that the lexer's rule already calls code: that is how a rule that is wrong about a word is found (nestedTagPages).
+const TAG_NAMES = ['b', 'U', 'span', 'A', 'x', 'in', 'out', 'type', 'of', 'as', 'is', 'async', 'get', 'set'];
+function tagShapes(words) {
+ const shapes = [];
+ for (const word of words) {
+ shapes.push({ text: word, name: word }, { text: `${word} U`, name: word }, { text: `U ${word}`, name: 'U' }, { text: `${word} U extends A`, name: word }, { text: `U extends ${word}`, name: 'U' }, { text: `A.${word}`, name: `A.${word}` },
+ { text: `${word}.A`, name: `${word}.A` }, { text: `${word}-a`, name: `${word}-a` }, { text: `a-${word}`, name: `a-${word}` }, { text: `${word}="v"`, name: word }, { text: `a ${word}="v"`, name: 'a' }, { text: `${word}={v}`, name: word },
+ { text: `a ${word}`, name: 'a' }, { text: `a="v" ${word}`, name: 'a' }, { text: `${word} ${word}`, name: word }, { text: `A.B ${word} x`, name: 'A.B' }, { text: `${word} U = V`, name: word },
+ // A line break between a word and its `=`, or before a valued `get` or `set`, makes the tag the members of a type: an initializer that ends at the break, and a member with an initializer of its own. With the `=` on the line
+ // of its word the tag is an element's, as prettier writes one.
+ { text: `a\n${word}\n="v"`, name: 'a' }, { text: `a ${word}\n="v"`, name: 'a' }, { text: `a\n${word}="v"`, name: 'a' }, { text: `a\r\n${word}\r\n='v'`, name: 'a' }, { text: `a\r${word}\r={v}`, name: 'a' }, { text: `${word}\n="v"`, name: word },
+ { text: `A.B\n${word}\n="v"`, name: 'A.B' }, { text: `A.${word}\nx\n="v"`, name: `A.${word}` }, { text: `a\nb\n${word}\n="v"`, name: 'a' }, { text: `a\n${word}="v"\n${word}\n="v"`, name: 'a' }, { text: `a\n ${word}\n ="v"\n`, name: 'a' },
+ { text: `a\n ${word}="v"\n title="t"\n`, name: 'a' }, { text: `a\u2028${word}\u2028="v"`, name: 'a' }, { text: `a\n${word}\u2029="v"`, name: 'a' });
+ }
+ return shapes;
+}
+const TAG_ROLES = [
+ // The tag as the comparison or the type arguments of an expression, as type arguments of a name in a type, and as the type parameters of a signature or a method: its text, a string that holds its closing tag, then the
+ // decoy that holds the closing tag of the head.
+ (tag, lit, decoy, gap, op) => `m(p = x <${tag.text}>${gap} ${lit}${op}${gap} ${decoy}): void`,
+ (tag, lit, decoy, gap, op) => `m: Array<${tag.text}> =${gap} ${lit}${op}${gap} ${decoy}`,
+ (tag, lit, decoy, gap) => `<${tag.text}>(y): ${lit};${gap} q: ${decoy}`,
+ (tag, lit, decoy, gap) => `m<${tag.text}>(y): ${lit};${gap} q: ${decoy}`,
+ (tag, lit, decoy, gap) => `new <${tag.text}>(y): ${lit};${gap} q: ${decoy}`,
+ (tag, lit, decoy, gap, op) => `m: A<${tag.text}>;${gap} n: ${lit}${op}${gap} ${decoy}`,
+ (tag, lit, decoy, gap, op) => `m: A = a <${tag.text}> c;${gap} n: ${lit} |${gap} ${decoy}`,
+ (tag, lit, decoy, gap, op) => `m(p = x <${tag.text}>\`t\`${op}${gap} ${lit}${op}${gap} ${decoy}): void`,
+ // The tag as an element: its text is JSX text, and what stands after its closing tag is read as the code it follows.
+ (tag, lit, decoy, gap, op) => `m(p = <${tag.text}>x</${tag.name}>${op}${gap} ${decoy}): void`,
+ (tag, lit, decoy, gap, op) => `m(p = <${tag.text}>'x</${tag.name}>${op}${gap} ${lit}${op}${gap} ${decoy}): void`,
+ (tag, lit, decoy, gap, op) => `[<${tag.text}>x // y</${tag.name}>${op}${gap} ${decoy}]: string`,
+];
+const FRAGMENT_OPERANDS = ['f(x)', 'a[0]', 'a!', "'s'", '{}', 'x', '1', 'this', 'f<U>(x)', '(a)', '`t`', '/re/', 'x.y', 'f()', 'a[0][1]', 'async', 'm', '1.', '\u00e9', 'a?.b'];
+// What stands between the operand and the fragment: a space, a line break of any kind, a comment — and a line comment, which may end in any character, so that the character before the fragment on the next line is no operand's:
+// `f // note:` and a line break, then `<> || …`, is the instantiation expression `f<> || …`.
+const FRAGMENT_SEPARATORS = ['', '', '', ' ', '\n', '\r\n', '\r', '\u2028', '\u2029', '\u0085', ' /* c */ ', ' // note:\n', ' // note.\n', ' // note,\n', ' // note -\n', ' // note =\n', ' // note (\n', ' // note\n', ' // note:\r\n', ' // note:\r',
+ ' // note:\u2028', ' // note:\u2029', '\n\n // note:\n ', ' // c\n// d:\n'];
+const FRAGMENT_ROLES = [
+ // An empty pair of angle brackets after an operand (the type arguments of an instantiation or of a call), after a name in a type, and before a parenthesis or a back-tick (type parameters, type arguments of a tagged template); a
+ // fragment after an operator or a separator is JSX.
+ (operand, lit, decoy, gap, op) => `m(p = ${operand}<>${op}${gap} ${lit}${op}${gap} ${decoy}): void`,
+ (operand, lit, decoy, gap, op) => `m(p = ${operand}<> ${lit}${op}${gap} ${decoy}): void`,
+ (operand, lit, decoy, gap, op) => `m: ${operand}<> =${gap} ${lit}${op}${gap} ${decoy}`,
+ (operand, lit, decoy, gap) => `${operand}<>(y): ${lit};${gap} q: ${decoy}`,
+ (operand, lit, decoy, gap) => `new ${operand}<>(y): ${lit};${gap} q: ${decoy}`,
+ (operand, lit, decoy, gap, op) => `m(p = ${operand} <>\`t\`${op}${gap} ${lit}${op}${gap} ${decoy}): void`,
+ (operand, lit, decoy, gap, op) => `m(p = ${operand}${op} <>x // y</>${op}${gap} ${decoy}): void`,
+ (operand, lit, decoy, gap) => `m(p = ${operand}, <>x // y</>${gap} + ${decoy}): void`,
+ (operand, lit, decoy, gap) => `[${operand}; <>x // y</>${gap} + ${decoy}]: string`,
+];
+function nestedTagPages(seed, count, keywords) {
+ const rng = mulberry32(seed);
+ const words = [...new Set([...keywords, ...TAG_NAMES])];
+ const shapes = tagShapes(words);
+ const pages = [];
+ const seen = new Set();
+ for (let i = 0; i < count; i += 1) {
+ const gap = pick(rng, CODE_BREAKS);
+ const operator = pick(rng, CODE_OPERATORS);
+ const decoy = pick(rng, CODE_DECOYS);
+ let member;
+ let what;
+ if (chance(rng, 0.25)) {
+ const operand = pick(rng, FRAGMENT_OPERANDS) + pick(rng, FRAGMENT_SEPARATORS);
+ member = pick(rng, FRAGMENT_ROLES)(operand, "'</>'", decoy, gap, operator);
+ what = `fragment after ${JSON.stringify(operand)}`;
+ } else {
+ const tag = pick(rng, shapes);
+ member = pick(rng, TAG_ROLES)(tag, `'</${tag.name}>'`, decoy, gap, operator);
+ what = `tag ${JSON.stringify(tag.text)}`;
+ }
+ const code = `${pick(rng, CODE_FRAMES)(pick(rng, NESTED_SEPARATORS), member)}\n${CALL};\n`;
+ if (seen.has(code)) continue;
+ seen.add(code);
+ pages.push({ code, label: `nested tag words / ${what} / ${JSON.stringify(member)}`, what });
+ }
+ return pages;
+}
+
+// ─── Two nested elements whose text opens a region each ───────────────────────────────────────────────────────────────────────────────────────────────
+// Each of two nested elements in a default value, a computed name or an initializer holds a comment opener, a quote or a back-tick in its text, which is JSX text to an element and code to a type: the region that the first
+// opens, and the one that the second opens, may end at one place — two `//` comments on one line end at its line break, and a template or a string that one holds may end where the other's does. Every region that is open at the
+// closing tag of an element is a place to choose between the two readings of it, told by where it starts, so that two regions with one end are two places (nestedPairPages).
+const PAIR_TEXTS = ['//', 'x // y', '/*', 'x /* y', "'", "'x", '"x', '`', '`x', '// y\n', 'x', ''];
+const PAIR_TAGS = ['b', 'i', 'span', 'A.B', ''];
+const PAIR_JOINS = [' -', ' +', ' ??', ' ||', ' &&', ',', ' ?', ' :', ' ==', ''];
+const PAIR_FRAMES = [
+ (value) => `interface I { <T>(x); m(a = ${value}): void }`,
+ (value) => `interface I { <T>(x); [${value}]: string }`,
+ (value) => `type L = { <T>(x); m(a?: string, b = ${value}): void };`,
+ (value) => `interface C { new <T>(x); m(a = ${value}): void }`,
+ (value) => `interface I { <T>(x); m: A = ${value} }`,
+ (value) => `interface I { <T>(x); m(a = [${value}]): void }`,
+];
+function nestedPairPages(seed, count) {
+ const rng = mulberry32(seed);
+ const element = () => {
+ const tag = pick(rng, PAIR_TAGS);
+ const text = pick(rng, PAIR_TEXTS);
+ return tag === '' ? `<>${text}</>` : `<${tag}>${text}</${tag}>`;
+ };
+ const pages = [];
+ const seen = new Set();
+ for (let i = 0; i < count; i += 1) {
+ let value = element();
+ for (let k = 1 + Math.floor(rng() * 2); k > 0; k -= 1) value += `${pick(rng, PAIR_JOINS)}${pick(rng, ['', ' '])}${element()}`;
+ if (chance(rng, 0.2)) value = `f(${value})`;
+ value += pick(rng, TAG_OPERATORS) + pick(rng, TAG_BREAKS);
+ value += pick(rng, TAG_DECOYS);
+ if (chance(rng, 0.4)) value += pick(rng, [')', ']', ' : 1', '])', ')]']);
+ const code = `${pick(rng, PAIR_FRAMES)(value)}\n${CALL};\n`;
+ if (seen.has(code)) continue;
+ seen.add(code);
+ pages.push({ code, label: `nested pair / ${JSON.stringify(value)}` });
+ }
+ return pages;
+}
+
+// ─── An import type whose `(` stands on a later line ─────────────────────────────────────────────────────────────────────────────────────────────────────
+// `typeof import` and `import` have no line-break rule before their `(` (parseImportType), so a line terminator, a space of any kind or a comment may stand between each two of their tokens, where after any other type a `(` at the
+// start of a line begins a call signature, whose first parameter a string is not. The string, template, comment or regex that holds the closing tag is the import path or what follows the type (importTypePages).
+const IMPORT_LEADS = ['m: ', 'm?: ', 'm(): ', 'readonly m: ', 'm: A | ', 'm: A & ', 'm: keyof ', "'k': ", '[k: string]: ', 'get x(): ', 'new (): ', 'm(p: ', 'static m: ', 'm: A.B | ', 'm: readonly '];
+const IMPORT_WORD_GAPS = ['\n', '\r', '\r\n', '\u2028', '\u2029', '\u0085', ' ', ' /* c */ ', ' /*\n*/ ', ' // c\n', '\n ', '/**/'];
+const IMPORT_PAREN_GAPS = ['', ...IMPORT_WORD_GAPS];
+const IMPORT_PATHS = ["'./m'", `'${HOLDING_BODY}'`, '"./m"', '`./m`', `\`${HOLDING_BODY}\``, `'./m' /* ${HOLDING_BODY} */`, `"${HOLDING_BODY.replace(/"/g, "'")}"`];
+const IMPORT_TAILS = ['', '', '.X', ' | A', ' & B', '[]', '.X.Y', '<A>', ' extends B ? C : D'];
+const IMPORT_AFTERS = [`;\n q: ${HOLDING}`, ` // ${HOLDING_BODY}\n q: T`, `,\n q: \`</T>;${CALL};//\``, `\n q: ${HOLDING}`, ` /* ${HOLDING_BODY} */ q: T`, `;\n q: /[</T>;${CALL}//]/`, '', ';'];
+function importTypePages(seed, count) {
+ const rng = mulberry32(seed);
+ const pages = [];
+ const seen = new Set();
+ for (let i = 0; i < count; i += 1) {
+ const word = () => pick(rng, IMPORT_WORD_GAPS);
+ const gap = () => pick(rng, IMPORT_PAREN_GAPS);
+ const form = pick(rng, [`typeof${word()}import${gap()}`, `import${gap()}`, `keyof${word()}typeof${word()}import${gap()}`, `typeof${word()}import${gap()}`, `readonly${word()}typeof${word()}import${gap()}`]);
+ const member = `${pick(rng, IMPORT_LEADS)}${form}(${gap()}${pick(rng, IMPORT_PATHS)}${gap()})${pick(rng, IMPORT_TAILS)}${pick(rng, IMPORT_AFTERS)}`;
+ const code = `${pick(rng, CODE_FRAMES)(pick(rng, NESTED_SEPARATORS), member)}\n${CALL};\n`;
+ if (seen.has(code)) continue;
+ seen.add(code);
+ pages.push({ code, label: `import type / ${JSON.stringify(member)}` });
+ }
+ return pages;
+}
+
+// ─── An accessor, or another modifier, before a computed name that holds a comma ──────────────────────────────────────────────────────────────────────
+// `get [a, /x/]()` is an accessor whose computed name is a comma expression with a regex in it: parseTypeMember tries `get` and `set` before an index signature, and what follows them may be any `[`, on any line. After any other word
+// that `[`, a name and a `,` or a `:` are an index signature, and no `/` follows. The regex holds the closing tag and the text of a call (accessorNamePages).
+const ACCESSOR_MODIFIERS = ['', '', 'static ', 'readonly ', 'declare ', 'public ', 'private ', 'abstract ', 'override ', 'accessor ', 'async ', 'static readonly ', 'get ', 'set '];
+const ACCESSOR_WORDS = ['get', 'set', 'get', 'set', 'static', 'readonly', 'accessor', 'x', 'type', 'of', 'new', 'in', 'default'];
+const ACCESSOR_NAMES = ['a', 'this', 'a?', 'A.b', '1', "'x'", 'type', 'get', 'new', 'in', '\u00e9', 'a, b', 'x1'];
+const ACCESSOR_COMMAS = [',', ':', '?,', '?:', ',\n', ', // note\n', ': // note\n', ' ,', ', /* c */ ', ', // note:\r\n'];
+const ACCESSOR_REGEXES = [`/[${HOLDING_BODY}]/`, `/[</T>;${CALL};\\/\\/]/`, `/[</T>;${CALL}//]/.source`, `/x[</T>;${CALL}//]/`];
+const ACCESSOR_TAILS = [']()', '](): string', ']: string', '](v)', ']?: A', ']', '] = 1', '](): A;\n q: T'];
+function accessorNamePages(seed, count) {
+ const rng = mulberry32(seed);
+ const pages = [];
+ const seen = new Set();
+ for (let i = 0; i < count; i += 1) {
+ const gap = () => pick(rng, IMPORT_PAREN_GAPS);
+ const member = `${pick(rng, ACCESSOR_MODIFIERS)}${pick(rng, ACCESSOR_WORDS)}${gap()}[${gap()}${pick(rng, ACCESSOR_NAMES)}${pick(rng, ACCESSOR_COMMAS)}${gap()}${pick(rng, ACCESSOR_REGEXES)}${pick(rng, ACCESSOR_TAILS)}`;
+ const code = `${pick(rng, CODE_FRAMES)(pick(rng, NESTED_SEPARATORS), member)}\n${CALL};\n`;
+ if (seen.has(code)) continue;
+ seen.add(code);
+ pages.push({ code, label: `accessor name / ${JSON.stringify(member)}` });
+ }
+ return pages;
+}
+
+module.exports = { numberedMemberPages, nestedTextPages, expressionLinePages, literalTagPages, nestedSoupPages, nestedCodePages, nestedTagPages, nestedPairPages, taggedStringPages, importTypePages, accessorNamePages, NUMBER_NAMES };
diff --git a/plugins/model-apps/scripts/tests/helpers/jsx-element-fuzz.js b/plugins/model-apps/scripts/tests/helpers/jsx-element-fuzz.js
index 01f7b46dc..a1b01e3d4 100644
--- a/plugins/model-apps/scripts/tests/helpers/jsx-element-fuzz.js
+++ b/plugins/model-apps/scripts/tests/helpers/jsx-element-fuzz.js
@@ -12,7 +12,7 @@
// cases written by hand (an attribute string with a backslash-quote, so that JavaScript's strings and JSX's end in different places). A seeded generator
// makes a failure reproducible.
-const { CALL, DECOYS, SIGNATURE_FRAMES, ELEMENT_FRAMES } = require('./angle-frames.js');
+const { CALL, DECOYS, SIGNATURE_FRAMES, ELEMENT_FRAMES, PROSE_COMMENT_LINES, PROSE_PATHS } = require('./angle-frames.js');
function mulberry32(seed) {
let a = seed >>> 0;
@@ -361,6 +361,17 @@ const HIDING_MEMBERS = [
// A string right after a keyword, with no white space between: its quote is no apostrophe.
"readonly'a</NAME>': number", "m: keyof'a</NAME>'", "m: T extends'a</NAME>' ? 1 : 2", "m: { [K in'a</NAME>']: T }", "m: { get'a</NAME>'(): T }",
];
+// Members of a type that read like the prose of an element — a URL or a label, a name and a note, with the closing tag of the head in the comment, and a type on the next line that makes it one — and the same without the closing tag.
+const PROSE_HIDING_MEMBERS = ['https: // </NAME>\n string', 'see: // </NAME>\n T', 'a // </NAME>\n b: T', 'type: // </NAME>\n string', 'default: // </NAME>\n string', 'new // </NAME>\n x: T', 'readonly // </NAME>\n x: T',
+ 'a:\n // </NAME>\n string', 'a: b // </NAME>\n c: d', 'a? // </NAME>\n : T', 'a: A\n | B // </NAME>', 'x: https: // </NAME>\n string'];
+const PROSE_TYPE_MEMBERS = ['https: // c\n string', 'see: // c\n T', 'a // c\n b: T', 'type: // c\n string', 'a: b // c\n c: d', 'a? // c\n : T', 'a: A\n | B // c', 'a\n // c\n b'];
+
+// What a reader of a page writes after `(a);`: lines of prose with a comment in them and a path (PROSE_COMMENT_LINES, PROSE_PATHS), which no type has for its members, so that an element reads it for certain wherever it compiles
+// (typeMembersFail). The text ends with a line break, so that the closing tag after it is in no comment.
+function proseTail(rng, decided) {
+ const lines = Array.from({ length: between(rng, 1, 3) }, () => (chance(rng, 0.35) ? pick(rng, PROSE_PATHS) : pick(rng, PROSE_COMMENT_LINES)));
+ return { text: `${lines.join(pick(rng, ['\n ', '\n']))}\n`, plain: true, risky: !decided, prose: decided };
+}
// One piece of JSX text, with whether the lexer may be unable to read it to its end (a back-tick or a slash that could hide the closing tag; a container it does not read).
function jsxPiece(rng) {
@@ -373,19 +384,21 @@ function jsxPiece(rng) {
return [pick(rng, NESTED_ELEMENTS), false];
}
-// What follows the head's `)` and the separator: JSX text (40%), members (45%), or a bit of each. `plain` is JSX alone; `risky` is where the lexer may say nothing.
+// What follows the head's `)` and the separator: prose with comments and paths (15%), JSX text (30%), members (45%), or a bit of each. `plain` is JSX alone; `risky` is where the lexer may say nothing.
function signatureTail(rng, name) {
const roll = rng();
const jsx = (n) => Array.from({ length: n }, () => jsxPiece(rng));
const members = (n) => Array.from({ length: n }, () => {
const kind = rng();
- return kind < 0.3 ? pick(rng, TYPE_MEMBERS) : kind < 0.5 ? pick(rng, HIDING_MEMBERS) : pick(rng, memberForms(rng, 1))();
+ return kind < 0.25 ? pick(rng, TYPE_MEMBERS) : kind < 0.4 ? pick(rng, HIDING_MEMBERS) : kind < 0.5 ? pick(rng, PROSE_HIDING_MEMBERS) : kind < 0.55 ? pick(rng, PROSE_TYPE_MEMBERS) : pick(rng, memberForms(rng, 1))();
});
let tail;
- if (roll < 0.4) {
+ if (roll < 0.15) {
+ tail = proseTail(rng, chance(rng, 0.8));
+ } else if (roll < 0.45) {
const pieces = jsx(between(rng, 0, 4));
tail = { text: pieces.map(([text]) => text).join(pick(rng, ['', ' ', '\n'])), plain: true, risky: pieces.some(([, risky]) => risky) };
- } else if (roll < 0.85) {
+ } else if (roll < 0.88) {
tail = { text: members(between(rng, 0, 3)).join(pick(rng, ['; ', ',\n ', '\n ', ';\n ', ', ', ' '])), plain: false, risky: true };
} else {
const pieces = jsx(between(rng, 1, 2));
@@ -422,6 +435,7 @@ function* signaturePrograms(seed, count) {
yield {
kind: 'element', code: `${elementFrame.replace('@', `${head}${parameters}${separator}${tail.text}</${name}>`)}\n${decoy}\n${CALL};\n`, at, after: at + name.length + 2, name,
precise: tail.plain && !tail.risky && !head.includes('/') && !separator.includes('/') && !parameters.includes('<') && !MAY_HOLD_EXPRESSION.test(parameters) && !COLON_NEXT.test(`${separator}${tail.text}`),
+ prose: tail.prose === true,
};
}
}
@@ -537,7 +551,7 @@ function judgeSignatures(ts, { opens, children }, programs) {
programs: 0, valid: 0, failing: 0,
signature: { valid: 0, code: 0, guess: 0, element: 0 },
element: { valid: 0, code: 0, guess: 0, element: 0 },
- precise: { valid: 0, guessed: [] },
+ precise: { valid: 0, prose: 0, guessed: [] },
unsound: [], unjustified: [],
};
for (const program of programs) {
@@ -552,6 +566,7 @@ function judgeSignatures(ts, { opens, children }, programs) {
if (program.kind === 'signature' ? side === 'element' : side === 'code') stats.unsound.push({ kind: program.kind, code: program.code });
if (program.kind === 'element' && program.precise) {
stats.precise.valid += 1;
+ if (program.prose) stats.precise.prose += 1;
if (side !== 'element') stats.precise.guessed.push(program.code);
}
} else if (program.kind === 'element' && side === 'code') {
diff --git a/plugins/model-apps/scripts/tests/helpers/live-shaped-pages.js b/plugins/model-apps/scripts/tests/helpers/live-shaped-pages.js
new file mode 100644
index 000000000..5136aa93a
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/live-shaped-pages.js
@@ -0,0 +1,137 @@
+'use strict';
+
+// Pages shaped like the ones a generative-page author writes, each valid TSX with one real navigation call in a handler — the call the build must resolve. They hold the text that the lexer's reading of a `<` and of
+// a `/` is about: JSX text that starts with a parenthesis (a note, a hint, a URL, a path, a link), a method whose type parameters follow a name, and a callee in parentheses.
+// - RESOLVED_PAGES are read for certain: the one real call is resolved, and nothing else is.
+// - REFUSED_PAGES have a call signature whose default value puts a `/` after a line comment, where a regex may begin: whether it does decides where the parameter list ends, or whether a closing tag is hidden in
+// the regex, so a token that is data cannot be told from a call, and the build halts on the page. (The released lexer refuses one of the two and reads the other wrong.)
+//
+// No page holds a real environment, tenant or person.
+const page = (...lines) => `${lines.join('\n')}\n`;
+const IMPORTS = ["import * as React from 'react';", 'declare const navigateTo: (input: unknown) => void;'];
+const CALL = 'navigateTo({ pageType: "generative", pageId: "PAGEREF_detail" })';
+const HANDLER = ` const open = () => ${CALL};`;
+const RETURN = ' return <div><button onClick={open}>Detail</button></div>;';
+const COMPONENT = ['const GeneratedComponent = () => {', HANDLER, RETURN, '};', 'export default GeneratedComponent;'];
+// The same, with the element that the page declares shown before the button.
+const withElement = (declaration, shown) => page(...IMPORTS, 'const GeneratedComponent = () => {', ` ${declaration.replace(/\n/g, '\n ')}`, HANDLER, ` return <div>${shown}<button onClick={open}>Detail</button></div>;`, '};', 'export default GeneratedComponent;');
+
+const RESOLVED_PAGES = [
+ // `async<T>(x: T)` is a method named `async` with type parameters: its `<T>` is no element and no cast.
+ { name: 'a method named like a modifier, with type parameters', code: page(...IMPORTS, 'const o = { async<T>(x: T) { return x; } };', 'const GeneratedComponent = () => {', HANDLER, ' void o;', RETURN, '};', 'export default GeneratedComponent;') },
+ // A regex in the text of an element is text.
+ { name: 'JSX text that has a regex-like default in it', code: page(...IMPORTS, 'const note = <p>(a = /x/)</p>;', 'const GeneratedComponent = () => {', HANDLER, ' return <div>{note}<button onClick={open}>Detail</button></div>;', '};', 'export default GeneratedComponent;') },
+ // A callee in parentheses: the `(` after `return` is no parameter list.
+ { name: 'a callee in parentheses', code: page(...IMPORTS, 'const GeneratedComponent = () => {', ` const open = () => { return (navigateTo)({ pageType: "generative", pageId: "PAGEREF_detail" }); };`, RETURN, '};', 'export default GeneratedComponent;') },
+ {
+ name: 'JSX text that starts with a parenthesis and holds links, a keyword, a number',
+ code: page(...IMPORTS, 'declare const user: { name: string };', 'declare const profile: string;', 'const h1 = <small>(Size: 10 MB max, <a href="/x">upgrade</a>)</small>;', 'const h2 = <small>(Name: {user.name}, <a href={profile}>edit</a>)</small>;',
+ 'const h3 = <small>(Mode: new <a href="/x">beta</a>)</small>;', 'const h4 = <small>(Hint: import <a href="/x">docs</a>)</small>;', 'const h5 = <small>(Tip: use <code>=</code>)</small>;', 'const GeneratedComponent = () => {', HANDLER,
+ ' return <div>{h1}{h2}{h3}{h4}{h5}<button onClick={open}>Detail</button></div>;', '};', 'export default GeneratedComponent;'),
+ },
+ { name: 'JSX text with an `=` and a nested element, and an attribute named like a keyword', code: page(...IMPORTS, 'declare const Flag: (props: { extends?: boolean }) => JSX.Element;', 'const n1 = <p>(a = <b>c</b>)</p>;', 'const f1 = <Flag extends />;', 'const GeneratedComponent = () => {', HANDLER, ' return <div>{n1}{f1}<button onClick={open}>Detail</button></div>;', '};', 'export default GeneratedComponent;') },
+ // The text after `(a);` is lines of prose: a URL, a path that starts a line. No type has them for its members, so no closing tag is hidden in a regex that begins at the path.
+ { name: 'a note, a URL on its own line, and a path that starts a line', code: withElement('const e = <p>(a);\n https://contoso.com\n /b</p>;', '{e}') },
+ { name: 'a note, a label and a URL, and a path that starts a line', code: withElement('const e = <p>(a);\n Docs: https://contoso.com/help\n /b</p>;', '{e}') },
+ { name: 'a note, a comma, a word with a comment, and a path that starts a line', code: withElement('const e = <p>(a),\n b // c\n /d</p>;', '{e}') },
+ { name: 'a note, a line break, a URL, and a path that starts a line', code: withElement('const e = <p>(a)\n https://contoso.com/x\n /b</p>;', '{e}') },
+ // A bracket where a member would begin is no member (TS1131), so nothing after it is a type's.
+ { name: 'a note, a bracketed word and a URL, and a path that starts a line', code: withElement('const e = <p>(a);\n [x] https://contoso.com\n /b</p>;', '{e}') },
+ // A link is an element with an attribute, which no type has the tag of: its text is JSX text, and a URL, an apostrophe, a back-tick or a comment opener in it opens nothing, whatever stands after the link.
+ { name: 'a hint that holds a link whose text is a URL', code: withElement('const e = <p>(Docs: <a href="https://contoso.com/help">https://contoso.com/help</a>)</p>;', '{e}') },
+ { name: 'a note that holds a link whose text has an apostrophe and a back-tick, and a second link', code: withElement("const e = <p>(a); <a href=\"/x\">it's `quick`</a> and <a href=\"/y\">that's</a></p>;", '{e}') },
+ { name: 'a note that holds a link whose text opens a comment, and a path that starts a line', code: withElement('const e = <p>(a), <a href="/x">/* tip</a> done\n /b</p>;', '{e}') },
+ { name: 'a hint that holds a link, a line comment in its text, and a quote after it', code: withElement("const e = <p>(a)\n <a href=\"/x\">see // here</a> 'not a string</p>;", '{e}') },
+ // A button, a label and a link whose attribute has a keyword for its name or its value (`type="button"`, `for="x"`, `as="span"`) are elements to every reading: the text in them is JSX text, and nothing after them is guessed.
+ { name: 'a note that holds a button, a label and a link with keyword attributes', code: withElement("const e = <p>(a); <button type=\"button\">see https://contoso.com</button> <label for=\"x\">it's</label> <Link as=\"span\" href=\"/x\">`t</Link> `u`</p>;", '{e}') },
+ { name: 'a note, a fragment after a comma, and a path that starts a line', code: withElement('const e = <p>(a), <>x // y</> and\n /b</p>;', '{e}') },
+ // A line that opens a parenthesis, or ends in an initializer, after a note: no type has it for a member where its `(` opens a parameter list that a `/` fails, or after an `=` where no member of a type begins.
+ { name: 'a note and a line that opens a parenthesis, then a comment and a path on the next line', code: withElement('const e = <p>(optional);\n foo( // note\n /docs</p>;', '{e}') },
+ { name: 'a note and a line that opens a parenthesis, where a member of a type may begin (after `return`)', code: page(...IMPORTS, 'const GeneratedComponent = () => {', HANDLER, ' return <p>(optional);', ' foo( // note', ' /docs <button onClick={open}>Detail</button></p>;', '};', 'export default GeneratedComponent;') },
+ { name: 'a note and a line that ends in an initializer, then a comment and a path on the next line', code: withElement('const e = <p>(optional);\n x = // note\n /docs</p>;', '{e}') },
+ // A tag whose attributes each stand on a line of its own, as prettier writes one, has every `=` on the line of its word: no member of a type is that, so the tag is an element's, and the URL, the apostrophe and the comment opener in its
+ // text open nothing. A fragment on a line of its own after an operator, a separator or a tag stands where no operand ends.
+ { name: 'a hint that holds a link whose attributes are on lines of their own, with a URL in its text', code: withElement('const e = <p>(optional){" "}\n <a\n href="https://contoso.com/help"\n target="_blank"\n rel="noreferrer"\n >\n see https://contoso.com\n </a>\n</p>;', '{e}') },
+ { name: 'a hint that holds a fragment on a line of its own after a tag, with an apostrophe and a URL in its text', code: withElement("const e = <p>(optional)\n <b>x</b>\n <>it's https://contoso.com/x</>\n</p>;", '{e}') },
+ // After a `:` a `[` opens a tuple type, whose first type is no `/`: the note, the unfinished line and the path on the next line are no type's, where a member of a type may begin (after `return`).
+ { name: 'a note and a line that opens a bracket after a colon, where a member of a type may begin (after `return`)', code: page(...IMPORTS, 'const GeneratedComponent = () => {', HANDLER, ' return <p>(optional);', ' Total: [ // note', ' /docs <button onClick={open}>Detail</button></p>;', '};', 'export default GeneratedComponent;') },
+];
+
+// A call signature whose default value has a `/` on the line after a line comment: a regex may begin there, and TypeScript reads one. In the first page the regex holds the `)` that would end the parameter list, and the
+// string after the list holds the closing tag of the signature's head and a token that is data; in the second the regex holds the closing tag and the token. A lexer that read the `/` as a division, or the head as an element,
+// took the closing tag for its own and rewrote the token that is data as well as the real call.
+const DECOY = '</T>;navigateTo({ pageType: "generative", pageId: "PAGEREF_detail" })//';
+const REFUSED_PAGES = [
+ {
+ name: 'a default value whose regex follows a line comment, in a signature',
+ code: page(...IMPORTS, 'interface Callable { <T>(a = 1 + // fallback', ' /[)]/); m: \'' + DECOY + '\' }', ...COMPONENT),
+ },
+ {
+ name: 'a method whose default holds the closing tag in a regex after a line comment',
+ code: page(...IMPORTS, 'interface Callable { <T>(x); m(a = 1 + // fallback', ' /[' + DECOY + ']/): void }', ...COMPONENT),
+ },
+];
+
+// A call signature `<T>(x)` and the text after it, which the lexer reads to the closing tag `</T>` that an element would end at, and that a type with the same text for its members may hold in a string, a template, a
+// comment or a regex. Each page below is valid to TypeScript's parser (the type checker rejects an initializer or a computed name in a type; the parser and a transpile do not), has one real call after the type, and
+// holds a token in the type that is data: it is in a string, a template or a regex that holds the closing tag. A lexer that took the head for an element rewrote that token as well as the real call, so each page is
+// refused, with the `generic` guess at the `<` of the head, and nothing in it is rewritten.
+// - A member named by a number: `1e-5` is ONE numeric literal to the scanner (scanNumber, a sign after the `e` is part of it), a valid name, so the type exists and its string holds the closing tag.
+// - The text of a nested element in an expression of a member — a default value or a computed name. A type reads the element, which has no comment or string in its text, and code goes on after the closing tag of the
+// nested element: a `//`, a `/*`, a quote or a back-tick in its text opens nothing that reaches past the closing tag, and the operator after it is what decides whether the `/` on the next line begins a regex.
+// The released lexer reads the pages with a quote, a back-tick or a comment in the nested text wrong too; the pages with a signed exponent it refuses.
+const CALL_NO_SPACE = 'navigateTo({pageType:"generative", pageId:"PAGEREF_detail"});';
+const HOLD = `'</T>;${CALL_NO_SPACE}//'`;
+const TEMPLATE = `\`\n</T>;${CALL_NO_SPACE}//\``;
+const REGEX = `/[</T>;${CALL_NO_SPACE}//]/`;
+const typePage = (type) => `interface I { <T>(x); ${type} }\n${CALL_NO_SPACE}\n`;
+const HIDDEN_CLOSING_TAG_PAGES = [
+ { name: 'a member named by a number with a signed exponent', code: typePage(`1e-5: ${HOLD}`) },
+ { name: 'a member named by a number with a positive exponent, and a method type', code: `interface I { <T>(x), 1E+5(): ${HOLD} }\n${CALL_NO_SPACE}\n` },
+ { name: 'a construct signature, a line break, and a member named by a number with a signed exponent and an underscore', code: `interface I { new <T>(x)\n 1_0e+1?: ${HOLD} }\n${CALL_NO_SPACE}\n` },
+ { name: 'a line comment in a nested element, an operator, and a regex on the next line that holds the closing tag', code: typePage(`m(a = <b>x // y</b> +\n${REGEX}): void`) },
+ { name: 'a line comment in a nested element in a computed name', code: typePage(`[<b>x // y</b> +\n${REGEX}.source]: string`) },
+ { name: 'a line comment in a nested fragment, a real comment, and a regex', code: typePage(`[<>x // y</> ||\n // more\n${REGEX}]: string`) },
+ { name: 'a quote in a nested element, an operator, and a string that holds the closing tag', code: typePage(`m(a = <b>'x</b> + ${HOLD}): void`) },
+ { name: 'a quote in a nested element in an element, an operator, and a string that holds the closing tag', code: typePage(`m(a = <b><i>'x</i></b> + ${HOLD}): void`) },
+ { name: 'a quote in a nested element in a computed name', code: typePage(`[<b>'x</b> + ${HOLD}]: string`) },
+ { name: 'a quote in a nested element in an initializer', code: typePage(`m: A = <b>'x</b> + ${HOLD}`) },
+ { name: 'a quote in a nested fragment, a block comment, and a string that holds the closing tag', code: typePage(`m(a = <>'x</> + /* c */ ${HOLD}): void`) },
+ { name: 'a back-tick in a nested element, an operator, and a template that holds the closing tag', code: typePage(`m(a = <b>\`x</b> + ${TEMPLATE}): void`) },
+ { name: 'a line comment in a nested element, an operator, and a template that holds the closing tag', code: typePage(`m(a = <b>x // y</b> + ${TEMPLATE}): void`) },
+ // A string, a template or a regex that holds the text of an element is one token, whose quote ends it: the string after it holds the closing tag.
+ { name: 'a string that holds an element, an operator, and a string that holds the closing tag', code: typePage(`m(a = '<b>c</b>' + ${HOLD}): void`) },
+ { name: 'a template that holds an element, an operator, and a template that holds the closing tag', code: typePage(`m(a = \`<b>c</b>\` + ${TEMPLATE}): void`) },
+ { name: 'a regex that holds an element, an operator, and a string that holds the closing tag', code: typePage(`m(a = /<b>c<\\/b>/ + ${HOLD}): void`) },
+ { name: 'a fragment in one string and its closing tag in a template, then a template that holds the closing tag', code: typePage(`m(a = '<>' + \`</>\` && ${TEMPLATE}): void`) },
+ // A nested tag that is no element: the type arguments of a name, a comparison, the type parameters of a signature. The text after its `>` is code, and its closing tag is in a string that comes before the one that holds
+ // the closing tag of the head, so that quote is the end of one string and the start of the next — where an element would take it for text.
+ { name: 'type arguments, and a string that holds their closing tag before the string that holds the closing tag of the head', code: typePage(`m: Array<b> = '</b>' + ${HOLD}`) },
+ { name: 'type arguments in a member of its own, and a string that holds their closing tag', code: typePage(`m: A<b>; n: '</b>' | ${HOLD}`) },
+ { name: 'a comparison, and a string that holds the closing tag of its element', code: typePage(`m: A = a<b>c; n: '</b>' | ${HOLD}`) },
+ { name: 'the type parameters of a signature, and a string that holds their closing tag', code: typePage(`<b>(y): '</b>'; q: ${HOLD}`) },
+ { name: 'the type parameters of a signature with a constraint, and a string that holds their closing tag', code: typePage(`<U extends A>(y): '</U>'; k: ${HOLD}`) },
+ // A tag with a keyword of TypeScript's in it is code to a type — a modifier of a type parameter (`<public U>`), an operator in a comparison (`a <b in c>`), a type operator in type arguments (`Array<keyof X>`) — and so is an empty
+ // pair of angle brackets after a name, a call or a bracket, or before a parenthesis (`<>(y)`, `f(x)<>`): the text after the `>` is code, and a string there holds the closing tag. (The parser accepts them all; the checker does not.)
+ { name: 'a type parameter with a modifier, and a string that holds its closing tag', code: typePage(`<public U>(y): '</public>'; q: ${HOLD}`) },
+ { name: 'a type parameter with a modifier after a name, and a string that holds its closing tag', code: typePage(`m<static U>(y): '</static>'; q: ${HOLD}`) },
+ { name: 'a comparison with `in` between two names in a default, and a string that holds the closing tag of its element', code: typePage(`m(p = x <a in b> '</a>' + ${HOLD}): void`) },
+ { name: 'a comparison with `typeof` after the `<` in a default, and a string that holds the closing tag of its element', code: typePage(`m(p = x <typeof U> '</typeof>' + ${HOLD}): void`) },
+ { name: 'type arguments with a type operator in a type, and a string that holds their closing tag', code: `type X = { a: 1 };\ninterface I { <T>(x); m: Array<keyof X>; n: '</keyof>'; q: ${HOLD} }\n${CALL_NO_SPACE}\n` },
+ { name: 'empty type parameters before a parenthesis, and a string that holds their closing tag', code: typePage(`<>(y): '</>'; q: ${HOLD}`) },
+ { name: 'empty type arguments after a call in a default, and a string that holds their closing tag', code: typePage(`m(p = f(x)<> || '</>' + ${HOLD}): void`) },
+ // Two regions that end at one place — two line comments on a line, each opened in the text of an element of its own — are two crossings of the closing tags between them, told by where each starts.
+ { name: 'two line comments on one line in two nested elements, an operator, and a template that holds the closing tag', code: typePage(`m(a = <b>//</b> - <i>//</i> ?? ${TEMPLATE}): void`) },
+ { name: 'two line comments on one line in two nested elements in a computed name, and a regex that holds the closing tag', code: typePage(`[<b>x // y</b> + <i>u // v</i> +\n${REGEX}]: string`) },
+ // A line break ends a member of a type, so a tag whose `=` stands on a line of its own — or whose valued `get` does — is an initializer that ends at the break and a member with an initializer of its own: the string after it holds
+ // the closing tag. A line comment may end in any character, so a fragment on the next line may follow an operand before it (`f // note:` and `<> || …` is `f<> || …`), and so may a number that ends in a dot (`1.<>`).
+ { name: 'a tag whose attribute has its `=` on a line of its own, in an initializer, and a string that holds the closing tag', code: typePage(`m: A = x <a\nhref\n="/x"> '</a>' + ${HOLD}`) },
+ { name: 'a tag whose valued `get` stands on a line of its own, in an initializer, and a string that holds the closing tag', code: typePage(`m: A = x <a\nget="/x"> '</a>' + ${HOLD}`) },
+ { name: 'a fragment after an operand and a line comment that ends in a colon, in a default, and a string that holds the closing tag', code: typePage(`m(p = f // note:\n<> || '</>' + ${HOLD}): void`) },
+ { name: 'a fragment after a number that ends in a dot, in a default, and a string that holds the closing tag', code: typePage(`m(p = 1.<> || '</>' + ${HOLD}): void`) },
+ // The `(` of an import type has no line-break rule: `typeof import` and a line break, then the path, which holds the closing tag. After `get` or `set` a `[` begins an accessor's computed name, an expression that a regex may hold.
+ { name: 'an import type with its `(` on the next line, and a path that holds the closing tag', code: typePage(`m: typeof import\n(${HOLD})`) },
+ { name: 'an accessor whose computed name holds a comma and a regex that holds the closing tag', code: typePage(`get [a, ${REGEX}](): string`) },
+];
+
+module.exports = { RESOLVED_PAGES, REFUSED_PAGES, HIDDEN_CLOSING_TAG_PAGES, DECOY };
diff --git a/plugins/model-apps/scripts/tests/helpers/misread-page.js b/plugins/model-apps/scripts/tests/helpers/misread-page.js
index 55b558856..632011dbd 100644
--- a/plugins/model-apps/scripts/tests/helpers/misread-page.js
+++ b/plugins/model-apps/scripts/tests/helpers/misread-page.js
@@ -192,6 +192,37 @@ const MISREAD_PAGES = {
'}',
),
},
+ // A line comment ends in the last word of its text, which is trivia: after `1 + // fallback` the last token is the `+`, so the `/` on the next line begins a regex, whose `)` is not the one that
+ // ends the parameter list. A lexer that took that `/` for a division — the last word is a name — ended the list at the `)`, read the string after it, which holds a closing tag and the text of a
+ // call, as code, and rewrote the token in it. The guess is reported at the `<` (`generic`), so the text in the string, and the call after it, are refused.
+ 'generic, a regex after a line comment': {
+ kind: 'generic',
+ frontier: (code) => code.indexOf('<T>'),
+ code: page(
+ 'export default function Page() {',
+ ` ${CALL}`,
+ ' interface Callable { <T>(a = 1 + // fallback',
+ ` /[)]/); m: '</T>;${CALL}//' }`,
+ ` ${CALL}`,
+ ' return null;',
+ '}',
+ ),
+ },
+ // The same after a call signature with no return type, whose text is read up to a closing tag: a later member's default holds, after a line comment, a regex that holds the closing tag and the
+ // text of a call. Read as a division, the `/` hid the closing tag no more, and the text after it was read as code.
+ 'generic, a regex that holds a closing tag after a line comment': {
+ kind: 'generic',
+ frontier: (code) => code.indexOf('<T>'),
+ code: page(
+ 'export default function Page() {',
+ ` ${CALL}`,
+ ' interface Callable { <T>(x); m(a = 1 + // fallback',
+ ` /[</T>;${CALL}//]/): void }`,
+ ` ${CALL}`,
+ ' return null;',
+ '}',
+ ),
+ },
// After the cut `>=`, TypeScript reads `<T extends X>(x: T): text</T>` as an element whose text starts with a parenthesis — and reads the same text as an arrow with a return type in
// another program (`let x: A<number>= <T extends X>(y: T): T => y`). Which program this is cannot be told for the `>` and `=` that may be a cut, so the element is read and the guess
// reported (`operator`), and the regex after it, which holds a token, is refused. With no parameter list, `<T extends X>text</T>` is an element in every program that parses — an
diff --git a/plugins/model-apps/scripts/tests/helpers/production-scripts.js b/plugins/model-apps/scripts/tests/helpers/production-scripts.js
new file mode 100644
index 000000000..b761962d4
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/production-scripts.js
@@ -0,0 +1,51 @@
+'use strict';
+// The plugin's own scripts — what a user's run can execute — for source-scan tests that pin "no script does X".
+//
+// Skipped: vendor/ (the generated SDK bundle), _vendor-build/ (its dev-only bundler), node_modules/, and tests/
+// (whose mock SDKs deliberately differ from the real one, and which name the very calls the scans look for).
+const fs = require('node:fs');
+const path = require('node:path');
+const { commentRanges } = require('../../lib/source-literals.js');
+
+const SCRIPTS_DIR = path.resolve(__dirname, '..', '..');
+const SKIPPED_DIRS = new Set(['vendor', '_vendor-build', 'node_modules', 'tests']);
+
+function productionScripts(dir = SCRIPTS_DIR) {
+ const files = [];
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (!SKIPPED_DIRS.has(entry.name)) files.push(...productionScripts(full));
+ } else if (entry.name.endsWith('.js')) {
+ files.push(full);
+ }
+ }
+ return files;
+}
+
+// A sentence in a comment that names a call is not a call. The comments are the ones the plugin's literal-aware lexer finds
+// (lib/source-literals.js commentRanges, the lexer the page checks use), so a `//` or `/*` inside a string, a template or a
+// regular expression — `'https://host'`, `'a // b'` — is never taken for one, and the code after it is still scanned. A pattern
+// matched with a line-start or line-end anchor would see each comment as blank space rather than as nothing: a comment is replaced
+// by spaces, its line breaks kept, so an offset or a line number in the result is the source's own.
+function withoutComments(source) {
+ const text = String(source);
+ let out = '';
+ let at = 0;
+ for (const { start, end } of commentRanges(text)) {
+ out += text.slice(at, start) + text.slice(start, end).replace(/[^\r\n]/g, ' ');
+ at = end;
+ }
+ return out + text.slice(at);
+}
+
+// The scripts (paths relative to scripts/, forward slashes) whose code — not comments — matches `pattern`.
+// `search`, not `test`: it ignores a /g pattern's lastIndex, which would skip a file after a match.
+function scriptsMatching(pattern) {
+ return productionScripts()
+ .filter((file) => withoutComments(fs.readFileSync(file, 'utf8')).search(pattern) !== -1)
+ .map((file) => path.relative(SCRIPTS_DIR, file).split(path.sep).join('/'))
+ .sort();
+}
+
+module.exports = { SCRIPTS_DIR, productionScripts, withoutComments, scriptsMatching };
diff --git a/plugins/model-apps/scripts/tests/helpers/read-probe.js b/plugins/model-apps/scripts/tests/helpers/read-probe.js
new file mode 100644
index 000000000..8850dcec2
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/read-probe.js
@@ -0,0 +1,47 @@
+'use strict';
+
+// Helpers for tests that watch HOW a reader is used — which reads were made, how many were in flight at once,
+// and in what order — rather than only what it answered.
+
+// One turn of the event loop. A timer's resolution is far coarser (about 15 ms on Windows), and the runs these
+// tests make involve hundreds of reads.
+const turn = () => new Promise((resolve) => setImmediate(resolve));
+
+// A small stable hash, so a read's latency depends on WHAT it reads and on the run's seed — never on when it
+// started — and the same seed delays the same reads however many are allowed at once.
+function hash(text) {
+ let h = 2166136261;
+ for (let i = 0; i < text.length; i++) {
+ h ^= text.charCodeAt(i);
+ h = Math.imul(h, 16777619) >>> 0;
+ }
+ return h;
+}
+
+// Wraps every method of `read` (an object of async functions): records the call, counts how many are in flight,
+// and delays the answer by `latency(call)` turns of the event loop. `stats.calls` is in the order the reads
+// STARTED; `stats.maxInFlight` is the most that were under way together.
+function instrument(read, { latency = () => 1 } = {}) {
+ const stats = { calls: [], inFlight: 0, maxInFlight: 0 };
+ const wrapped = {};
+ for (const [name, fn] of Object.entries(read)) {
+ wrapped[name] = async (...args) => {
+ const call = { name, args };
+ stats.calls.push(call);
+ stats.inFlight += 1;
+ stats.maxInFlight = Math.max(stats.maxInFlight, stats.inFlight);
+ try {
+ for (let turns = latency(call); turns > 0; turns--) await turn();
+ return await fn(...args);
+ } finally {
+ stats.inFlight -= 1;
+ }
+ };
+ }
+ return { read: wrapped, stats };
+}
+
+// The reads of a run as a sorted list: two runs made the same reads exactly when these are equal.
+const callKeys = (stats) => stats.calls.map((c) => JSON.stringify([c.name, c.args])).sort();
+
+module.exports = { turn, hash, instrument, callKeys };
diff --git a/plugins/model-apps/scripts/tests/helpers/type-member-texts.js b/plugins/model-apps/scripts/tests/helpers/type-member-texts.js
new file mode 100644
index 000000000..1a3137be6
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/type-member-texts.js
@@ -0,0 +1,204 @@
+'use strict';
+
+// Texts for the sweeps of what a type can hold for its members (source-literals.test.js, typeMembersFail). The text after the `)` of a call signature, `interface I { <T>(x)TEXT }`, is read up to the first thing that could hide
+// the closing tag of an element head `<T>` — a comment, a string, a template, a regex — and the reader may claim that no type has the text for its members, so that nothing hides the closing tag. The claim is TypeScript's
+// to judge: its parser's first diagnostic for the text must be at or before the thing that opens. These generators make the texts where a claim that is too eager is wrong:
+// - tokenTexts, drawnTexts: every text of up to `depth` tokens of a vocabulary of the pieces of a member and of what TypeScript rejects there, in order, and seeded draws of four to seven of them;
+// - memberTexts: runs of valid members — names, strings, numbers, computed names, signatures, modifiers, accessors, optional members, initializers — with separators, comments and line breaks, mutated at one or two
+// places, so that the texts are near-misses of types;
+// - keywordTexts: every keyword of TypeScript in each place of a member where a word may stand;
+// - bracketTexts: an operand that ends in a `)` or a `]`, in each place an expression stands, then a comment of every kind, where a `/` follows;
+// - wordTexts: every keyword after a `.`, `typeof`, `infer`, `keyof`, `readonly` and `unique`, then each thing that may follow a name or a type;
+// - numberWordTexts: a number of every spelling, then a word, a quote or a `/` with nothing between;
+// - importTypeTexts, drawnImportTypeTexts: `typeof import` and `import` with a line terminator, a space or a comment between every two tokens, in each place a type stands, and a type query on a name before a `(` on the next line;
+// - accessorNameTexts, drawnAccessorNameTexts: `get`, `set` and every other modifier before a computed name that holds a comma or a colon and a regex, with trivia between;
+// - tupleTexts: a `[` after a `:`, a type or an operator type, then trivia and a `/`.
+
+const { mulberry32 } = require('./jsx-element-fuzz.js');
+
+// What a member is made of, and what a text of prose may have in it: names and keywords, numbers of every spelling (a signed exponent is ONE token to the scanner), brackets, strings, tags, the operators.
+const BASE_TOKENS = ['a', '1', 'type', 'new', 'in', 'readonly', ':', ',', ';', ' ', '\n', '/* c */', '/* c\n */', '// c\n', '?', '.', '(', '-', "'a'", '\u00e9', '&', '|', '*', '1.5', 'extends'];
+const MORE_TOKENS = ['1e+5', '1e-5', '.5', '1.', '1e+', '0x1e', '[', ']', ')', '!', 'x!', '=', '=>', '<', '>', '<b>', '</b>', '#', '#x', '@', '{', '}', '"a"', "'a", '"a', '...', '||', '+', '%', '\\', '\u2014',
+ 'static', 'get', 'string', 'https', '(x)', '[x]', 'x = 1', '1 2', '<T>', '<T,U>', '`a`',
+ '&&', '==', '??', '?.', '<=', '>=', '++', '--', '**', '::', '</', '-1', 'keyof', 'typeof', 'unique', 'is', 'A.B', ': A', ': -1', ': A | B', ': A & B', ': keyof A',
+ 'infer', '\\u0061', '0x1F', '0b1'];
+const ALL_TOKENS = [...BASE_TOKENS, ...MORE_TOKENS];
+
+function* tokenTexts(tokens, depth, prefix = '') {
+ yield prefix;
+ if (depth > 0) for (const token of tokens) yield* tokenTexts(tokens, depth - 1, prefix + token);
+}
+function* drawnTexts(tokens, seed, count) {
+ const rng = mulberry32(seed);
+ for (let n = 0; n < count; n += 1) yield Array.from({ length: 4 + Math.floor(rng() * 4) }, () => tokens[Math.floor(rng() * tokens.length)]).join('');
+}
+
+// ─── Near-misses of types ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+const NAMES = ['a', 'b1', '$x', '_y', 'https', 'url', '\u00e9', 'new', 'type', 'in', 'default', 'readonly', 'static', 'get', 'set', 'of', 'is', 'class', 'return', 'abstract', 'async', 'declare', 'private', 'out', 'const'];
+const TYPES = ['string', 'A', 'A.B', "'lit'", '1', '-1', 'A[]', 'A | B', 'A & B', '[A, B]', '(A)', '{ x: A }', 'keyof A', 'typeof a', 'A<B>', 'readonly A[]', '`t${string}`', 'void', '(x: A) => B', 'new () => A', 'A extends B ? C : D',
+ 'unique symbol', 'infer U'];
+const PARAMS = ['', 'x', 'x: A', 'x?: A', '...x: A[]', 'x = 1', 'x: A, y?: B', 'this: A', '{ a }: B', '[a]: B'];
+const GAPS = [' ', ' ', ' ', '', '\n', '\n ', ' /* c */ ', ' // c\n', '\r\n', '\u2028', ' /* c\n */ '];
+const SEPARATORS = [';', ',', '\n', ';\n', ',\n', ' ; ', '\n\n', ';;', ';,'];
+const MODIFIERS = ['readonly', 'static', 'public', 'private', 'declare', 'abstract', 'async', 'accessor', 'override', 'in', 'out', 'default', 'export', 'const'];
+const NUMBERS = ['1', '1.5', '.5', '1e+5', '1e-3', '0x1F', '1_0'];
+const KEYS = ['k: string', 'x', 'a.b', 'Symbol.iterator', "'k'", '1', ''];
+const INITIALIZERS = ['1', 'a', "'s'", 'a + b', 'f(x)', '[1]', 'x as A', 'typeof x', '{}', '/re/', '`t`'];
+const MUTATIONS = ['!', '=', '|', '&', '?', '.', '@', '#', '#x', '<', '>', '</b>', '<b/>', '<b>', '(', ')', '[', ']', "'", '"', '`', '{', '}', ':', ',', ';', ' x', ' 1', "'a'", '1e+5', '...', '=>', '||', '/', '\\', '\u2014', '*',
+ '%', '+', '-', '~', '^', 'extends', 'typeof', 'in', 'is', 'as'];
+
+function* memberTexts(seed, count) {
+ const rng = mulberry32(seed);
+ const pick = (options) => options[Math.floor(rng() * options.length)];
+ const gap = () => pick(GAPS);
+ const member = () => {
+ const roll = rng();
+ const name = pick(NAMES);
+ const optionalType = () => (rng() < 0.5 ? `: ${pick(TYPES)}` : '');
+ if (roll < 0.14) return name;
+ if (roll < 0.27) return `${name}${gap()}:${gap()}${pick(TYPES)}`;
+ if (roll < 0.34) return `${name}?${gap()}:${gap()}${pick(TYPES)}`;
+ if (roll < 0.40) return `'${name}'${gap()}:${gap()}${pick(TYPES)}`;
+ if (roll < 0.44) return `${pick(NUMBERS)}${gap()}:${gap()}${pick(TYPES)}`;
+ if (roll < 0.50) return `[${pick(KEYS)}]${gap()}:${gap()}${pick(TYPES)}`;
+ if (roll < 0.58) return `${name}(${pick(PARAMS)})${rng() < 0.5 ? `${gap()}:${gap()}${pick(TYPES)}` : ''}`;
+ if (roll < 0.62) return `<T>(${pick(PARAMS)})${optionalType()}`;
+ if (roll < 0.66) return `new${gap()}(${pick(PARAMS)})${optionalType()}`;
+ if (roll < 0.74) return `${pick(MODIFIERS)}${gap()}${name}${gap()}:${gap()}${pick(TYPES)}`;
+ if (roll < 0.80) return `${pick(['get', 'set'])}${gap()}${name}(${pick(['', 'v: A'])})${gap()}:${gap()}${pick(TYPES)}`;
+ if (roll < 0.86) return `${name}${gap()}=${gap()}${pick(INITIALIZERS)}`;
+ if (roll < 0.92) return `${name}${gap()}:${gap()}${pick(TYPES)}${gap()}=${gap()}${pick(['1', 'a'])}`;
+ if (roll < 0.96) return `${name}<U>(${pick(PARAMS)})${optionalType()}`;
+ return `${name}${gap()}?`;
+ };
+ const mutate = (text) => {
+ let out = text;
+ const edits = 1 + (rng() < 0.4 ? 1 : 0);
+ for (let i = 0; i < edits; i += 1) {
+ const at = Math.floor(rng() * (out.length + 1));
+ const roll = rng();
+ if (roll < 0.5) out = out.slice(0, at) + pick(MUTATIONS) + out.slice(at);
+ else if (roll < 0.75 && out.length > 0) out = out.slice(0, at) + out.slice(at + 1 + Math.floor(rng() * 3));
+ else out = out.slice(0, at) + pick(MUTATIONS) + out.slice(at + 1);
+ }
+ return out;
+ };
+ for (let n = 0; n < count; n += 1) {
+ let text = pick(SEPARATORS);
+ const members = 1 + Math.floor(rng() * 4);
+ for (let m = 0; m < members; m += 1) text += pick(GAPS) + member() + (m < members - 1 ? pick(SEPARATORS) : pick(['', ' ', '\n', ';', ',', ';\n']));
+ yield rng() < 0.8 ? mutate(text) : text;
+ }
+}
+
+// ─── Every keyword, wherever a word may stand ───────────────────────────────────────────────────────────────────────────────────────────────────────
+// A word where a member begins, after a name, a type, an initializer's operand, a modifier, in a type, on the next line: whether it is a modifier, a name, an operator or an error is the parser's to say.
+const KEYWORD_SHAPES = [
+ (k) => `;\n ${k}`, (k) => `;\n ${k} b`, (k) => `;\n ${k}: A`, (k) => `;\n ${k}?: A`, (k) => `;\n ${k}(): A`, (k) => `;\n ${k}\n b`, (k) => `;\n ${k} ${k}`, (k) => `;\n ${k} 'b'`, (k) => `;\n ${k} 1`, (k) => `;\n ${k} [b]`,
+ (k) => `;\n a ${k}`, (k) => `;\n a: A ${k}`, (k) => `;\n a(): A ${k}`, (k) => `;\n a: A\n ${k}`, (k) => `;\n a?: ${k}`, (k) => `;\n a: ${k} b`, (k) => `;\n [a] ${k}`,
+ (k) => `;\n readonly ${k}`, (k) => `;\n readonly ${k} b`, (k) => `;\n static ${k}: A`, (k) => `;\n get ${k}()`,
+ (k) => `;\n a = 1 ${k}`, (k) => `;\n a = b ${k}`, (k) => `;\n a = 'b' ${k}`, (k) => `;\n a = (b) ${k}`, (k) => `;\n a = 1\n ${k}`, (k) => `;\n a = ${k}`, (k) => `;\n a = ${k} b`, (k) => `;\n a = 1 ${k} b`, (k) => `;\n a = 1 ${k} 2`,
+ (k) => `;\n a: A = 1 ${k}`, (k) => `;\n a = typeof ${k}`,
+ // A keyword in a type: after an operator, a `.`, a `|` or an `&`, twice, and before a second type.
+ (k) => `;\n a: A | ${k}`, (k) => `;\n a: A & ${k} b`, (k) => `;\n a: A.${k}`, (k) => `;\n a: ${k} ${k}`, (k) => `;\n a: keyof ${k}`, (k) => `;\n a: typeof ${k} b`, (k) => `;\n a: A\n | ${k}`, (k) => `;\n a: A\n ${k} b`,
+];
+// A character after a keyword — where a member begins, after a modifier or a name, and where a type must follow — on its line and the next.
+const KEYWORD_PUNCTUATION = ['*', '.', '!', '&', '|', '+', '-', '%', '^', '~', '@', '=', '?', ':', '(', ')', '[', ']', '<', ',', ';', '#', '\\', '||', '&&'];
+function* keywordTexts(keywords) {
+ for (const keyword of keywords) {
+ for (const shape of KEYWORD_SHAPES) yield shape(keyword);
+ for (const punctuation of KEYWORD_PUNCTUATION) yield* [`;\n ${keyword} ${punctuation}`, `;\n ${keyword}\n ${punctuation}`, `;\n a: ${keyword} ${punctuation}`, `;\n a: A ${punctuation} ${keyword}`, `;\n a: A ${keyword} ${punctuation}`];
+ }
+}
+
+// ─── A `/` after a bracket ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+// An expression in a default value, a computed name or an initializer that ends in a `)` or a `]` — a parenthesised expression, a call, an array, an index, an optional call — and then a comment of every kind, where the
+// probe's `/` stands. After the bracket the `/` divides, as it does after a name: a parser that has read an operand takes it for the operator. (After a `)` that ends the head of a statement it begins a regex, `if (a) /x/.test(b)`,
+// but a statement needs a block, whose braces the reading does not enter.) Operands that end in anything else — a template, a regex, a tag — are left to a regex, and are in the texts to show that nothing is claimed of them.
+const BRACKET_OPERANDS = ['(a)', '(a, b)', '((a))', 'f(a)', 'f(a, (b))', 'f()(g)', 'a[0]', 'a[b[0]]', '[1]', '[1, 2]', '[]', '()', '(a)[0]', 'a?.[0]', 'a?.(b)', 'new A()', '(a as B)', '(<b/>)', 'f(<b/>)', 'f(/x/)', '[/x/]', '(a /* c */)',
+ '(a // c\n)', '`t`', 'f(`t${a}`)', '/x/', '<b/>', 'a!', 'a++', 'this', '1'];
+const BRACKET_FRAMES = [(o) => `; m(a = ${o}`, (o) => `; m(a = 1 + ${o}`, (o) => `; [${o}`, (o) => `; [x, ${o}`, (o) => `; m(a = f(${o}`, (o) => `; m(a = q ? ${o}`, (o) => `; m: A = ${o}`, (o) => `;\n m(a = x ||\n ${o}`];
+const BRACKET_GAPS = ['', ' ', '\n ', ' // c\n ', ' /* c */ ', '\n // c\n ', ' /* c\n */ ', '\r\n', '\u2028 // c\u2029'];
+function* bracketTexts() {
+ for (const frame of BRACKET_FRAMES) for (const operand of BRACKET_OPERANDS) for (const gap of BRACKET_GAPS) yield frame(operand) + gap;
+}
+
+// Two keywords in a row, the first of the words that a type or a member may start with, and then each keyword: `abstract new`, `keyof typeof`, `readonly static`, `extends infer`.
+const FIRST_KEYWORDS = ['keyof', 'typeof', 'readonly', 'unique', 'infer', 'asserts', 'new', 'abstract', 'function', 'import', 'extends', 'is', 'in', 'out', 'static', 'get', 'set', 'declare', 'public', 'async', 'default', 'const',
+ 'export', 'accessor', 'override', 'private', 'protected', 'type', 'of', 'as', 'satisfies'];
+function* keywordPairTexts(keywords) {
+ for (const first of FIRST_KEYWORDS) {
+ for (const second of keywords) yield* [`;\n a: ${first} ${second}`, `;\n ${first} ${second}`, `;\n a: A ${first} ${second}`, `;\n a = 1 ${first} ${second}`, `;\n a: ${first}\n ${second}`];
+ }
+}
+
+// ─── A word where a name or a type must stand ───────────────────────────────────────────────────────────────────────────────────────────────────────
+// After a `.` any word is a name (`A.new`, `A.unique`); `typeof` takes an entity name and `infer` an identifier, so a keyword after them is a name too; `keyof`, `readonly` and `unique` take a type, which a word that no type
+// begins with is not. What the word is decides whether the `,` or the `;` after it ends a member, which is the difference between a type that goes on and one that fails there.
+const WORD_PREFIXES = ['A.', 'A.B.', 'typeof ', 'typeof A.', 'infer ', 'infer U extends ', 'keyof ', 'keyof keyof ', 'readonly ', 'unique ', 'keyof readonly ', 'keyof unique ', 'keyof typeof ', 'keyof infer ', 'A | ', 'A | A.'];
+const WORD_TAILS = [',', ';', '\n b', '\n b: A', ' | A', ' & A', '[]', '.B', ' ?', ' =', ' b', '<A>', ': A'];
+function* wordTexts(keywords) {
+ for (const keyword of keywords) for (const prefix of WORD_PREFIXES) for (const tail of WORD_TAILS) yield `;\n a: ${prefix}${keyword}${tail}`;
+}
+
+// ─── A number and a word right after it ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
+// A decimal literal that a name follows with no space is TS1351, and a hex, octal or binary one is not: the scanner ends it at its last digit, and `0x1Fin` is `0x1F` and `in`, an operator. After a word that is an operator
+// a `/` or a quote begins a regex or a string, and after an operand it divides or is an error: the reading must end the number where the scanner does.
+const NUMBER_SPELLINGS = ['0x1F', '0xE', '0x1e', '0b1', '0o7', '0x1Fn', '1', '1.5', '1e5', '1e+5', '.5', '1n', '1_0'];
+const NUMBER_WORDS = ['in', 'instanceof', 'as', 'satisfies', 'of', 'b', 'x1', '\u00e9', 'e', 'n', 'typeof', 'extends'];
+const NUMBER_TAILS = ["'", '\n /', ' /', '\n `', ' b', '=', ' in', '/'];
+function* numberWordTexts(keywords) {
+ for (const number of NUMBER_SPELLINGS) {
+ for (const word of [...NUMBER_WORDS, ...keywords]) for (const tail of NUMBER_TAILS) yield `;\n a = ${number}${word}${tail}`;
+ }
+}
+
+// ─── An import type, an accessor's computed name and a tuple that begins with a `/` ─────────────────────────────────────────────────────────────────────────
+// The `(` of an import type has no line-break rule (parseImportType), so `typeof import` and a line break, then `('./m')`, is one type, where after any other type the `(` on a new line begins a call signature; `get [` and
+// `set [` begin an accessor whatever line the `[` is on (canFollowGetOrSetKeyword), and its computed name is an expression, `[a, /x/]`, where after any other word that `[` is an index signature that no `/` follows; and a `[`
+// after a `:` or a type begins a tuple or an indexed access, whose first type is no `/`. Between each two tokens stands every kind of line terminator, a space of each kind and a comment, or nothing where the grammar allows it.
+const LINE_BREAKS = ['\n', '\r', '\r\n', '\u2028', '\u2029'];
+const WORD_GAPS = [...LINE_BREAKS, '\u0085', ' ', ' /* c */ ', ' /*\n*/ ', ' // c\n', ' // c\r\n', '\n ', '/**/'];
+const PAREN_GAPS = ['', ...WORD_GAPS, '\u00a0'];
+const IMPORT_LEADS = [';\n m: ', ';\n m?: ', ';\n m(): ', ';\n [k: string]: ', ';\n readonly m: ', ';\n m: A | ', ';\n m: A & ', ';\n m: keyof ', ';\n m: readonly ', ';\n m: (', ';\n get x(): ', ';\n new (): ', ';\n m(p: ', ';\n static m: ', ";\n 'k': ", ';\n 1: ', ';\n new: ', ';\n get: ', ';\n m: A.B | ', ',\n m: [A, '];
+const IMPORT_FORMS = [(g, p) => `typeof${g}import${p}`, (g, p) => `import${p}`, (g, p) => `keyof${g}typeof${g}import${p}`, (g, p) => `typeof${g}import${g}${p}`, (g, p) => `readonly${g}typeof${g}import${p}`];
+const IMPORT_PATHS = ["'./m'", '"./m"', '`./m`', "'./m', { with: { 'resolution-mode': 'import' } }", "'a</T>b'"];
+const IMPORT_TAILS = ['', '.X', '.X.Y', ' | A', ' & B', '[]', '<A>', '.X<A>', ';\n n: A', ',\n n: A', '\n n: A', ' extends B ? C : D', ')', ']', ')[]'];
+// A type query on a name, and a `(` on the next line: the type ends, and the `(` begins a call signature, whose first parameter a string is not.
+const TYPE_QUERY_FORMS = [(g) => `typeof${g}A.import`, (g) => `typeof${g}a`, (g) => `typeof${g}import_`, (g) => `typeof${g}importer`, (g) => `typeof${g}\u00e9mport`, (g) => `A${g}.import`];
+function* importTypeTexts() {
+ for (const lead of IMPORT_LEADS.slice(0, 3)) for (const form of IMPORT_FORMS.slice(0, 3)) for (const g of WORD_GAPS) for (const p of PAREN_GAPS) yield `${lead}${form(g, p)}('./m')`;
+ for (const form of TYPE_QUERY_FORMS) for (const g of WORD_GAPS) for (const p of LINE_BREAKS) yield `;\n m: ${form(g)}${p}('x')`;
+}
+function* drawnImportTypeTexts(seed, count) {
+ const rng = mulberry32(seed);
+ const pick = (options) => options[Math.floor(rng() * options.length)];
+ for (let n = 0; n < count; n += 1) yield `${pick(IMPORT_LEADS)}${pick(IMPORT_FORMS)(pick(WORD_GAPS), pick(PAREN_GAPS))}(${pick(PAREN_GAPS)}${pick(IMPORT_PATHS)}${pick(PAREN_GAPS)})${pick(IMPORT_TAILS)}`;
+}
+
+const ACCESSOR_MODIFIERS = ['', 'static ', 'readonly ', 'declare ', 'public ', 'private ', 'protected ', 'abstract ', 'override ', 'accessor ', 'async ', 'static readonly ', 'get ', 'set '];
+const ACCESSOR_WORDS = ['get', 'set', 'static', 'readonly', 'accessor', 'async', 'declare', 'new', 'x', 'type', 'of', 'in', 'is', 'as', 'default'];
+const COMPUTED_NAMES = ['a', 'a?', 'this', 'A.b', '1', "'x'", 'type', 'get', 'new', 'in', '\u00e9', 'a, b'];
+const COMPUTED_COMMAS = [',', ':', '?,', '?:', ' ,', ',\n', ', // note\n', ': // note\n', ', /* c */ '];
+const COMPUTED_REGEXES = ['/[</T>]/', '/b </T> /', '/b </T>'];
+const COMPUTED_TAILS = ['', ']', ']()', '](): string', ']: string', '](v)', ']?: A'];
+function* accessorNameTexts() {
+ for (const modifier of ['', 'static ', 'readonly ']) for (const word of ['get', 'set', 'static', 'readonly', 'x']) for (const g of PAREN_GAPS) for (const name of ['a', 'this', 'a?']) for (const comma of COMPUTED_COMMAS) {
+ yield `;\n ${modifier}${word}${g}[${name}${comma}${COMPUTED_REGEXES[0]}](): string`;
+ }
+}
+function* drawnAccessorNameTexts(seed, count) {
+ const rng = mulberry32(seed);
+ const pick = (options) => options[Math.floor(rng() * options.length)];
+ for (let n = 0; n < count; n += 1) {
+ yield `${pick([';\n ', ',\n ', ';\n m: A\n ', ';\n m(): A\n ', ';\n m\n '])}${pick(ACCESSOR_MODIFIERS)}${pick(ACCESSOR_WORDS)}${pick(PAREN_GAPS)}[${pick(PAREN_GAPS)}${pick(COMPUTED_NAMES)}${pick(COMPUTED_COMMAS)}${pick(PAREN_GAPS)}${pick(COMPUTED_REGEXES)}${pick(COMPUTED_TAILS)}`;
+ }
+}
+
+// A `[` after a `:`, a type, `keyof` or `readonly`, then trivia and a `/`: the first type of a tuple or an indexed access is none, and a `/` after a name is a division, not read.
+const TUPLE_LEADS = [';\n Total: ', ';\n m: A', ';\n m: A | ', ';\n m: keyof ', ';\n m: readonly ', ';\n m: A.B', ';\n m: typeof a', ';\n m: unique ', ';\n m\n ', ';\n m: A\n ', ';\n m?: ', ';\n m(): ', ';\n m: ', ';\n m: [A, '];
+function* tupleTexts() {
+ for (const lead of TUPLE_LEADS) for (const g of PAREN_GAPS) for (const h of PAREN_GAPS.slice(0, 8)) for (const after of ['/b </T> /', '/docs </T>', '/[</T>]/', 'a, /b </T> /', '] // c </T>']) yield `${lead}[${g}${h}${after}`;
+}
+
+module.exports = { BASE_TOKENS, MORE_TOKENS, ALL_TOKENS, tokenTexts, drawnTexts, memberTexts, keywordTexts, keywordPairTexts, bracketTexts, wordTexts, numberWordTexts, importTypeTexts, drawnImportTypeTexts, accessorNameTexts, drawnAccessorNameTexts, tupleTexts, LINE_BREAKS };
diff --git a/plugins/model-apps/scripts/tests/helpers/typescript-oracle.js b/plugins/model-apps/scripts/tests/helpers/typescript-oracle.js
index 11eacec29..8bcb44e7f 100644
--- a/plugins/model-apps/scripts/tests/helpers/typescript-oracle.js
+++ b/plugins/model-apps/scripts/tests/helpers/typescript-oracle.js
@@ -1,29 +1,37 @@
'use strict';
+const path = require('node:path');
+
+// A parser or lexer that a test is pointed at by an environment variable must load: a variable that is set and a package that is not there is a broken setup, and the tests that need it must FAIL, not skip — the CI job
+// that runs them (test-model-apps-lexer-oracles) would otherwise pass without running one. Unset, the loader answers null and the test skips.
+function loadFromEnv(name, what, file = '') {
+ const at = process.env[name];
+ if (!at) return null;
+ try {
+ return require(file ? path.join(at, file) : at);
+ } catch (error) {
+ throw new Error(`${name} is set to ${JSON.stringify(at)}, which does not load as ${what}: ${error.message}`);
+ }
+}
+
// The TypeScript parser that review snippets are checked against: the lexer's, and the navigation oracle's tolerance of
// type-only tails. The plugin ships dependency-free, so a checkout has none: point TYPESCRIPT_ORACLE_PATH at a
// `typescript` package to run those checks; they are skipped otherwise.
function loadTypescriptOracle() {
- const at = process.env.TYPESCRIPT_ORACLE_PATH;
- if (!at) return null;
- try {
- return require(at);
- } catch {
- return null;
- }
+ return loadFromEnv('TYPESCRIPT_ORACLE_PATH', 'a typescript package');
}
// The Babel parser, for the few places where compilers read the same text differently — a JSX attribute string written after white space is a
// string with escapes to TypeScript and one without to Babel and esbuild. Point BABEL_ORACLE_PATH at an `@babel/parser` package to run those
// checks; they are skipped otherwise.
function loadBabelOracle() {
- const at = process.env.BABEL_ORACLE_PATH;
- if (!at) return null;
- try {
- return require(at);
- } catch {
- return null;
- }
+ return loadFromEnv('BABEL_ORACLE_PATH', 'an @babel/parser package');
+}
+
+// The navigation resolver of the lexer before a change, for the sweeps that compare what each lexer reads (a page that the base resolves must be resolved here, and the pages it misreads show that the sweep sees a
+// misread). Point BASE_LIB_PATH at the scripts/lib directory of that release; the comparison is skipped otherwise.
+function loadBaseLexer() {
+ return loadFromEnv('BASE_LIB_PATH', 'the scripts/lib directory of a release (pageref-resolver.js)', 'pageref-resolver.js');
}
-module.exports = { loadTypescriptOracle, loadBabelOracle };
+module.exports = { loadTypescriptOracle, loadBabelOracle, loadBaseLexer };
diff --git a/plugins/model-apps/scripts/tests/helpers/valid-pages.js b/plugins/model-apps/scripts/tests/helpers/valid-pages.js
index 581842c28..da8c8b900 100644
--- a/plugins/model-apps/scripts/tests/helpers/valid-pages.js
+++ b/plugins/model-apps/scripts/tests/helpers/valid-pages.js
@@ -14,6 +14,8 @@
// - generic function types in every position, with every kind of parameter list;
// - destructured and default parameters.
+const { proseElements, PROSE_SHAPED_LINES, PROSE_OPEN_LINES, PROSE_HIDING_ELEMENTS, JSX_ONLY_ELEMENTS } = require('./angle-frames.js');
+
const NAVIGATION_CALL = 'navigateTo({pageType:"generative", pageId:"PAGEREF_detail"});';
// A page: `top` is module-level code (declarations), `body` the statements of the component before its navigation call. `ownDefault` says that `top` has the default export.
@@ -30,29 +32,30 @@ function page({ top = '', body = '', ownDefault = false }) {
].join('\n');
}
-// Where a value stands. `$` is the value.
+// Where a value stands. `$` is the value. The third entry says whether a member of a type may begin there, which a head in a type's members could be at: after a `,`, a `{`, `return`, `default` or a `?`. After an `=`, a `(`, a `[`, a
+// `:`, an `=>` or a binary operator none can, and a parameter list that neither `=>` nor `:` follows is an element for certain (source-literals.js, NO_MEMBER_BEFORE).
const VALUE_POSITIONS = [
- ['an initializer', (v) => ({ body: `const f = ${v};` })],
- ['an argument', (v) => ({ body: `g(${v});` })],
- ['a second argument', (v) => ({ body: `g(a, ${v});` })],
- ['a return value', (v) => ({ body: `function mk() { return ${v}; }` })],
- ['an array element', (v) => ({ body: `const r = [${v}];` })],
- ['an object value', (v) => ({ body: `const o = { k: ${v} };` })],
- ['a conditional branch', (v) => ({ body: `const c = cond ? ${v} : null;` })],
- ['the right side of ||', (v) => ({ body: `const d = a || ${v};` })],
- ['the right side of ??', (v) => ({ body: `const e = a ?? ${v};` })],
- ['parentheses', (v) => ({ body: `const p = (${v});` })],
- ['a cast', (v) => ({ body: `const u = ${v} as any;` })],
- ['a hook argument', (v) => ({ body: `const cb = React.useCallback(${v}, []);` })],
- ['a JSX attribute container', (v) => ({ body: `const el = <Cmp render={${v}} />;` })],
- ['a nested JSX attribute container', (v) => ({ body: `const el = <A><B render={${v}} /></A>;` })],
- ['an assignment', (v) => ({ body: `let w; w = ${v};` })],
- ['a class property', (v) => ({ top: `class K { f = ${v}; }` })],
- ['an export default', (v) => ({ top: `export default ${v};`, ownDefault: true })],
- ['a default parameter', (v) => ({ top: `function dp(cb = ${v}) {}` })],
- ['a template substitution', (v) => ({ body: `const t = \`a\${${v}}b\`;` })],
- ['a spread', (v) => ({ body: `const s = [...g(${v})];` })],
- ['an await', (v) => ({ body: 'async function aw() { await (' + v + '); }' })],
+ ['an initializer', (v) => ({ body: `const f = ${v};` }), false],
+ ['an argument', (v) => ({ body: `g(${v});` }), false],
+ ['a second argument', (v) => ({ body: `g(a, ${v});` }), true],
+ ['a return value', (v) => ({ body: `function mk() { return ${v}; }` }), true],
+ ['an array element', (v) => ({ body: `const r = [${v}];` }), false],
+ ['an object value', (v) => ({ body: `const o = { k: ${v} };` }), false],
+ ['a conditional branch', (v) => ({ body: `const c = cond ? ${v} : null;` }), true],
+ ['the right side of ||', (v) => ({ body: `const d = a || ${v};` }), false],
+ ['the right side of ??', (v) => ({ body: `const e = a ?? ${v};` }), false],
+ ['parentheses', (v) => ({ body: `const p = (${v});` }), false],
+ ['a cast', (v) => ({ body: `const u = ${v} as any;` }), false],
+ ['a hook argument', (v) => ({ body: `const cb = React.useCallback(${v}, []);` }), false],
+ ['a JSX attribute container', (v) => ({ body: `const el = <Cmp render={${v}} />;` }), true],
+ ['a nested JSX attribute container', (v) => ({ body: `const el = <A><B render={${v}} /></A>;` }), true],
+ ['an assignment', (v) => ({ body: `let w; w = ${v};` }), false],
+ ['a class property', (v) => ({ top: `class K { f = ${v}; }` }), false],
+ ['an export default', (v) => ({ top: `export default ${v};`, ownDefault: true }), true],
+ ['a default parameter', (v) => ({ top: `function dp(cb = ${v}) {}` }), false],
+ ['a template substitution', (v) => ({ body: `const t = \`a\${${v}}b\`;` }), true],
+ ['a spread', (v) => ({ body: `const s = [...g(${v})];` }), false],
+ ['an await', (v) => ({ body: 'async function aw() { await (' + v + '); }' }), false],
];
// Generic arrows, of every kind.
@@ -142,6 +145,32 @@ const MEMBERS = [
...SIGNATURE_MEMBERS, ...HIDDEN_CLOSING_MEMBERS,
];
+// Elements whose text starts with a parenthesis and a label, where the list that the text would be fails to parse as one — a number and a word (`10 MB`), an object type whose first member is no member (`{user.name}`),
+// `new` and `import` where a type must follow, an `=` before a closing tag — so that only the element compiles, and a default whose first token is a regex or an element, a division of a name or a number, or a template
+// with no `${`: read exactly, the `)` that ends the list is the one before the closing tag.
+const FAILING_LIST_ELEMENTS = [
+ '<p>(Size: 10 MB max, <a href="/x">upgrade</a>)</p>', '<p>(Size: -5 px, <b>x</b>)</p>', '<p>(Size: 1.5 GB, <b>x</b>)</p>', '<p>(Name: {user.name}, <a href={profile}>edit</a>)</p>', '<p>(Count: {items.length + 1}, <b>x</b>)</p>',
+ '<p>(Total: {a - b}, <b>x</b>)</p>', '<p>(Mode: new <a href="/x">beta</a>)</p>', '<p>(Mode: new feature, <b>x</b>)</p>', '<p>(Hint: import <a href="/x">docs</a>)</p>', '<p>(Hint: import from <b>CSV</b>)</p>',
+ '<p>(Tip: use <code>=</code>)</p>', '<p>(Tip: <b>a</b> <code>=</code> <b>b</b>)</p>',
+];
+const EXACT_INITIALIZER_ELEMENTS = ['<p>(a = /x/)</p>', '<p>(a = /[)]/)</p>', '<p>(a = b/(c))</p>', '<p>(score = 3/5)</p>', '<p>(a = <b>c</b>)</p>', '<p>(Status = <Badge>OK</Badge>)</p>', '<p>(a = `x`)</p>'];
+
+// Elements whose text starts with a parenthesis, a separator, a line with a `//` in it — a URL on a line of its own, a label and a URL, a name and a note, a keyword for either — and a line that starts with a `/`, a path.
+// A type that has the text for its members reads the `//` as a comment, so the `/` follows the token before it, and begins no regex that holds the closing tag: only the element compiles. The base read the last word of the
+// comment for that token, and resolved them (see angle-frames.js, PROSE_COMMENT_LINES).
+const PROSE_ELEMENTS = [...proseElements({
+ leads: [';\n ', ',', '\n '], paths: ['/b', '/ x'], ends: ['</p>'],
+ lines: ['https://contoso.com', 'http://x.y/z', 'Docs: https://contoso.com', 'default: https://contoso.com', 'in: https://contoso.com', 'b // note', '$x // note', 'type // note', 'new // note', 'return // note', 'get // note', 'a: b // c', 'x /* c */ // d',
+ '\u00e9 // note'],
+})];
+// The same, where the line before the `//` begins with a parenthesis, a bracket, a quote, a tag or an operator, ends in a `!`, a call or an index, has a number with a `.` or an exponent sign, or starts with a modifier that
+// no `:` follows (angle-frames.js, PROSE_LINE_CLASSES). Each fails as the members of a type where a member begins or after a name, or at the `/` that starts the next line, so only the element compiles; the base resolved
+// them by the word that ends the comment, and so does this lexer, by the reading of the type.
+const SHAPED_PROSE_ELEMENTS = [...proseElements({ leads: [';\n ', ','], lines: PROSE_SHAPED_LINES, paths: ['/b'], ends: ['</p>'] })];
+// The same, where the line before the `//` ends in an open `[`, an initializer's `=` or an operator in one: a regex may begin at the `/` of the next line, which a computed name, a default or an initializer of a type may hold, and the closing tag
+// may be inside it. Where no member of a type begins at the head the element is the only reading (a head after an `=`, a `(`, a `[`, a `:`, an `=>` or a binary operator), and where one may it is a guess (OPEN_LINE_PAGES).
+const PROSE_OPEN_ELEMENTS = [...proseElements({ leads: [';\n ', ','], lines: PROSE_OPEN_LINES, paths: ['/b'], ends: ['</p>'] })];
+
// Elements whose text starts with a parenthesis, as a page holds them — a hint after a label, a count, a translated label, a note with a link, several lines — and as a value in every place one stands. Each
// is JSX text that a call signature with no return type shares the start of: the reading turns on what comes after the `)` and, where a line break or a separator follows it, on the text to the closing tag.
const PARENTHESISED_ELEMENTS = [
@@ -172,13 +201,21 @@ const PARENTHESISED_ELEMENTS = [
// Text in which something may start an expression — an `=`, a `[`, an `@`, `import` — but no `/`, `<` or back-tick follows it: read exactly, as code holds no regex, JSX or template there.
'<p>(x = 5)</p>', '<p>(a: [b])</p>', '<p>(Ctrl = \u2318 on Mac)</p>', '<span>(@username)</span>', '<span>([optional])</span>', '<p>(tags: [a, b])</p>', '<button>(import)</button>',
'<li>(optional, <a href="/docs">see docs</a>)</li>',
+ // Attributes each on a line of its own, as prettier lays a tag out, and a fragment on a line of its own after a tag or a separator: no member of a type has a name and an `=` on two lines, and no operand ends where the fragment begins.
+ '<p>(optional){" "}\n <a\n href="https://x.y/docs"\n target="_blank"\n >\n see https://x.y\n </a>\n</p>', '<p>(see\n <a\n href="https://x.y/docs"\n target="_blank"\n >https://x.y/docs</a>)\n</p>',
+ '<p>(optional)\n <b>x</b>\n <>it\'s https://x.y</>\n</p>', '<p>(a);\n <>it\'s here</>\n</p>', '<p>(a), <b>x</b>,\n <>it\'s https://x.y</>\n</p>',
+ ...FAILING_LIST_ELEMENTS, ...EXACT_INITIALIZER_ELEMENTS, ...PROSE_ELEMENTS, ...SHAPED_PROSE_ELEMENTS, ...JSX_ONLY_ELEMENTS,
];
// The same, where something before the `)` may start an expression in a signature's parameter list (a default, a computed name, a decorator, an accessor's body, a constraint) and a `/`,
-// a `<` or a back-tick follows it, which may begin a regex, JSX or a template that holds a `)` of its own: the `)` that ends the list may be another, so the reading of the head is a guess.
-const INITIALIZER_ELEMENTS = ['<p>(a = /x/)</p>', '<p>(a = b/(c))</p>', '<p>(a = <b>c</b>)</p>', '<p>(a = `x`)</p>'];
+// a `<` or a back-tick follows it, which may begin a regex, JSX or a template that holds a `)` of its own, and the scan cannot read it exactly — the default's first token is no regex or element, a `/` follows
+// something that is no name or number (or a line comment, which may end in one: the last token is the one before the comment), a template holds a `${` — so the `)` that ends the list may be another, and the reading
+// of the head is a guess.
+const INITIALIZER_ELEMENTS = ['<p>(a = f(/x/))</p>', '<p>(a = (b)/c)</p>', '<p>(a = typeof /x/)</p>', '<p>(a = <b>c</b> / 2)</p>', '<p>(a = `${b}`)</p>', '<p>(a = x ? /y/ : z)</p>', '<p>(a = [/x/])</p>',
+ // A `/` after a line comment: the last token is the one before the comment, so the regex on the next line is no division, and a division there is not told from one.
+ '<p>(a = 1 + // c\n/[)]/)</p>', '<p>(a = b // c\n/ 2)</p>', '<p>(a = x || // c1\r\n/\\)/)</p>'];
// The same, where a `,`, `;` or line break follows the `)` and the text holds a comment, a template or a regex that is open at the closing tag, after text that a type could hold for its members: the closing tag
// could be inside it, in a type that has the same text, so the reading of the head is a guess. (A template after a member's colon is a type, `m: \`a${string}\``.)
-const HIDING_ELEMENTS = ['<p>(a); // c </p>', '<p>(a);\n /* c </p>', '<p>(a), x // c </p>', '<p>(a); m: `x ${y} </p>'];
+const HIDING_ELEMENTS = ['<p>(a); // c </p>', '<p>(a);\n /* c </p>', '<p>(a), x // c </p>', '<p>(a); m: `x ${y} </p>', ...PROSE_HIDING_ELEMENTS];
// Types that are not function types and hold a `<`, `>` or `{`.
const TYPE_DECLARATIONS = [
@@ -330,8 +367,9 @@ const EVERYDAY = [
'const h1: <T>(x: { /* c */ readonly a: T }) => T = g;', 'const h2: <T>(x: { a /* c */ : T }) => T = g;', 'const h3: <T>(x: { [k /* c */ : string]: T }) => T = g;', 'const h4: <T>(x: { m(a /* c */): T }) => T = g;',
// An element whose text starts with a parenthesis and holds an apostrophe, with a string on the same line after it.
"const q1 = cond ? <p>(a), it's</p> : 'none';", "const q2 = [<p>(a); the user's</p>, 'x'];", 'const q3 = <p>(a), 5" wide</p> + "x";',
- // An element whose first attribute is named `extends` and that closes at once: in a type the same `<T extends /` opens type parameters whose constraint is a regex.
- 'const e1 = <Flag extends />;', 'const e2 = <Flag extends/>;',
+ // An element whose first attribute is named `extends` and that closes at once: in a type the same `<T extends /` opens type parameters whose constraint is a regex. Where the regex does not close on its line
+ // it is unterminated, and only the element compiles; where another `/` on the line closes it, both do.
+ 'const e1 = <Flag extends />;', 'const e2 = <Flag extends/>;', 'const e3 = <Flag extends />; const r = a / b;',
];
// The pages. Each is { group, name, code }; the test drops those TypeScript does not parse.
@@ -359,7 +397,12 @@ function* validPages() {
}
for (const declaration of TYPE_ARGUMENT_EXPRESSIONS) yield { group: 'type arguments in an expression', name: declaration, code: page({ body: declaration }) };
for (const declaration of COMPONENTS) yield { group: 'component or hook', name: declaration, code: page({ body: declaration }) };
- for (const [position, place] of VALUE_POSITIONS) for (const element of [...PARENTHESISED_ELEMENTS, ...HIDING_ELEMENTS, ...INITIALIZER_ELEMENTS]) yield { group: 'parenthesised element', name: `${element} / ${position}`, element, code: page(place(element)) };
+ for (const [position, place, member] of VALUE_POSITIONS) {
+ for (const element of [...PARENTHESISED_ELEMENTS, ...HIDING_ELEMENTS, ...INITIALIZER_ELEMENTS]) yield { group: 'parenthesised element', name: `${element} / ${position}`, element, member, code: page(place(element)) };
+ // The lines that end in an open `[`, an `=` or an operator, where no member of a type begins: a regex cannot hold the closing tag there, since the text is no member's (the same lines where a member may begin are
+ // OPEN_LINE_PAGES, in the test of what cannot be read for certain).
+ if (!member) for (const element of PROSE_OPEN_ELEMENTS) yield { group: 'parenthesised element', name: `${element} / ${position}`, element, member, code: page(place(element)) };
+ }
for (const member of MEMBERS) {
yield { group: 'interface member', name: member, code: page({ top: `interface P1<T, U> { ${member} }` }) };
yield { group: 'type literal member', name: member, code: page({ top: `type P2<T, U> = { ${member} };` }) };
@@ -373,4 +416,10 @@ function* validPages() {
for (const form of PARAMETER_FORMS) yield { group: 'parameter form', name: form, code: page({ top: form }) };
}
-module.exports = { validPages, functionTypes, NAVIGATION_CALL, page, ARROWS, FUNCTION_VALUES, CASTS, OPERATORS, OPERANDS, MEMBERS, SIGNATURE_MEMBERS, HIDDEN_CLOSING_MEMBERS, PARENTHESISED_ELEMENTS, HIDING_ELEMENTS, INITIALIZER_ELEMENTS, TYPE_POSITIONS, VALUE_POSITIONS, EVERYDAY };
+// The lines that end in an open `[`, an `=` or an operator, at a head where a member of a type may begin (the pages of PROSE_OPEN_ELEMENTS that `validPages` leaves out): the text could be the members of a type that holds a regex, which the next line's
+// `/` begins, and the closing tag is inside it — both programs compile, and the lexer refuses after a guess.
+function* openLinePages() {
+ for (const [position, place, member] of VALUE_POSITIONS) if (member) for (const element of PROSE_OPEN_ELEMENTS) yield { group: 'open line', name: `${element} / ${position}`, element, code: page(place(element)) };
+}
+
+module.exports = { validPages, openLinePages, functionTypes, NAVIGATION_CALL, page, ARROWS, FUNCTION_VALUES, CASTS, OPERATORS, OPERANDS, MEMBERS, SIGNATURE_MEMBERS, HIDDEN_CLOSING_MEMBERS, PARENTHESISED_ELEMENTS, FAILING_LIST_ELEMENTS, EXACT_INITIALIZER_ELEMENTS, PROSE_ELEMENTS, SHAPED_PROSE_ELEMENTS, PROSE_OPEN_ELEMENTS, HIDING_ELEMENTS, INITIALIZER_ELEMENTS, TYPE_POSITIONS, VALUE_POSITIONS, EVERYDAY };
diff --git a/plugins/model-apps/scripts/tests/jsx-element-reading.test.js b/plugins/model-apps/scripts/tests/jsx-element-reading.test.js
index 3f2b3238c..e6d221668 100644
--- a/plugins/model-apps/scripts/tests/jsx-element-reading.test.js
+++ b/plugins/model-apps/scripts/tests/jsx-element-reading.test.js
@@ -84,7 +84,7 @@ test('fuzz (TypeScript parser): "<Name>(…)" that neither an arrow nor a colon
const stats = runSignatureFuzz({ ts, opens: opensTypeParameters, children: elementChildren, scale });
t.diagnostic(`parameter lists with neither an arrow nor a colon after them, each as a type and as an element: ${stats.programs} programs, ${stats.valid} valid to TypeScript`);
t.diagnostic(`as a type, ${stats.signature.valid} valid: code for certain ${stats.signature.code} (${(100 * stats.signature.code / stats.signature.valid).toFixed(1)}%), a guess ${stats.signature.guess}, an element ${stats.signature.element}`);
- t.diagnostic(`as an element, ${stats.element.valid} valid: an element for certain ${stats.element.element} (${(100 * stats.element.element / stats.element.valid).toFixed(1)}%), a guess ${stats.element.guess}, code ${stats.element.code}; elements with nothing the reading may be unable to read ${stats.precise.valid}, guessed ${stats.precise.guessed.length}`);
+ t.diagnostic(`as an element, ${stats.element.valid} valid: an element for certain ${stats.element.element} (${(100 * stats.element.element / stats.element.valid).toFixed(1)}%), a guess ${stats.element.guess}, code ${stats.element.code}; elements with nothing the reading may be unable to read ${stats.precise.valid} (${stats.precise.prose} of prose with comments and paths), guessed ${stats.precise.guessed.length}`);
t.diagnostic(`elements that TypeScript rejects, which the lexer reads as code: ${stats.failing}; unsound ${stats.unsound.length}, unsupported ${stats.unjustified.length}`);
assert.deepStrictEqual(stats.unsound.slice(0, 5).map((u) => ({ kind: u.kind, code: visible(u.code) })), [], 'a type that TypeScript parses read as an element, or an element that it parses read as code, for certain');
assert.deepStrictEqual(stats.unjustified.slice(0, 5).map((u) => ({ why: u.why, code: visible(u.code) })), [], 'an element read as failing that TypeScript does not reject, or not where the lexer says');
@@ -94,6 +94,8 @@ test('fuzz (TypeScript parser): "<Name>(…)" that neither an arrow nor a colon
assert.ok(stats.element.valid >= 8000 * scale && stats.element.element >= 6500 * scale && stats.element.guess >= 300 * scale, `${stats.element.valid} elements were valid, ${stats.element.element} read as elements and ${stats.element.guess} guessed`);
assert.ok(stats.failing >= 2000 * scale, `${stats.failing} elements that fail were read as code`);
assert.ok(stats.precise.valid >= 2800 * scale, `${stats.precise.valid} elements with nothing to hide were valid`);
+ // ... among them the prose with a comment in it and a path on a later line, which only an element compiles with and which must stay certain (the lines that the reading of a type's members reads).
+ assert.ok(stats.precise.prose >= 500 * scale, `${stats.precise.prose} elements of prose with comments and paths were valid`);
// The rule keeps what it can decide: nearly every valid type that does not hold a closing tag in a string, a template or a comment is code for certain.
assert.ok(stats.signature.code >= 0.8 * stats.signature.valid, `${stats.signature.code} of ${stats.signature.valid} valid types were read as code`);
});
diff --git a/plugins/model-apps/scripts/tests/lcid-cultures.test.js b/plugins/model-apps/scripts/tests/lcid-cultures.test.js
new file mode 100644
index 000000000..20ae37919
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/lcid-cultures.test.js
@@ -0,0 +1,161 @@
+'use strict';
+// The LCID -> culture mapping the languages script reports with (lib/lcid-cultures.js).
+//
+// The SDK answers LCIDs only; the planner needs a culture code and a text direction for each, and a page keys its
+// translations and its `dir` on them. So the table must be exact where it answers, and silent where it does not: an
+// unknown LCID stays numeric and is reported, never mapped to a neighbour's code or given a guessed direction.
+const test = require('node:test');
+const assert = require('node:assert');
+const {
+ CODES, RTL_LCIDS, cultureForLcid, languageName, describeLanguage, languageLine, describeEnvironmentLanguages,
+} = require('../lib/lcid-cultures.js');
+
+// The languages Dataverse provisions, by LCID, as [MS-LCID] names them.
+// See: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-lcid/70feba9f-294e-491e-b6eb-56532684c37f
+const KNOWN = {
+ 1025: 'ar-SA', 1026: 'bg-BG', 1027: 'ca-ES', 1028: 'zh-TW', 1029: 'cs-CZ', 1030: 'da-DK', 1031: 'de-DE', 1032: 'el-GR',
+ 1033: 'en-US', 1035: 'fi-FI', 1036: 'fr-FR', 1037: 'he-IL', 1038: 'hu-HU', 1040: 'it-IT', 1041: 'ja-JP', 1042: 'ko-KR',
+ 1043: 'nl-NL', 1044: 'nb-NO', 1045: 'pl-PL', 1046: 'pt-BR', 1048: 'ro-RO', 1049: 'ru-RU', 1050: 'hr-HR', 1051: 'sk-SK',
+ 1053: 'sv-SE', 1054: 'th-TH', 1055: 'tr-TR', 1057: 'id-ID', 1058: 'uk-UA', 1060: 'sl-SI', 1061: 'et-EE', 1062: 'lv-LV',
+ 1063: 'lt-LT', 1066: 'vi-VN', 1069: 'eu-ES', 1081: 'hi-IN', 1086: 'ms-MY', 1087: 'kk-KZ', 1110: 'gl-ES', 2052: 'zh-CN',
+ 2070: 'pt-PT', 2074: 'sr-Latn-CS', 3076: 'zh-HK', 3082: 'es-ES', 3098: 'sr-Cyrl-CS',
+};
+
+// Every SPECIFIC right-to-left culture in Windows culture metadata (CultureInfo.GetCultures filtered on
+// TextInfo.IsRightToLeft) — the list localization-reference.test.js pins the page-side fallback against.
+const RTL_CODES = [
+ 'ar-SA', 'ar-IQ', 'ar-EG', 'ar-LY', 'ar-DZ', 'ar-MA', 'ar-TN', 'ar-OM', 'ar-YE', 'ar-SY', 'ar-JO',
+ 'ar-LB', 'ar-KW', 'ar-AE', 'ar-BH', 'ar-QA', 'he-IL', 'yi-001', 'fa-IR', 'fa-AF', 'ur-PK', 'ur-IN',
+ 'ps-AF', 'sd-Arab-PK', 'ug-CN', 'dv-MV', 'syr-SY', 'ku-Arab-IQ', 'pa-Arab-PK', 'tzm-Arab-MA',
+];
+
+test('the table is sorted by LCID, holds each LCID once, and every LCID is a positive 16-bit integer', () => {
+ const lcids = CODES.map(([lcid]) => lcid);
+ assert.ok(lcids.length > 200, `${lcids.length} cultures`);
+ assert.deepStrictEqual(lcids, [...lcids].sort((a, b) => a - b), 'sorted');
+ assert.strictEqual(new Set(lcids).size, lcids.length, 'no LCID twice');
+ for (const lcid of lcids) assert.ok(Number.isInteger(lcid) && lcid > 0 && lcid <= 0xffff, `${lcid}`);
+});
+
+test('every code is a well-formed language tag Intl accepts', () => {
+ for (const [lcid, code] of CODES) {
+ assert.match(code, /^[a-z]{2,3}(?:-[A-Z][a-z]{3})?(?:-(?:[A-Z]{2}|\d{3}))?(?:-valencia)?$/, `${lcid} ${code}`);
+ assert.doesNotThrow(() => new Intl.Locale(code), `${lcid} ${code}`);
+ }
+});
+
+test('it names the languages Dataverse provisions, by the code .NET gives them', () => {
+ for (const [lcid, code] of Object.entries(KNOWN)) {
+ assert.deepStrictEqual(cultureForLcid(Number(lcid)), { lcid: Number(lcid), code, rtl: code === 'ar-SA' || code === 'he-IL' }, `${lcid}`);
+ }
+});
+
+test('direction: exactly the right-to-left cultures Windows marks, and no other', () => {
+ const rtl = CODES.filter(([lcid]) => cultureForLcid(lcid).rtl).map(([, code]) => code);
+ assert.deepStrictEqual([...rtl].sort(), [...RTL_CODES].sort());
+ assert.strictEqual(RTL_LCIDS.size, RTL_CODES.length);
+ // Every Arabic region, not the five or six a hand-kept list names.
+ assert.strictEqual(CODES.filter(([, code]) => code.startsWith('ar-')).length, 16);
+ for (const [lcid, code] of CODES) if (code.startsWith('ar-')) assert.strictEqual(cultureForLcid(lcid).rtl, true, code);
+ // Left-to-right controls, including scripts that are easy to mistake for right-to-left.
+ for (const code of ['en-US', 'fr-FR', 'de-DE', 'es-ES', 'ru-RU', 'el-GR', 'tr-TR', 'az-Latn-AZ', 'hi-IN', 'pa-IN', 'th-TH', 'zh-CN', 'zh-TW', 'ja-JP', 'ko-KR', 'vi-VN', 'sd-Deva-IN', 'ks-Deva-IN', 'mn-Mong-CN']) {
+ const row = CODES.find(([, c]) => c === code);
+ assert.ok(row, `${code} is in the table`);
+ assert.strictEqual(cultureForLcid(row[0]).rtl, false, code);
+ }
+});
+
+// Where the host's Intl has its script data, the table's direction must be what CLDR derives from the code — the
+// computation localization.md gives page authors as a fallback. A Node without full ICU answers no script for Arabic,
+// which is exactly why the table, and not this computation, is what the script reports.
+const RTL_SCRIPTS = new Set(['Arab', 'Hebr', 'Syrc', 'Thaa', 'Nkoo', 'Adlm', 'Rohg', 'Mand', 'Samr']);
+const hasScriptData = (() => {
+ try { return new Intl.Locale('ar-SA').maximize().script === 'Arab'; } catch { return false; }
+})();
+
+test('direction agrees with the script CLDR derives from each code', { skip: !hasScriptData && 'this Node has no ICU script data' }, () => {
+ for (const [lcid, code] of CODES) {
+ const script = new Intl.Locale(code).maximize().script || '';
+ assert.strictEqual(cultureForLcid(lcid).rtl, RTL_SCRIPTS.has(script), `${lcid} ${code} (${script})`);
+ }
+});
+
+test('an LCID the table does not name stays numeric: null, never a neighbour\u2019s code or a guessed direction', () => {
+ const unknown = [
+ 0, -1, 1.5, NaN, Infinity, '1033', '', null, undefined, {}, [1033], true,
+ 4096, // a custom locale
+ 127, // the invariant culture
+ 4, 7, 9, 31748, // neutral cultures (zh-CHS, de, en, zh-CHT)
+ 1084, 99999, 65535,
+ 0x10409, // en-US with a sort id — a different id, not a variant to read as en-US
+ 1033 + 0x400 * 60, // a sublanguage no culture holds, under a primary language that has others
+ ];
+ for (const lcid of unknown) assert.strictEqual(cultureForLcid(lcid), null, `${String(lcid)}`);
+ assert.deepStrictEqual(describeLanguage(4096), { lcid: 4096, code: null, name: null, rtl: null });
+});
+
+test('languageName gives the English name Intl has, and null where it has none', { skip: typeof Intl.DisplayNames !== 'function' && 'this Node has no Intl.DisplayNames' }, () => {
+ assert.strictEqual(languageName('ar-SA'), 'Arabic (Saudi Arabia)');
+ assert.strictEqual(languageName('en-US'), 'English (United States)');
+ assert.strictEqual(languageName('pt-BR'), 'Portuguese (Brazil)');
+ assert.strictEqual(languageName('xx-XX'), null, 'no name is null, not the code echoed back');
+ assert.strictEqual(languageName(1033), null);
+ assert.strictEqual(languageName(undefined), null);
+});
+
+test('languageName never throws and never invents a name when the host cannot name languages', () => {
+ assert.strictEqual(languageName('ar-SA', null), null, 'no DisplayNames at all');
+ assert.strictEqual(languageName('ar-SA', { of: () => { throw new RangeError('bad tag'); } }), null);
+ assert.strictEqual(languageName('ar-SA', { of: () => '' }), null);
+ assert.strictEqual(languageName('ar-SA', { of: () => undefined }), null);
+ // The code and the direction do not depend on a name.
+ assert.deepStrictEqual(describeLanguage(1025, null), { lcid: 1025, code: 'ar-SA', name: null, rtl: true });
+});
+
+test('languageLine is the planner\u2019s `<LCID> <Code> \u2014 RTL: Yes|No`, and says unknown for an unmapped LCID', () => {
+ assert.strictEqual(languageLine(describeLanguage(1025, null)), '1025 ar-SA \u2014 RTL: Yes');
+ assert.strictEqual(languageLine(describeLanguage(1033, null)), '1033 en-US \u2014 RTL: No');
+ assert.strictEqual(languageLine(describeLanguage(4096, null)), '4096 unknown \u2014 RTL: unknown');
+});
+
+test('describeEnvironmentLanguages: the base, every provisioned language in order, the unmapped LCIDs, and a line each', () => {
+ const out = describeEnvironmentLanguages({ baseLanguage: 1033, provisioned: [1033, 1025, 4096, 1036] }, null);
+ assert.deepStrictEqual(out.baseLanguage, { lcid: 1033, code: 'en-US', name: null, rtl: false });
+ assert.deepStrictEqual(out.languages.map((l) => l.lcid), [1033, 1025, 4096, 1036], 'server order is kept');
+ assert.deepStrictEqual(out.languages.map((l) => l.code), ['en-US', 'ar-SA', null, 'fr-FR']);
+ assert.deepStrictEqual(out.languages.map((l) => l.rtl), [false, true, null, false]);
+ assert.deepStrictEqual(out.unmapped, [4096]);
+ assert.deepStrictEqual(out.summary, ['1033 en-US \u2014 RTL: No', '1025 ar-SA \u2014 RTL: Yes', '4096 unknown \u2014 RTL: unknown', '1036 fr-FR \u2014 RTL: No']);
+});
+
+test('describeEnvironmentLanguages describes the base on its own: the SDK checks no relation between its reads', () => {
+ // A base language that is not among the provisioned ones (unproven beyond the organizations measured) is reported
+ // as the base, and is neither dropped nor added to the provisioned list.
+ const out = describeEnvironmentLanguages({ baseLanguage: 3082, provisioned: [1033] }, null);
+ assert.strictEqual(out.baseLanguage.code, 'es-ES');
+ assert.deepStrictEqual(out.languages.map((l) => l.lcid), [1033]);
+ // An unmapped base is reported once, even when it is also provisioned.
+ const unmappedBase = describeEnvironmentLanguages({ baseLanguage: 4096, provisioned: [4096, 4096, 1033] }, null);
+ assert.deepStrictEqual(unmappedBase.unmapped, [4096]);
+});
+
+test('describeEnvironmentLanguages reports an unknown BASE language in `unmapped` although it is not provisioned', () => {
+ // `unmapped` is what the planner tells the user about: a base language the table cannot name is as unknown as a
+ // provisioned one, and a provisioned list that names it not is no reason to leave it out.
+ const baseOnly = describeEnvironmentLanguages({ baseLanguage: 4096, provisioned: [1033] }, null);
+ assert.deepStrictEqual(baseOnly.baseLanguage, { lcid: 4096, code: null, name: null, rtl: null });
+ assert.deepStrictEqual(baseOnly.unmapped, [4096]);
+ assert.deepStrictEqual(baseOnly.languages.map((l) => l.lcid), [1033], 'it is not added to the provisioned languages');
+ assert.deepStrictEqual(baseOnly.summary, ['1033 en-US \u2014 RTL: No'], 'and gets no summary line: the lines are the provisioned languages\u2019');
+ // The base first, then the provisioned ones in the server's order, each LCID once.
+ const both = describeEnvironmentLanguages({ baseLanguage: 4096, provisioned: [1033, 5000, 4096, 5000] }, null);
+ assert.deepStrictEqual(both.unmapped, [4096, 5000]);
+ // A base the table names adds nothing.
+ assert.deepStrictEqual(describeEnvironmentLanguages({ baseLanguage: 1033, provisioned: [1033] }, null).unmapped, []);
+});
+
+test('describeEnvironmentLanguages refuses an answer that is not the SDK\u2019s shape', () => {
+ for (const bad of [null, undefined, {}, { baseLanguage: '1033', provisioned: [1033] }, { baseLanguage: 1033, provisioned: 1033 }, { baseLanguage: 1033 }]) {
+ assert.throws(() => describeEnvironmentLanguages(bad), TypeError, JSON.stringify(bad));
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/list-connections.test.js b/plugins/model-apps/scripts/tests/list-connections.test.js
index 29bdf46e1..1cd4f1be8 100644
--- a/plugins/model-apps/scripts/tests/list-connections.test.js
+++ b/plugins/model-apps/scripts/tests/list-connections.test.js
@@ -95,6 +95,12 @@ const {
const SP_CONN = '/providers/Microsoft.PowerApps/apis/shared_sharepointonline/connections/abc';
+// Sentences that read like an empty-state message and are NOT taken for one. `pac connection list` says an environment has no connections by printing the grid's header with
+// no rows under it (pacGrid below), never a sentence. The first is PAC's own `ConnectionNotFound` resource string, which the command does not print (PAC CLI 2.12.2: nothing
+// refers to it); the second is the wording an earlier version of this script guessed, which is in none of PAC's resources. A parser that took either for emptiness would give a
+// failure a way to read as "no connections", for the sake of text PAC does not print.
+const NO_CONNECTIONS_SENTENCES = ['No connections were found in the passed environment.', 'No connections found.'];
+
test('parses the fixed-width table PAC emits by default', () => {
// Connection Name Connector Id Connection Id
// --------------------- ------------------------------- ------------------
@@ -179,11 +185,31 @@ const REAL_CONNECTIONS = [
{ connectorId: '/providers/Microsoft.PowerApps/apis/shared_sharepointonline', connectionId: '00000000000000000000000000000002', displayName: 'SharePoint' },
];
+// `pac connection list` sizes every column of its grid to its widest cell — the header name included — plus one space (PAC CLI 2.12.2; the capture above is that rule applied
+// to a "Weather" and a "SharePoint" row), so the gap between two header names is wide only while some cell is longer than the name. This renders a grid by that rule for ANY rows, so a
+// test cannot drift from what PAC prints. The last column is not padded (the capture's lines end at their last character); `padLast` pads it, in case a build does.
+// no rows Id Name API Id Status
+// one connection "mail" Id Name API Id Status
+// 00000000000000000000000000000001 mail /providers/Microsoft.PowerApps/apis/shared_office365 Connected
+const PAC_GRID_HEADER = ['Id', 'Name', 'API Id', 'Status'];
+function pacGrid(rows, { banner = true, eol = '\r\n', padLast = false } = {}) {
+ const widths = PAC_GRID_HEADER.map((name, i) => Math.max(name.length, ...rows.map((row) => row[i].length)) + 1);
+ const line = (cells) => cells.map((cell, i) => (i === cells.length - 1 && !padLast ? cell : cell.padEnd(widths[i]))).join('');
+ return `${[...(banner ? [REAL_BANNER] : []), line(PAC_GRID_HEADER), ...rows.map(line)].join(eol)}${eol}${eol}`;
+}
+const GRID_ID = (n) => String(n).padStart(32, '0');
+const gridRow = (n, name, connector, status = 'Connected') => [GRID_ID(n), name, `/providers/Microsoft.PowerApps/apis/shared_${connector}`, status];
+const gridConnection = (n, name, connector) => ({ connectorId: `/providers/Microsoft.PowerApps/apis/shared_${connector}`, connectionId: GRID_ID(n), displayName: name });
+// The empty environment's listing, as PAC prints it.
+const EMPTY_GRID = pacGrid([]);
+
test('parses the exact layout of a real `pac connection list` capture, banner and CRLF included', () => {
assert.deepEqual(REAL_LISTING.split('\r\n').map((line) => line.length), [23, 110, 113, 113, 0, 0], 'the same line lengths as the capture');
assert.deepEqual(parsePacConnectionList(REAL_LISTING), REAL_CONNECTIONS);
assert.deepEqual(parsePacConnectionList(REAL_LISTING.replace(/\r\n/g, '\n')), REAL_CONNECTIONS, 'the same output with LF endings');
- assert.deepEqual(parsePacConnectionList(realListing()), [], 'the real header with no rows is an empty listing');
+ assert.deepEqual(parsePacConnectionList(realListing()), [], 'the capture\'s header with no rows below it is an empty listing');
+ // pacGrid applies the rule that made the capture: with the capture's two rows it reproduces it, character for character.
+ assert.strictEqual(pacGrid([gridRow(1, 'Weather', 'msnweather'), gridRow(2, 'SharePoint', 'sharepointonline')]), REAL_LISTING, 'the renderer is PAC\'s grid');
for (const [what, raw] of Object.entries(UNREADABLE_REAL_LISTINGS)) {
assert.throws(() => parsePacConnectionList(raw), /unrecognized connection listing/, what);
}
@@ -197,8 +223,10 @@ test('an Id/Name/API Id listing with a line that is not a connection row fails c
// Connection rows read wrong: each carries a connector's API path but not the columns around it.
assert.throws(() => parsePacConnectionList([header, '/providers/Microsoft.PowerApps/apis/shared_sharepointonline', 'Contoso /providers/Microsoft.PowerApps/apis/shared_office365'].join('\n')),
/unrecognized connection listing[\s\S]*Id\/Name\/API Id[\s\S]*"\/providers\/Microsoft\.PowerApps\/apis\/shared_sharepointonline"/);
- // PAC's own empty-state message under the header is still an empty listing.
- assert.deepEqual(parsePacConnectionList([header, 'No connections found.'].join('\n')), []);
+ // A sentence under the header — even PAC's own `ConnectionNotFound` resource string — is not a row: the listing is refused, not read as empty.
+ for (const sentence of NO_CONNECTIONS_SENTENCES) {
+ assert.throws(() => parsePacConnectionList([header, sentence].join('\n')), /unrecognized connection listing[\s\S]*not a connection row/, sentence);
+ }
// A Status of several words, or none, still parses.
const status = (s) => `00000000000000000000000000000001 Contoso Dataverse /providers/Microsoft.PowerApps/apis/shared_commondataservice${s}`;
for (const s of [' Not connected', '']) {
@@ -266,14 +294,145 @@ test('unreadable output is refused, never read as "no connections"', () => {
assert.equal(parseJsonConnections('"a string"'), null);
});
-test('an empty listing is one PAC itself reports as empty', () => {
- for (const raw of ['[]', '{"value":[]}', 'No connections found.', 'Connected as [email protected]\r\nNo connections found.\r\n',
+test('an empty listing is what PAC prints for an empty environment: a header with no rows, or an empty JSON list', () => {
+ for (const raw of ['[]', '{"value":[]}', EMPTY_GRID,
'Connected as [email protected]\r\nId Name API Id Status\r\n',
'Connection Name Connector Id Connection Id\n--------------- ------------ -------------\n']) {
assert.deepEqual(parsePacConnectionList(raw), [], JSON.stringify(raw));
}
});
+// `pac connection list` on an environment with NO connections prints PAC's banner and the grid's header, and nothing else — no message (PAC CLI 2.12.2). Its columns are sized to
+// the widest cell plus one space, so with no row to widen them the header is `Id Name API Id Status`, single-spaced; a header read by two-space gaps between its names refused
+// it, and an empty environment was reported as unreadable. The header is read by its words. These are the grids PAC renders (pacGrid), not hand-made approximations of them.
+test('pac\'s grid with NO rows — the header alone, single-spaced — is an empty listing, with the banner or without it, whatever the line endings and padding', async () => {
+ assert.strictEqual(EMPTY_GRID, `${REAL_BANNER}\r\nId Name API Id Status\r\n\r\n`, 'the premise: the exact text PAC prints, one space between the names');
+ for (const [what, raw] of [
+ ['with the banner, in CRLF', EMPTY_GRID],
+ ['in LF', pacGrid([], { eol: '\n' })],
+ ['in a bare CR', pacGrid([], { eol: '\r' })],
+ ['with no banner', pacGrid([], { banner: false })],
+ ['with the last column padded', pacGrid([], { padLast: true })],
+ ['with a trailing space', `${REAL_BANNER}\r\nId Name API Id Status \r\n\r\n`],
+ ['with a tab between the names', `${REAL_BANNER}\r\nId\tName\tAPI Id\tStatus\r\n`],
+ ['in the other cases', `${REAL_BANNER}\r\nid name api id status\r\n`],
+ ['with no trailing line break', `${REAL_BANNER}\r\nId Name API Id Status`],
+ ['with the wider gaps older fixtures use', `${REAL_BANNER}\r\nId Name API Id Status\r\n`],
+ ]) {
+ assert.deepEqual(parsePacConnectionList(raw), [], what);
+ const run = await driveDiscovery({ pac: { status: 0, stdout: raw, stderr: '' }, refs: { status: 200, data: { value: [] } } });
+ assert.deepEqual(run.emitted, [{ ok: true, payload: { ok: true, connections: [], connectionReferences: [] } }], `${what}: an empty environment is a successful, empty discovery`);
+ assert.strictEqual(run.queries.length, 1, `${what}: the connection-reference read follows a readable listing`);
+ }
+});
+
+test('pac\'s grid with ONE connection, whose name is short enough that the header pads to a single space, is read', async () => {
+ // A name of four characters or fewer leaves "Name" the widest cell of its column, so the header is `Name API Id` and the row `<id> mail /providers/…`.
+ for (const name of ['a', 'ab', 'abc', 'mail', 'Sales']) {
+ const grid = pacGrid([gridRow(7, name, 'office365')]);
+ const header = grid.split('\r\n')[1];
+ if (name.length <= 4) assert.match(header, /Name API Id/, `the premise for ${JSON.stringify(name)}: one space between the names`);
+ else assert.match(header, /Name {2,}API Id/, `the premise for ${JSON.stringify(name)}: the longer name widens the column`);
+ assert.deepEqual(parsePacConnectionList(grid), [gridConnection(7, name, 'office365')], name);
+ assert.deepEqual(parsePacConnectionList(pacGrid([gridRow(7, name, 'office365')], { padLast: true, eol: '\n' })), [gridConnection(7, name, 'office365')], `${name}: padded last column, LF`);
+ const run = await driveDiscovery({ pac: { status: 0, stdout: grid, stderr: '' }, refs: { status: 200, data: { value: [] } } });
+ assert.strictEqual(run.emitted[0].ok, true, `${name}: ${run.emitted[0].ok ? '' : run.emitted[0].payload.message}`);
+ assert.deepEqual(run.emitted[0].payload.connections.map((c) => [c.connectionId, c.displayName]), [[GRID_ID(7), name]], name);
+ }
+ // A name with spaces in it, still short: the API path is the delimiter, not the gaps.
+ assert.deepEqual(parsePacConnectionList(pacGrid([gridRow(8, 'a b', 'sql', 'Error')])), [gridConnection(8, 'a b', 'sql')]);
+});
+
+test('pac\'s grid with several connections of mixed name lengths is read, rows in the order PAC printed them', () => {
+ const rows = [gridRow(1, 'Weather', 'msnweather'), gridRow(2, 'ab', 'sql', 'Error'), gridRow(3, 'SharePoint', 'sharepointonline'), gridRow(4, 'Contoso Dataverse (maker)', 'commondataserviceforapps', 'Not connected')];
+ const expected = [gridConnection(1, 'Weather', 'msnweather'), gridConnection(2, 'ab', 'sql'), gridConnection(3, 'SharePoint', 'sharepointonline'), gridConnection(4, 'Contoso Dataverse (maker)', 'commondataserviceforapps')];
+ for (const options of [{}, { eol: '\n' }, { banner: false }, { padLast: true }]) {
+ assert.deepEqual(parsePacConnectionList(pacGrid(rows, options)), expected, JSON.stringify(options));
+ }
+ // The names alone decide how wide the Name column is: all short, then one long.
+ assert.deepEqual(parsePacConnectionList(pacGrid(rows.slice(1, 2))), expected.slice(1, 2));
+ assert.match(pacGrid(rows).split('\r\n')[1], /Name {2,}API Id/);
+});
+
+// An empty listing is the ONE answer that sends connection setup on to create a connection, so what makes a header "the header" is exactly its words and nothing else on the line.
+test('only the grid\'s four header names, in order, on a line of their own are the header; nothing else is read as an empty listing', () => {
+ const header = 'Id Name API Id Status';
+ for (const line of ['Id Name API Id', 'Id Name API Id Status Extra', 'Id Name Status API Id', 'Id API Id Name Status', 'Name Id API Id Status', 'Id Name API Status', 'Id Name APIId Status',
+ 'Id Name API Id Status could not be read', 'Warning: Id Name API Id Status', 'Id: Name API Id Status', 'Id, Name, API Id, Status', 'Connection Id Connector Id Status',
+ 'Id Name API Id Status.', '- Id Name API Id Status']) {
+ for (const raw of [`${REAL_BANNER}\r\n${line}\r\n`, `${line}\r\n`]) {
+ assert.throws(() => parsePacConnectionList(raw), /could not read[\s\S]*not reported as "no connections"/, JSON.stringify(raw));
+ }
+ }
+ assert.deepEqual(parsePacConnectionList(`${REAL_BANNER}\r\n${header}\r\n`), []);
+});
+
+// A listing is only as good as what is under its header. A header with nothing under it is empty; a header with a warning under it, or before it, is a failure to read.
+test('pac\'s grid with a warning line before or after the header — or between rows — is refused, never read as empty or as the rows that parsed', async () => {
+ const warning = 'Warning: failed to retrieve connections.';
+ const rows = [gridRow(1, 'mail', 'office365'), gridRow(2, 'Weather', 'msnweather')];
+ const cases = {
+ 'a warning after the header of an empty environment': `${[REAL_BANNER, 'Id Name API Id Status', warning].join('\r\n')}\r\n\r\n`,
+ 'the same, as one line cut off': `${[REAL_BANNER, 'Id Name API Id Status', 'Warning: failed to retr'].join('\r\n')}\r\n`,
+ 'a warning before the header of an empty environment': `${[REAL_BANNER, warning, 'Id Name API Id Status'].join('\r\n')}\r\n\r\n`,
+ 'a warning after the rows': `${pacGrid(rows).trimEnd()}\r\n${warning}\r\n`,
+ 'a warning between the rows': `${[REAL_BANNER, pacGrid(rows, { banner: false }).split('\r\n')[0], pacGrid(rows, { banner: false }).split('\r\n')[1], warning, pacGrid(rows, { banner: false }).split('\r\n')[2]].join('\r\n')}\r\n`,
+ 'a warning before the rows': `${[REAL_BANNER, pacGrid(rows, { banner: false }).split('\r\n')[0], warning, pacGrid(rows, { banner: false }).split('\r\n')[1]].join('\r\n')}\r\n`,
+ 'a sentence PAC does not print': `${[REAL_BANNER, 'Id Name API Id Status', NO_CONNECTIONS_SENTENCES[0]].join('\r\n')}\r\n`,
+ 'a diagnostic that names an API path': `${[REAL_BANNER, 'Id Name API Id Status', 'Warning: could not read /providers/Microsoft.PowerApps/apis/shared_msnweather connections'].join('\r\n')}\r\n`,
+ };
+ for (const [what, raw] of Object.entries(cases)) {
+ assert.throws(() => parsePacConnectionList(raw), /could not read[\s\S]*not reported as "no connections"/, what);
+ const run = await driveDiscovery({ pac: { status: 0, stdout: raw, stderr: '' }, refs: { status: 200, data: { value: [] } } });
+ assert.deepEqual(run.queries, [], `${what}: no connection-reference query`);
+ assert.strictEqual(run.emitted.length, 1, what);
+ assert.strictEqual(run.emitted[0].ok, false, what);
+ }
+});
+
+test('pac\'s empty grid is refused when PAC exited non-zero or wrote to stderr: a failed listing can print a header', async () => {
+ // A non-zero exit keeps its own report and never reaches the parser, so the header cannot make it an empty environment.
+ const failed = await driveDiscovery({ pac: { status: 1, stdout: EMPTY_GRID, stderr: 'Error: the request failed' } });
+ assert.deepEqual(failed.queries, []);
+ assert.strictEqual(failed.emitted[0].ok, false);
+ assert.strictEqual(failed.emitted[0].payload.message, 'pac connection list failed (exit 1): Error: the request failed');
+ const failedQuietly = await driveDiscovery({ pac: { status: 3, stdout: EMPTY_GRID, stderr: '' } });
+ assert.deepEqual(failedQuietly.queries, []);
+ assert.strictEqual(failedQuietly.emitted[0].ok, false, 'a non-zero exit with the header on stdout is not an empty environment');
+ // Text on stderr after a zero exit means the stdout cannot be trusted, whatever it holds.
+ for (const stderr of ['Warning: failed to retrieve connections.\n', '\r\n Warning: indented\r\n', 'x']) {
+ const run = await driveDiscovery({ pac: { status: 0, stdout: EMPTY_GRID, stderr }, refs: { status: 200, data: { value: [] } } });
+ assert.deepEqual(run.queries, [], JSON.stringify(stderr));
+ assert.strictEqual(run.emitted[0].ok, false, JSON.stringify(stderr));
+ assert.match(run.emitted[0].payload.message, /exited 0 but wrote to stderr[\s\S]*not reported as "no connections"/, JSON.stringify(stderr));
+ }
+ // The control: a quiet stderr is the clean exit PAC really gives, and the empty grid is then an empty discovery.
+ for (const stderr of ['', '\r\n', undefined, null]) {
+ const run = await driveDiscovery({ pac: { status: 0, stdout: EMPTY_GRID, stderr }, refs: { status: 200, data: { value: [] } } });
+ assert.deepEqual(run.emitted, [{ ok: true, payload: { ok: true, connections: [], connectionReferences: [] } }], JSON.stringify(stderr));
+ }
+});
+
+// PAC's resources hold a sentence for "no connections" (`ConnectionNotFound`) and a header ("Connection ID,Connector ID,Created By", `ConnectionListHeader`), but `pac connection list`
+// prints neither (PAC CLI 2.12.2). They are not accepted either: a parser that took them would be taking text PAC does not print, and a sentence taken for emptiness is how a failure
+// reads as "no connections". A build that does print one is refused as unreadable, which costs a re-run of `pac connection list`; the answer it would otherwise give is a duplicate connection.
+test('sentences and headers from PAC\'s resources that `pac connection list` does not print are refused, alone and with the banner', async () => {
+ const unprinted = [
+ ...NO_CONNECTIONS_SENTENCES, ...NO_CONNECTIONS_SENTENCES.map((s) => s.toLowerCase()), ...NO_CONNECTIONS_SENTENCES.map((s) => s.slice(0, -1)),
+ 'Connection ID Connector ID Created By', 'Connection ID Connector ID Created By', 'connection id,connector id,created by',
+ `Connection ID Connector ID Created By\r\n${GRID_ID(1)} /providers/Microsoft.PowerApps/apis/shared_sql [email protected]`,
+ `Connection ID Connector ID Created By\r\n${GRID_ID(1)} /providers/Microsoft.PowerApps/apis/shared_sql [email protected]`,
+ ];
+ for (const text of unprinted) {
+ for (const raw of [text, `${REAL_BANNER}\r\n${text}\r\n`, `${text}\r\n`]) {
+ assert.throws(() => parsePacConnectionList(raw), /could not read[\s\S]*not reported as "no connections"/, JSON.stringify(raw));
+ const run = await driveDiscovery({ pac: { status: 0, stdout: raw, stderr: '' }, refs: { status: 200, data: { value: [] } } });
+ assert.deepEqual(run.queries, [], `${JSON.stringify(raw)}: no connection-reference query`);
+ assert.strictEqual(run.emitted[0].ok, false, JSON.stringify(raw));
+ }
+ }
+});
+
// An identifier is a non-empty string. Whitespace, a number, an object or an array in an id column made a
// row with "both ids" that nothing could ever bind — offered to the maker as a real connection.
test('identifiers must be non-empty strings, trimmed', () => {
@@ -368,7 +527,7 @@ test('a line other than the banner before a recognised table header is refused,
'Id/Name/API Id, after the banner': ['Connected as [email protected]', warning, idNameApi, goodRow],
'Id/Name/API Id, between two banners': ['Connected as [email protected]', warning, 'Connected as [email protected]', idNameApi, goodRow],
'Id/Name/API Id, text that only resembles the banner': ['Connected to [email protected]', idNameApi, goodRow],
- 'Id/Name/API Id, the empty-state message is not preamble': ['No connections found.', idNameApi],
+ 'Id/Name/API Id, a sentence before the header is not preamble': [NO_CONNECTIONS_SENTENCES[0], idNameApi],
'fixed-width, header only': [warning, ...fixedHeader],
'fixed-width, with a row': [warning, ...fixedHeader, fixedRow],
'fixed-width, after the banner': ['Connected as [email protected]', warning, ...fixedHeader, fixedRow],
@@ -448,21 +607,29 @@ test('tables of real rows, a trailing blank line and a separator-only line still
assert.deepEqual(parsePacConnectionList(loose), [{ connectorId: 'shared_msnweather', connectionId: 'shared-msnweather-00000000-0000-4000-8000-000000000001', displayName: 'Weather' }]);
});
-// Emptiness is PAC's own statement that there is nothing to list — or a header with no rows. A broad pattern
-// ("no connections ... found") accepted "No connections could be found because the request failed.", the
-// answer that sends connection setup on to create a duplicate of a connection the maker already has.
-test('only the exact PAC empty-state message, or a header with no rows, reads as an empty listing', () => {
+// Emptiness is a header with no rows (or an empty JSON list) and nothing else: no sentence is taken for it. A broad pattern ("no connections ... found") accepted "No connections could be
+// found because the request failed.", the answer that sends connection setup on to create a duplicate of a connection the maker already has — and a sentence PAC does not print
+// gains nothing by being accepted (see NO_CONNECTIONS_SENTENCES).
+test('only a header with no rows, or an empty JSON list, reads as an empty listing: no sentence does', () => {
const idNameApi = 'Id Name API Id Status';
- for (const raw of ['No connections found.', 'no connections found', 'No connections found.\r\n', '\r\n No connections found. \r\n',
- 'Connected as [email protected]\nNo connections found.', 'Connected as [email protected]\nConnected as [email protected]\n\nNo connections found.',
- idNameApi, `${idNameApi}\nNo connections found.`, `${idNameApi}\n\n`, '[]', '{"value":[]}']) {
+ for (const raw of [idNameApi, `${idNameApi}\n\n`, 'Id Name API Id Status', EMPTY_GRID, '[]', '{"value":[]}']) {
assert.deepEqual(parsePacConnectionList(raw), [], JSON.stringify(raw));
}
- for (const raw of ['No connections could be found because the request failed.', 'No connections found because the request failed.',
- 'No connections were found.', 'No connection found.', 'No connections found. Try again later.', 'No connections found.\nWarning: partial failure',
- 'Warning: partial failure\nNo connections found.', 'No connections found.\nNo connections found. Retrying...',
- // The message beside a row contradicts it: neither is trusted.
- `${idNameApi}\n00000000000000000000000000000001 Contoso Dataverse /providers/Microsoft.PowerApps/apis/shared_commondataservice Connected\nNo connections found.`]) {
+ const [pacSentence, guessedSentence] = NO_CONNECTIONS_SENTENCES;
+ for (const raw of [
+ // A failure worded like the empty-state message is a failure, not an empty environment.
+ 'No connections could be found because the request failed.', 'No connections found because the request failed.',
+ 'No connections were found in the passed environment because the request failed.', `${pacSentence} Try again later.`,
+ 'No connections were found in the environment.', 'No connections were found.', 'No connection was found in the passed environment.',
+ `${pacSentence}\nWarning: partial failure`, `Warning: partial failure\n${pacSentence}`, `${pacSentence}\n${pacSentence} Retrying...`,
+ // PAC's own resource string, which this command does not print, and the wording an earlier version guessed, which is in none of PAC's resources: neither is read as emptiness — alone,
+ // in any case, with or without its period or the banner, or under or over a header.
+ ...NO_CONNECTIONS_SENTENCES, ...NO_CONNECTIONS_SENTENCES.map((s) => s.toUpperCase()), ...NO_CONNECTIONS_SENTENCES.map((s) => `\r\n ${s} \r\n`),
+ pacSentence.slice(0, -1), 'no connections found', `${guessedSentence}\r\n`,
+ `Connected as [email protected]\n${pacSentence}`, `Connected as [email protected]\nConnected as [email protected]\n\n${pacSentence}`,
+ `Connected as [email protected]\n${guessedSentence}`, `${idNameApi}\n${pacSentence}`, `${idNameApi}\n${guessedSentence}`, `${EMPTY_GRID}${pacSentence}\r\n`,
+ // A sentence beside a row contradicts it: neither is trusted.
+ `${idNameApi}\n00000000000000000000000000000001 Contoso Dataverse /providers/Microsoft.PowerApps/apis/shared_commondataservice Connected\n${pacSentence}`]) {
assert.throws(() => parsePacConnectionList(raw), /could not read[\s\S]*not reported as "no connections"/, JSON.stringify(raw));
}
});
@@ -536,7 +703,7 @@ function driveDiscovery({ pac, refs, refsError }) {
test('CLI discovery failure is not an empty success', async () => {
const warning = 'Warning: failed to retrieve connections.';
- const warningMessage = 'pac connection list printed output this script could not read — no connection table, JSON list or "no connections found" message '
+ const warningMessage = 'pac connection list printed output this script could not read — no connection table or JSON list '
+ `(first line: "${warning}"). It is not reported as "no connections", which would lead connection setup to create a duplicate; run \`pac connection list\` to see what it printed.`;
const malformed = '[{"Id":';
const malformedMessage = 'pac connection list printed output this script could not read — it starts like JSON but is not a connection list '
@@ -568,7 +735,7 @@ test('CLI discovery failure is not an empty success', async () => {
);
const empty = await driveDiscovery({
- pac: { status: 0, stdout: 'No connections found.', stderr: '' },
+ pac: { status: 0, stdout: EMPTY_GRID, stderr: '' },
refs: { status: 200, data: { value: [] } },
});
assert.deepEqual(empty.queries, [{
@@ -629,7 +796,7 @@ test('CLI discovery failure is not an empty success', async () => {
}]);
const refsDown = await driveDiscovery({
- pac: { status: 0, stdout: 'No connections found.', stderr: '' },
+ pac: { status: 0, stdout: EMPTY_GRID, stderr: '' },
refs: { status: 500, data: { error: { message: 'refs unavailable' } } },
});
assert.equal(refsDown.queries.length, 1, 'the reference read is attempted only after a readable listing');
@@ -645,6 +812,7 @@ test('CLI: a diagnostic after a table header, or a failure worded like emptiness
'Connection Id Connector Id\n------------- ------------\nWarning: failed to retrieve connections.',
'Id Name API Id Status\n[{"Id":',
'No connections could be found because the request failed.',
+ ...NO_CONNECTIONS_SENTENCES,
]) {
const run = await driveDiscovery({ pac: { status: 0, stdout, stderr: '' } });
assert.deepEqual(run.queries, [], `${JSON.stringify(stdout)} must not query connection references`);
@@ -652,9 +820,9 @@ test('CLI: a diagnostic after a table header, or a failure worded like emptiness
assert.equal(run.emitted[0].ok, false);
assert.match(run.emitted[0].payload.message, /could not read[\s\S]*not reported as "no connections"/);
}
- // Controls: PAC's own empty-state message, with its banner, is a successful empty listing; so is JSON after the banner.
+ // Controls: the empty grid, with its banner, is a successful empty listing; so is JSON after the banner.
const empty = await driveDiscovery({
- pac: { status: 0, stdout: 'Connected as [email protected]\r\nNo connections found.\r\n', stderr: '' },
+ pac: { status: 0, stdout: EMPTY_GRID, stderr: '' },
refs: { status: 200, data: { value: [] } },
});
assert.deepEqual(empty.emitted, [{ ok: true, payload: { ok: true, connections: [], connectionReferences: [] } }]);
@@ -729,7 +897,7 @@ test('CLI: text on stderr after a zero exit is a discovery failure, before the r
const cases = {
'a header with no rows beside a warning': [{ status: 0, stdout: header, stderr: 'Warning: failed to retrieve connections.\n' }, 'Warning: failed to retrieve connections.'],
'an empty JSON list beside an error': [{ status: 0, stdout: '[]', stderr: 'Error: the request failed\n' }, 'Error: the request failed'],
- 'PAC\'s empty-state message beside a warning': [{ status: 0, stdout: 'No connections found.', stderr: 'Warning: partial results\n' }, 'Warning: partial results'],
+ 'the empty grid beside a warning': [{ status: 0, stdout: EMPTY_GRID, stderr: 'Warning: partial results\n' }, 'Warning: partial results'],
'a readable listing beside a warning': [{ status: 0, stdout: REAL_LISTING, stderr: 'Warning: some connections were skipped\n' }, 'Warning: some connections were skipped'],
'blank lines, then a warning': [{ status: 0, stdout: header, stderr: '\r\n \t\r\n Warning: indented\r\nsecond line\r\n' }, 'Warning: indented'],
'output that is unreadable too': [{ status: 0, stdout: 'garbage', stderr: 'Error: boom\n' }, 'Error: boom'],
@@ -770,13 +938,15 @@ test('CLI: text on stderr after a zero exit is a discovery failure, before the r
// column set PAC prints (compared normalized: case and punctuation do not matter), never by one column that looks like an id column.
// `Connection Id could not be read.` has such a column, was read as a header with no rows, and so as "no connections": the answer that
// sends connection setup on to create a duplicate. The column sets, from the layouts in this file:
-// Id Name API Id Status a live capture of `pac connection list` (no dashed separator)
+// Id Name API Id Status the header of `pac connection list`'s grid (a live capture; read by its words, see pacGrid) — and under a dashed separator
// Connection Name Connector Id Connection Id the default fixed-width table, and the plain whitespace one
// Connection Id Connector Id the two-column fixed-width table
+// PAC's resources also hold a "Connection ID,Connector ID,Created By" header string that this command does not print: it is not a column set (see the test for it below).
test('a line with an id column and prose, or any column set PAC does not print, is unreadable rather than an empty table', async () => {
const lookalikes = [
'Connection Id could not be read.', 'Connection Id Error', 'Id Error', 'Id Name', 'Id Name API Id', 'Id Name API Id Status Extra',
'Name Id API Id Status', 'Connection Connector', 'Connection Id Connector Id Status', 'Connection Name Connection Id', 'Connection Name Connector Id',
+ 'Connection ID Connector ID Created By', 'Connection ID Connector ID Created By',
];
for (const header of lookalikes) {
for (const [where, stdout] of [
@@ -831,6 +1001,26 @@ test('each column set PAC prints is still a table, with rows or none, whatever t
assert.deepEqual(parsePacConnectionList('Id Name API Id Status'), []);
});
+// The belief that PAC's `ConnectionNotFound` sentence and `ConnectionListHeader` header were what this command prints is what once left an empty environment unreadable: both are
+// resource strings it does not print. Wherever the script's comments name either, the same comment says so — and no code is left behind that accepts them.
+test('the script\'s comments name PAC\'s `ConnectionNotFound` and `ConnectionListHeader` strings only as ones the command does not print, and no code reads them', () => {
+ const comments = scriptSrc.split(/\r?\n/).filter((line) => /^\s*\/\//.test(line)).map((line) => line.replace(/^\s*\/\/\s?/, ''));
+ const blocks = [];
+ let current = [];
+ for (const line of scriptSrc.split(/\r?\n/)) {
+ if (/^\s*\/\//.test(line)) current.push(line.replace(/^\s*\/\/\s?/, ''));
+ else if (current.length) { blocks.push(current.join(' ').replace(/\s+/g, ' ')); current = []; }
+ }
+ assert.ok(comments.length > 0);
+ for (const name of ['ConnectionNotFound', 'ConnectionListHeader']) {
+ const naming = blocks.filter((block) => block.includes(name));
+ assert.ok(naming.length >= 1, `${name} is explained where the parser leaves it out`);
+ for (const block of naming) assert.match(block, /does not print|not print it|nothing refers to that string/, `${name}: a comment that names it says the command does not print it`);
+ }
+ assert.doesNotMatch(scriptSrc, /NO_CONNECTIONS_MESSAGE|CREATED_BY_COLUMNS|headerCells|createdby/i, 'nothing in the parser reads either');
+ assert.doesNotMatch(scriptSrc, /^\s*(?:const|let)\s+\w+\s*=\s*\/\^no connections/im, 'and no pattern takes a sentence for "no connections"');
+});
+
// PAC's output is split into lines on CRLF, CR and LF alike, never by deleting CRs, and the auth banner is a WHOLE line. Deleting every CR
// joined a banner and the line a bare CR put after it —
// Connected as [maker001]\rWarning: failed to retrieve connections.\r\nId Name API Id Status
diff --git a/plugins/model-apps/scripts/tests/list-languages-real-bundle.test.js b/plugins/model-apps/scripts/tests/list-languages-real-bundle.test.js
new file mode 100644
index 000000000..b66837ef2
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/list-languages-real-bundle.test.js
@@ -0,0 +1,209 @@
+'use strict';
+// REAL BUNDLE: the languages script's read, through the plugin's real az-token HttpClient over a fake Dataverse that
+// answers the three reads the SDK's `getEnvironmentLanguages()` makes, in the shapes the SDK measured on live
+// environments:
+// GET organizations?$select=languagecode -> { value: [ { languagecode: <LCID> } ] } one row
+// GET RetrieveProvisionedLanguages() -> { RetrieveProvisionedLanguages: [<LCID>, ...] } the key is the function's
+// GET RetrieveAvailableLanguages() -> { LocaleIds: [<LCID>, ...] } a different key
+// A stub cannot tell the plugin that a re-vendored bundle stopped answering `ENVIRONMENT_LANGUAGES_UNREADABLE` for a
+// shape it cannot read, started to default to English, wrote to the workspace, or moved a read: this can.
+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 { createAzHttpClient } = require('../lib/sdk-http-client.js');
+const auth = require('../lib/dataverse-auth.js');
+const { readLanguages } = require('../list-languages.js');
+
+const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
+const ENV = 'https://contoso.crm.dynamics.com';
+
+const json = (statusCode, body) => ({ statusCode, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
+
+// A Dataverse holding one organization. `languages` answers each read: a number or list is the measured body; a
+// function receives the request and answers however the test needs (a status, a body of another shape).
+function fakeOrg({ base = 1033, provisioned = [1033], available = [1033], answer = {} } = {}) {
+ const requests = [];
+ async function request({ url, method, headers }) {
+ const u = new URL(url);
+ const where = decodeURIComponent(u.pathname + u.search);
+ requests.push({ method, where, authorization: headers && headers.Authorization, headers });
+ const read = (name, fallback) => (typeof answer[name] === 'function' ? answer[name]() : fallback);
+ if (method === 'GET' && /\/organizations\?\$select=languagecode$/.test(where)) {
+ return read('organization', json(200, {
+ '@odata.context': `${ENV}/api/data/v9.2/$metadata#organizations(languagecode)`,
+ value: [{ '@odata.etag': 'W/"1"', languagecode: base, organizationid: '00000000-0000-0000-0000-000000000001' }],
+ }));
+ }
+ if (method === 'GET' && /\/RetrieveProvisionedLanguages\(\)$/.test(where)) {
+ return read('provisioned', json(200, {
+ '@odata.context': `${ENV}/api/data/v9.2/$metadata#Microsoft.Dynamics.CRM.RetrieveProvisionedLanguagesResponse`,
+ RetrieveProvisionedLanguages: provisioned,
+ }));
+ }
+ if (method === 'GET' && /\/RetrieveAvailableLanguages\(\)$/.test(where)) {
+ return read('available', json(200, {
+ '@odata.context': `${ENV}/api/data/v9.2/$metadata#Microsoft.Dynamics.CRM.RetrieveAvailableLanguagesResponse`,
+ LocaleIds: available,
+ }));
+ }
+ throw new Error(`the languages read made an unexpected request: ${method} ${where}`);
+ }
+ return { request, requests };
+}
+
+function clientFor(org, tokens = []) {
+ return createAzHttpClient(ENV, {
+ getToken: (origin) => { tokens.push(origin); return 'test-token'; },
+ request: org.request,
+ sleep: async () => {},
+ });
+}
+
+test('REAL BUNDLE: an English-only, a Spanish-only and a two-language environment, each in three reads and in the planner\u2019s terms', async () => {
+ const cases = [
+ { name: 'English only', org: { base: 1033, provisioned: [1033], available: [1033] }, languages: [[1033, 'en-US', false]], base: [1033, 'en-US'] },
+ { name: 'Spanish only', org: { base: 3082, provisioned: [3082], available: [3082] }, languages: [[3082, 'es-ES', false]], base: [3082, 'es-ES'] },
+ { name: 'two languages', org: { base: 1033, provisioned: [1033, 3082], available: [1033, 3082] }, languages: [[1033, 'en-US', false], [3082, 'es-ES', false]], base: [1033, 'en-US'] },
+ { name: 'Arabic and French beside English', org: { base: 1033, provisioned: [1033, 1025, 1036], available: [1033, 1025, 1036, 3082] }, languages: [[1033, 'en-US', false], [1025, 'ar-SA', true], [1036, 'fr-FR', false]], base: [1033, 'en-US'] },
+ ];
+ for (const c of cases) {
+ const org = fakeOrg(c.org);
+ const tokens = [];
+ const result = await readLanguages(ENV, clientFor(org, tokens));
+ assert.deepStrictEqual(org.requests.map((r) => `${r.method} ${r.where.replace(/^\/api\/data\/v9\.\d\//, '')}`), [
+ 'GET organizations?$select=languagecode',
+ 'GET RetrieveProvisionedLanguages()',
+ 'GET RetrieveAvailableLanguages()',
+ ], `${c.name}: three reads, in the SDK's order, and nothing else`);
+ assert.ok(org.requests.every((r) => r.authorization === 'Bearer test-token'), `${c.name}: each read carries the az token`);
+ assert.deepStrictEqual(tokens, [ENV], `${c.name}: one token, for the environment's own origin`);
+ assert.deepStrictEqual(result.languages.map((l) => [l.lcid, l.code, l.rtl]), c.languages, c.name);
+ assert.deepStrictEqual([result.baseLanguage.lcid, result.baseLanguage.code], c.base, c.name);
+ assert.deepStrictEqual(result.unmapped, [], c.name);
+ assert.ok(!JSON.stringify(result).includes('test-token'), `${c.name}: no token in the output`);
+ }
+});
+
+test('REAL BUNDLE: an LCID this plugin cannot name comes through numeric, and the answer is still complete', async () => {
+ const org = fakeOrg({ base: 1033, provisioned: [1033, 4096], available: [1033, 4096] });
+ const result = await readLanguages(ENV, clientFor(org));
+ assert.deepStrictEqual(result.languages[1], { lcid: 4096, code: null, name: null, rtl: null });
+ assert.deepStrictEqual(result.unmapped, [4096]);
+ assert.strictEqual(result.summary[1], '4096 unknown \u2014 RTL: unknown');
+});
+
+test('REAL BUNDLE: a BASE language this plugin cannot name is reported in `unmapped` although it is not provisioned', async () => {
+ const result = await readLanguages(ENV, clientFor(fakeOrg({ base: 4096, provisioned: [1033], available: [1033] })));
+ assert.deepStrictEqual(result.baseLanguage, { lcid: 4096, code: null, name: null, rtl: null });
+ assert.deepStrictEqual(result.unmapped, [4096]);
+ assert.deepStrictEqual(result.languages.map((l) => l.lcid), [1033], 'the provisioned languages are the ones the server listed');
+});
+
+test('REAL BUNDLE: an answer it cannot read as a list of languages fails ENVIRONMENT_LANGUAGES_UNREADABLE, never an English default', async () => {
+ const shapes = {
+ 'an empty provisioned list': { provisioned: () => json(200, { RetrieveProvisionedLanguages: [] }) },
+ 'provisioned under the other function\u2019s key': { provisioned: () => json(200, { LocaleIds: [1033] }) },
+ 'a non-integer LCID': { provisioned: () => json(200, { RetrieveProvisionedLanguages: [1033, '3082'] }) },
+ 'an available list with no answer': { available: () => json(200, { LocaleIds: [] }) },
+ 'two organization rows': { organization: () => json(200, { value: [{ languagecode: 1033 }, { languagecode: 1033 }] }) },
+ 'an organization row with no language code': { organization: () => json(200, { value: [{ organizationid: 'x' }] }) },
+ 'an organization answer with no rows': { organization: () => json(200, { value: [] }) },
+ };
+ for (const [name, answer] of Object.entries(shapes)) {
+ const org = fakeOrg({ answer });
+ await assert.rejects(readLanguages(ENV, clientFor(org)), (err) => {
+ assert.strictEqual(err.code, 'ENVIRONMENT_LANGUAGES_UNREADABLE', `${name}: ${err.message}`);
+ assert.match(err.message, /Nothing is assumed in its place/, name);
+ return true;
+ }, name);
+ }
+});
+
+// Every way the Azure CLI or the identity can fail, through the REAL token reader and client. The planner falls back to
+// `pac model list-languages` on ANY non-zero exit of the script, so what these pin is that each one is a rejected
+// read — never an answer, and never an English default in the place of one. The SDK reports them all as the same
+// `CONNECTION_ERROR`: a failure before any answer (statusCode 0) wraps the client's own error, so a missing Azure CLI
+// reads like a dropped connection, and a refusal carries its HTTP status. Nothing in either is a code a planner could
+// match, which is why its rule is the exit status.
+// az missing `spawn az ENOENT: not found on PATH` (process-runner.js) -> kind 'missing'
+// az too slow `ETIMEDOUT` -> kind 'timeout' (cli-failure.js)
+// az signed out any other failure of `az account get-access-token` -> kind 'failed'
+const failingAz = (code, message) => (origin, options) => auth.getAuthToken(origin, { ...options, exec: () => { throw Object.assign(new Error(message), { code }); } });
+
+test('REAL BUNDLE: every Azure CLI or identity failure rejects the read — no answer, and no request made without a token', async () => {
+ const cases = {
+ 'the Azure CLI is not installed': { getToken: failingAz('ENOENT', 'spawn az ENOENT: not found on PATH'), statusCode: 0, message: /Could not get an Azure CLI token for .*: Azure CLI \(`az`\) is not on PATH/ },
+ 'the Azure CLI is too slow': { getToken: failingAz('ETIMEDOUT', 'spawnSync az ETIMEDOUT'), statusCode: 0, message: /Could not get an Azure CLI token for .*: `az account get-access-token` did not answer within \d+ s/ },
+ 'the Azure CLI is signed out': { getToken: failingAz(1, 'Command failed: az account get-access-token'), statusCode: 0, message: /Failed to get Azure CLI token for .*Run 'az login' first/ },
+ };
+ for (const [name, c] of Object.entries(cases)) {
+ const org = fakeOrg();
+ await assert.rejects(readLanguages(ENV, createAzHttpClient(ENV, { getToken: c.getToken, request: org.request, sleep: async () => {} })), (err) => {
+ assert.strictEqual(err.code, 'CONNECTION_ERROR', `${name}: ${err.message}`);
+ assert.strictEqual(err.statusCode, c.statusCode, name);
+ assert.match(err.message, c.message, name);
+ return true;
+ }, name);
+ assert.deepStrictEqual(org.requests, [], `${name}: the Dataverse was never asked`);
+ }
+ const refusals = {
+ 'a token for another tenant (401)': { answer: () => json(401, { error: { message: 'Unauthorized' } }), statusCode: 401, message: /^HTTP 401 from / },
+ 'an identity that is no user of the environment (403)': { answer: () => json(403, { error: { code: '0x80072560', message: 'The user is not a member of the organization.' } }), statusCode: 403, message: /^HTTP 403 from .*The user is not a member of the organization\./ },
+ 'a connection that drops': { answer: () => ({ error: 'ECONNRESET' }), statusCode: 0, message: /^Transport failure reaching .*Request failed: ECONNRESET/ },
+ 'an environment that is down (503)': { answer: () => json(503, { error: { message: 'Service unavailable' } }), statusCode: 503, message: /^HTTP 503 from / },
+ };
+ for (const [name, c] of Object.entries(refusals)) {
+ const client = createAzHttpClient(ENV, { getToken: () => 'test-token', request: async () => c.answer(), sleep: async () => {} });
+ await assert.rejects(readLanguages(ENV, client), (err) => {
+ assert.strictEqual(err.code, 'CONNECTION_ERROR', `${name}: ${err.message}`);
+ assert.strictEqual(err.statusCode, c.statusCode, name);
+ assert.match(err.message, c.message, name);
+ assert.ok(!err.message.includes('test-token'), `${name}: no token in the message`);
+ return true;
+ }, name);
+ }
+});
+
+test('REAL BUNDLE: a read the platform refuses fails with its own error, and no partial answer is returned', async () => {
+ for (const [name, answer] of Object.entries({
+ organization: { organization: () => json(403, { error: { code: '0x80040220', message: 'SecLib::AccessCheckEx failed' } }) },
+ provisioned: { provisioned: () => json(403, { error: { code: '0x80040220', message: 'SecLib::AccessCheckEx failed' } }) },
+ available: { available: () => json(404, { error: { message: 'Resource not found for the segment RetrieveAvailableLanguages' } }) },
+ })) {
+ const org = fakeOrg({ answer });
+ await assert.rejects(readLanguages(ENV, clientFor(org)), (err) => {
+ assert.notStrictEqual(err.code, 'ENVIRONMENT_LANGUAGES_UNREADABLE', `${name}: a refused read is not an unreadable shape`);
+ assert.match(err.message, /40[34]|SecLib|Resource not found/, `${name}: ${err.message}`);
+ return true;
+ }, name);
+ }
+});
+
+test('REAL BUNDLE: the read uses no workspace — nothing is written, not even the manifest an initialized one lays down', async () => {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'languages-ws-'));
+ try {
+ const org = fakeOrg({ provisioned: [1033, 3082], available: [1033, 3082] });
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: ENV, httpClient: clientFor(org) });
+ assert.deepStrictEqual(await sdk.getEnvironmentLanguages(), { baseLanguage: 1033, provisioned: [1033, 3082], available: [1033, 3082] });
+ assert.deepStrictEqual(fs.readdirSync(dir), [], 'the SDK never touched its workspace, so the script needs no initWorkspace()');
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test('REAL BUNDLE: the script leaves no throwaway directory behind, on a read or on a refused one', async () => {
+ const made = [];
+ const mkdtemp = fs.mkdtempSync;
+ fs.mkdtempSync = (prefix, ...rest) => { const dir = mkdtemp(prefix, ...rest); made.push(dir); return dir; };
+ try {
+ await readLanguages(ENV, clientFor(fakeOrg()));
+ await assert.rejects(readLanguages(ENV, clientFor(fakeOrg({ answer: { provisioned: () => json(403, { error: { message: 'no' } }) } }))));
+ } finally {
+ fs.mkdtempSync = mkdtemp;
+ }
+ assert.strictEqual(made.length, 2);
+ for (const dir of made) assert.strictEqual(fs.existsSync(dir), false, dir);
+});
diff --git a/plugins/model-apps/scripts/tests/list-languages.test.js b/plugins/model-apps/scripts/tests/list-languages.test.js
new file mode 100644
index 000000000..f420beca9
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/list-languages.test.js
@@ -0,0 +1,377 @@
+'use strict';
+// scripts/list-languages.js, end to end through its main(): flags, the origin check, the one SDK read, the planner's
+// output, and the throwaway workspace — with the SDK and the HTTP client stubbed (the real bundle is driven in
+// list-languages-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 { loadCli } = require('./helpers/cli-harness.js');
+const realAuth = require('../lib/dataverse-auth.js');
+
+const SCRIPT = path.resolve(__dirname, '..', 'list-languages.js');
+const ENV = 'https://contoso.crm.dynamics.com';
+
+// Runs main() with `argv`. `answer` is what `getEnvironmentLanguages` resolves, or a function that rejects/throws.
+// The stubbed emitResult ends the run the way the real one does (process.exit), so a test can see what came after.
+async function run(argv, answer = { baseLanguage: 1033, provisioned: [1033], available: [1033] }) {
+ const events = [];
+ const emitted = [];
+ const emitOptions = [];
+ const requires = {
+ './lib/dataverse-auth.js': {
+ ...realAuth,
+ emitResult: (ok, payload, options) => {
+ emitted.push({ ok, payload });
+ emitOptions.push(options);
+ const exit = new Error(`process.exit(${ok ? 0 : 1})`);
+ exit.exitCode = ok ? 0 : 1;
+ throw exit;
+ },
+ },
+ './lib/sdk-http-client.js': {
+ createAzHttpClient: (env) => {
+ events.push({ type: 'client', env });
+ return { marker: 'az-client', env };
+ },
+ },
+ './vendor/cds-maker-sdk.cjs': {
+ createNodeWorkspaceStorage: (dir) => ({ dir }),
+ createMakerSdk: (cfg) => {
+ events.push({ type: 'sdk', cfg });
+ // Only the one method the script may call: any other (initWorkspace, a workspace read) is a TypeError.
+ return {
+ getEnvironmentLanguages: async () => {
+ events.push({ type: 'getEnvironmentLanguages' });
+ if (typeof answer === 'function') return answer();
+ return answer;
+ },
+ };
+ },
+ },
+ };
+ const cli = loadCli(SCRIPT, { requires, argv });
+ let exitCode = 0;
+ try {
+ await cli.main();
+ } catch (err) {
+ if (typeof err.exitCode !== 'number') throw err;
+ exitCode = err.exitCode;
+ }
+ const sdk = events.find((e) => e.type === 'sdk');
+ return { events, emitted, emitOptions, exitCode, stderr: cli.stderrText(), stdout: cli.stdoutText(), workspaceDir: sdk && sdk.cfg.workspaceStorage.dir };
+}
+
+test('no --env is a usage error: nothing is read and no workspace is made', async () => {
+ const r = await run([]);
+ assert.strictEqual(r.exitCode, 1);
+ assert.strictEqual(r.stdout, '', 'a usage error prints nothing on stdout: the planner reads a line there only for a failed read');
+ assert.match(r.stderr, /Usage: node scripts\/list-languages\.js --env <envUrl>/);
+ assert.deepStrictEqual(r.events, []);
+ assert.deepStrictEqual(r.emitted, []);
+});
+
+test('an unknown flag, or --env with no value, is refused naming the flag', async () => {
+ const typo = await run(['--envv', ENV]);
+ assert.strictEqual(typo.exitCode, 1);
+ assert.strictEqual(typo.stdout, '', 'nothing on stdout');
+ assert.match(typo.stderr, /unknown flag\(s\): --envv \(did you mean --env\?\)/);
+ assert.deepStrictEqual(typo.events, []);
+
+ const bare = await run(['--env']);
+ assert.strictEqual(bare.exitCode, 1);
+ assert.strictEqual(bare.stdout, '', 'nothing on stdout');
+ assert.match(bare.stderr, /--env requires a value/);
+ assert.deepStrictEqual(bare.events, []);
+});
+
+test('an --env that is not a Dataverse https origin is refused before any token or SDK exists', async () => {
+ for (const env of ['https://example.com', 'http://contoso.crm.dynamics.com', 'https://contoso.crm.dynamics.com/api/data/v9.2', 'contoso.crm.dynamics.com']) {
+ const r = await run(['--env', env]);
+ assert.strictEqual(r.exitCode, 1, env);
+ assert.strictEqual(r.stdout, '', `${env}: nothing on stdout`);
+ assert.match(r.stderr, /is not a Dataverse environment URL/, env);
+ assert.match(r.stderr, /Usage: node scripts\/list-languages\.js/, env);
+ assert.deepStrictEqual(r.events, [], `${env}: no client, no SDK`);
+ }
+});
+
+test('it reads the languages once through the az-token client for the normalized origin, and prints the planner\u2019s JSON', async () => {
+ const r = await run(['--env', 'https://Contoso.CRM.dynamics.com/'], { baseLanguage: 1033, provisioned: [1033, 1025, 1036], available: [1033, 1025, 1036, 3082] });
+ assert.strictEqual(r.exitCode, 0);
+ assert.deepStrictEqual(r.events.map((e) => e.type), ['client', 'sdk', 'getEnvironmentLanguages'], 'one client, one SDK, one read');
+ assert.strictEqual(r.events[0].env, ENV, 'the client is built for the origin, lower-cased and without the slash');
+ assert.strictEqual(r.events[1].cfg.instanceUrl, ENV);
+ assert.strictEqual(r.events[1].cfg.httpClient.marker, 'az-client');
+
+ assert.strictEqual(r.emitted.length, 1);
+ const { ok, payload } = r.emitted[0];
+ assert.strictEqual(ok, true);
+ assert.strictEqual(payload.ok, true);
+ assert.deepStrictEqual(Object.keys(payload).sort(), ['baseLanguage', 'languages', 'ok', 'summary', 'unmapped']);
+ assert.strictEqual(payload.baseLanguage.lcid, 1033);
+ assert.strictEqual(payload.baseLanguage.code, 'en-US');
+ assert.deepStrictEqual(payload.languages.map((l) => [l.lcid, l.code, l.rtl]), [[1033, 'en-US', false], [1025, 'ar-SA', true], [1036, 'fr-FR', false]]);
+ assert.deepStrictEqual(payload.unmapped, []);
+ assert.deepStrictEqual(payload.summary, ['1033 en-US \u2014 RTL: No', '1025 ar-SA \u2014 RTL: Yes', '1036 fr-FR \u2014 RTL: No']);
+ // Each language carries a name only as a courtesy: a string, or null where this host's Intl has none.
+ for (const l of payload.languages) assert.ok(l.name === null || (typeof l.name === 'string' && l.name), `${l.lcid} name`);
+ assert.strictEqual(r.stderr, '', 'a clean read prints nothing on stderr');
+});
+
+test('the throwaway workspace is removed after a read, and after a failed one', async () => {
+ const ok = await run(['--env', ENV]);
+ assert.ok(ok.workspaceDir, 'the SDK was given a workspace directory');
+ assert.strictEqual(fs.existsSync(ok.workspaceDir), false, 'removed after a read');
+
+ const bad = await run(['--env', ENV], () => { throw new Error('boom'); });
+ assert.ok(bad.workspaceDir);
+ assert.strictEqual(fs.existsSync(bad.workspaceDir), false, 'removed after a failed read');
+});
+
+test('a failed read exits 1 with the SDK\u2019s own code and message, never an English default', async () => {
+ const unreadable = Object.assign(
+ new Error('The org\u2019s languages could not be read: RetrieveProvisionedLanguages answered no list of language codes in \u2018RetrieveProvisionedLanguages\u2019. Nothing is assumed in its place \u2014 retry, or check the caller\u2019s access to the org.'),
+ { code: 'ENVIRONMENT_LANGUAGES_UNREADABLE' }
+ );
+ const r = await run(['--env', ENV], () => { throw unreadable; });
+ assert.strictEqual(r.exitCode, 1);
+ assert.deepStrictEqual(r.emitted, [{ ok: false, payload: { ok: false, error: unreadable.message, code: 'ENVIRONMENT_LANGUAGES_UNREADABLE' } }]);
+ assert.ok(!r.emitted.some((e) => e.ok), 'no success was emitted beside it');
+});
+
+test('a failure that carries no SDK code carries its message and no code field', async () => {
+ const r = await run(['--env', ENV], async () => { throw new Error('boom'); });
+ assert.strictEqual(r.exitCode, 1);
+ assert.deepStrictEqual(r.emitted, [{ ok: false, payload: { ok: false, error: 'boom' } }]);
+});
+
+// What the real SDK throws when the az-token client cannot supply a token, or the platform refuses it, is a
+// ConnectionError: `code: 'CONNECTION_ERROR'`, with `statusCode` 0 for a failure before any answer (the client's own
+// error is wrapped, so an Azure CLI that is missing, signed out or slow reads like a dropped connection) and the HTTP
+// status for a refusal. Those messages are the ones the real client and the real bundle produce
+// (list-languages-real-bundle.test.js drives them through both). Nothing in them is a code the planner could match —
+// which is why it falls back on the exit status alone — so what matters here is that every one of them is a LOUD
+// failure: exit 1, `ok: false`, the message, and nothing that reads as an answer.
+test('every Azure CLI or identity failure is an ordinary failed read: exit 1, `ok: false`, the SDK\u2019s CONNECTION_ERROR', async () => {
+ const origin = `${ENV}/api/data/v9.0/organizations?$select=languagecode`;
+ const failures = {
+ 'the Azure CLI is not installed': [0, `Transport failure reaching ${origin}: Could not get an Azure CLI token for ${ENV}: Azure CLI (\`az\`) is not on PATH. Install it from https://aka.ms/azure-cli and run \`az login\`.`],
+ 'the Azure CLI is signed out': [0, `Transport failure reaching ${origin}: Failed to get Azure CLI token for ${ENV}. Run 'az login' first.`],
+ 'the Azure CLI is too slow': [0, `Transport failure reaching ${origin}: Could not get an Azure CLI token for ${ENV}: \`az account get-access-token\` did not answer within 60 s.`],
+ 'the token is for another tenant': [401, `HTTP 401 from ${origin}: Unauthorized`],
+ 'the identity is not a user of the environment': [403, `HTTP 403 from ${origin}: The user is not a member of the organization.`],
+ };
+ for (const [why, [statusCode, message]] of Object.entries(failures)) {
+ const failure = Object.assign(new Error(message), { code: 'CONNECTION_ERROR', statusCode });
+ const r = await run(['--env', ENV], () => { throw failure; });
+ assert.strictEqual(r.exitCode, 1, why);
+ assert.deepStrictEqual(r.emitted, [{ ok: false, payload: { ok: false, error: message, code: 'CONNECTION_ERROR' } }], why);
+ assert.strictEqual(r.stdout, '', `${why}: nothing but the emitted result`);
+ }
+});
+
+test('an unknown BASE language is reported in `unmapped` and on stderr although it is not provisioned', async () => {
+ const r = await run(['--env', ENV], { baseLanguage: 4096, provisioned: [1033], available: [1033] });
+ assert.strictEqual(r.exitCode, 0);
+ const { payload } = r.emitted[0];
+ assert.deepStrictEqual(payload.baseLanguage, { lcid: 4096, code: null, name: null, rtl: null });
+ assert.deepStrictEqual(payload.unmapped, [4096]);
+ assert.deepStrictEqual(payload.languages.map((l) => l.lcid), [1033]);
+ assert.match(r.stderr, /LCID 4096 has no culture code in this plugin's table/);
+});
+
+test('both outcomes are printed as pure ASCII: the script asks emitResult to escape every other character', async () => {
+ const ok = await run(['--env', ENV]);
+ assert.deepStrictEqual(ok.emitOptions, [{ ascii: true }]);
+ const bad = await run(['--env', ENV], () => { throw new Error('boom'); });
+ assert.deepStrictEqual(bad.emitOptions, [{ ascii: true }]);
+});
+
+test('an LCID the table cannot name is reported on stderr and in `unmapped`, with null in its place', async () => {
+ const r = await run(['--env', ENV], { baseLanguage: 1033, provisioned: [1033, 4096], available: [1033] });
+ assert.strictEqual(r.exitCode, 0);
+ const { payload } = r.emitted[0];
+ assert.deepStrictEqual(payload.unmapped, [4096]);
+ assert.deepStrictEqual(payload.languages[1], { lcid: 4096, code: null, name: null, rtl: null });
+ assert.strictEqual(payload.summary[1], '4096 unknown \u2014 RTL: unknown');
+ assert.match(r.stderr, /LCID 4096 has no culture code in this plugin's table/);
+});
+
+test('the script is a CLI only when run directly, and exports the read for the real-bundle test', () => {
+ const mod = require('../list-languages.js');
+ assert.deepStrictEqual(Object.keys(mod), ['readLanguages']);
+ assert.strictEqual(typeof mod.readLanguages, 'function');
+});
+
+// --- the documents that send the planner to it ------------------------------------------------------------
+
+const PLUGIN = path.resolve(__dirname, '..', '..');
+const read = (...parts) => fs.readFileSync(path.join(PLUGIN, ...parts), 'utf8');
+// Whitespace folded and a block quote's `> ` marker dropped: the documents wrap their lines and the checks below read
+// sentences.
+const squash = (text) => text.replace(/^>\s?/gm, '').replace(/\s+/g, ' ');
+// The planner's own section on language detection, up to the next `### ` heading.
+function languageSection() {
+ const planner = read('agents', 'genpage-planner.md');
+ const start = planner.indexOf('### Detect Configured Languages');
+ const end = planner.indexOf('\n### ', start + 1);
+ assert.ok(start !== -1 && end !== -1, 'the planner has a Detect Configured Languages section');
+ return planner.slice(start, end);
+}
+
+test('the planner, the genpage skill and the references run the script first — `pac model list-languages` only comes after it', () => {
+ for (const parts of [['agents', 'genpage-planner.md'], ['skills', 'genpage', 'SKILL.md'], ['references', 'localization.md'], ['references', 'rules.md'], ['references', 'plan-schema.md']]) {
+ const text = read(...parts);
+ const script = text.indexOf('list-languages.js');
+ const pac = text.indexOf('pac model list-languages');
+ assert.ok(script !== -1, `${parts.join('/')} names the script`);
+ assert.ok(pac === -1 || script < pac, `${parts.join('/')} names the script before the command that falls back on it`);
+ }
+ const section = languageSection();
+ assert.match(section, /^node "\$\{PLUGIN_ROOT\}\/scripts\/list-languages\.js" --env '<envUrl>'$/m);
+ assert.match(section, /`<LCID> <Code> \u2014 RTL: Yes\|No`/, 'the line the plan carries is unchanged');
+ assert.match(squash(read('skills', 'genpage', 'SKILL.md')), /Language detection \(`node "\$\{PLUGIN_ROOT\}\/scripts\/list-languages\.js" --env '<envUrl>'`; when that exits non-zero, `pac model list-languages --environment '<envUrl>'` \u2014 the Azure CLI is not needed here\) \u2014 only on new-page path/);
+});
+
+test('the planner falls back to `pac model list-languages` on ANY non-zero exit of the script — decided by the exit status, never by a phrase of the message', () => {
+ const section = languageSection();
+ const text = squash(section);
+ // The script first, then the rule, then `pac` as a command of its own in a fenced block.
+ const script = section.indexOf('node "${PLUGIN_ROOT}/scripts/list-languages.js"');
+ const rule = section.indexOf('**Any non-zero exit');
+ const pac = section.search(/^pac model list-languages --environment '<envUrl>'$/m);
+ assert.ok(script !== -1 && script < rule && rule < pac, `script ${script} < rule ${rule} < pac ${pac}`);
+ assert.match(section, /```powershell\r?\npac model list-languages --environment '<envUrl>'\r?\n```/);
+ assert.match(text, /decide by the exit status, never by the wording of the message/);
+ // A script that never answers is a failure too: what ends it is the shell tool giving up, not an exit status.
+ assert.match(text, /\*\*Any non-zero exit \u2014 or no answer before your shell tool gives up \u2014 means the script could not read the languages; decide by the exit status, never by the wording of the message\.\*\*/);
+ // The fallback reads the environment the script was given. Without `--environment`, `pac` answers for the active organization of its
+ // auth profile, and the plan would carry another environment's languages under this environment's URL.
+ assert.match(text, /Pass the same `<envUrl>` the script was given: without `--environment`, `pac` answers for the active organization of its auth profile, which is not necessarily the environment this plan is for/);
+ // What the rule must not be: a trigger on a phrase. The sign-in advice `Run 'az login' first` is what ONE of the
+ // client's failures says; a missing Azure CLI, a slow one and a token another tenant refuses say something else,
+ // and the planner took each of those for "any other failure", reported it and stopped.
+ assert.doesNotMatch(text, /Run 'az login' first/);
+ // And no failure turns into a request that the user sign in: this flow works without `az`.
+ assert.doesNotMatch(text, /needs_input/);
+ assert.match(text, /do not stop and do not ask the user to run `az login`/);
+ assert.match(text, /`\/genpage` has never needed `az` for a page over existing entities or mock data/);
+ // `<envUrl>` is the column `pac auth list` prints ("Environment Url"); `Org URL:` is the line of `pac org who`.
+ assert.match(text, /`<envUrl>` is the selected environment's `Environment Url` from the `pac auth list` table \(Step 2; the `Org URL:` line of `pac org who` is the same address\)/);
+});
+
+test('the planner says it fell back — in the log and in its report of the environment — and stops only when pac fails too', () => {
+ const text = squash(languageSection());
+ assert.match(text, /Then \*\*say that you did\*\*/);
+ assert.match(text, /In `workflow-log\.md`, record the script's command line with its result \(its stdout, or its stderr when stdout is empty\), and then the `pac model list-languages` line with its table, each verbatim/);
+ assert.match(text, /In your report of the environment, say so: "Languages read with `pac model list-languages`: the languages script could not read them/);
+ assert.match(text, /If `pac model list-languages` fails as well, report that and stop\. Never assume the environment is English-only/);
+ // A failed read prints its JSON on stdout; a usage error exits 1 before any read and prints nothing there.
+ assert.match(text, /A failed read prints `\{ "ok": false, "error": "\u2026", "code": "\u2026" \}` on stdout \(`code` only when the SDK gave one\); a usage error, such as an `--env` that carries a path, prints nothing there and names the flag on stderr/);
+ // The commands a log records verbatim include the fallback, as it is run: pinned to the environment.
+ assert.match(squash(read('agents', 'genpage-planner.md')), /`` `pac model list-languages --environment '<envUrl>'` `` \(the fallback below\)/);
+ // The section stops in one place only: when pac fails too. A second stop — on one code of the script, say — would keep the planner from the
+ // fallback for the very failures the fallback is for. Its words say "stop" twice: "do not stop" (for az) and "report that and stop".
+ assert.strictEqual((text.match(/\bstop\b/gi) || []).length, 2, 'no stop but the two this test names');
+ assert.match(text, /do not stop and do not ask the user to run `az login`/);
+});
+
+test('README\u2019s promise — /genpage works without az for pages over existing entities or mock data — is still true: its one az read falls back to pac', () => {
+ const readme = squash(read('README.md'));
+ assert.match(readme, /Without `az`, the `\/genpage` skill still works for pages over existing entities or mock data \u2014 it only fails when entity creation is needed\./);
+ assert.match(readme, /Detecting the environment's languages uses `az` when it is signed in and falls back to `pac model list-languages --environment '<envUrl>'` when it is not\./);
+ // The planner's section is what makes the sentence true: without the fallback the first step of every new page needs az.
+ assert.match(squash(languageSection()), /fall back to the command that read the languages before this script, which signs in through `pac`/);
+});
+
+// Without `--environment`, `pac model list-languages` answers for the ACTIVE organization of pac's auth profile — not necessarily the environment the
+// plan is for — so a document that tells the planner to run it, or names it as the fallback, names the pinned command. (The planner's own section is
+// pinned above, where it gives the command; its later sentences refer to it by name.)
+test('every document that names the fallback names it pinned to the environment', () => {
+ for (const parts of [['skills', 'genpage', 'SKILL.md'], ['README.md'], ['references', 'localization.md'], ['references', 'plan-schema.md'], ['references', 'rules.md'], ['AGENTS.md']]) {
+ const text = read(...parts);
+ assert.ok(text.includes('pac model list-languages'), `${parts.join('/')} names the fallback`);
+ assert.deepStrictEqual(text.match(/pac model list-languages(?! --environment '<envUrl>')/g) || [], [], `${parts.join('/')} names it without --environment`);
+ }
+});
+
+test('the planner\u2019s example output is the shape — and the exact ASCII text — the script prints, field for field', () => {
+ const { describeEnvironmentLanguages } = require('../lib/lcid-cultures.js');
+ const block = /```json\r?\n(\{"ok":true[^\r\n]*\})\r?\n```/.exec(read('agents', 'genpage-planner.md'));
+ assert.ok(block, 'the planner shows the script\u2019s JSON line');
+ assert.match(block[1], /^[\x00-\x7e]*$/, 'the script prints pure ASCII, so the example does');
+ assert.ok(block[1].includes('"1033 en-US \\u2014 RTL: No"'), 'the dash of a summary line is the \\uXXXX escape the script writes');
+ const example = JSON.parse(block[1]);
+ const real = { ok: true, ...describeEnvironmentLanguages({ baseLanguage: 1033, provisioned: [1033, 1025] }) };
+ assert.deepStrictEqual(Object.keys(example), Object.keys(real));
+ assert.deepStrictEqual(Object.keys(example.baseLanguage), Object.keys(real.baseLanguage));
+ assert.deepStrictEqual(Object.keys(example.languages[0]), Object.keys(real.languages[0]));
+ assert.deepStrictEqual(example.languages.map((l) => [l.lcid, l.code, l.rtl]), real.languages.map((l) => [l.lcid, l.code, l.rtl]));
+ assert.deepStrictEqual(example.summary, real.summary);
+});
+
+// --- end to end: the real script in a real process ---------------------------------------------------------
+// What the planner's rule leans on — exit 0 with one line it can read, exit 1 with an `ok: false` line for every
+// failure — and what keeps the line readable on any console code page (pure ASCII on stdout) are properties of a PROCESS, not of main().
+
+const { spawnSync } = require('node:child_process');
+const os = require('node:os');
+const PRELOAD = path.resolve(__dirname, 'helpers', 'fake-org-languages-preload.js');
+
+const runScript = (env, nodeArgs = []) => spawnSync(process.execPath, [...nodeArgs, SCRIPT, '--env', ENV], { env, encoding: 'utf8', timeout: 120000 });
+const stdoutLines = (r) => r.stdout.split(/\r?\n/).filter(Boolean);
+
+test('END TO END: against a fake org the real script prints one pure-ASCII JSON line, which decodes to the planner\u2019s shape, and exits 0', () => {
+ const org = { base: 1033, provisioned: [1033, 1025, 1044], available: [1033, 1025, 1044] };
+ const r = runScript({ ...process.env, FAKE_ORG_LANGUAGES: JSON.stringify(org) }, ['--require', PRELOAD]);
+ assert.strictEqual(r.status, 0, r.stderr);
+ assert.strictEqual(r.stderr, '');
+ assert.strictEqual(stdoutLines(r).length, 1, 'one line');
+ // A raw dash would reach a Windows PowerShell 5.1 capture as mojibake (UTF-8 read as the OEM code page): the line
+ // carries escapes instead.
+ assert.match(r.stdout, /^[\x00-\x7e\r\n]*$/, 'pure ASCII');
+ assert.ok(r.stdout.includes('\\u2014'), 'the summary lines\u2019 dash is an escape');
+ const result = JSON.parse(stdoutLines(r)[0]);
+ assert.strictEqual(result.ok, true);
+ assert.deepStrictEqual(result.summary, ['1033 en-US \u2014 RTL: No', '1025 ar-SA \u2014 RTL: Yes', '1044 nb-NO \u2014 RTL: No']);
+ assert.deepStrictEqual(result.languages.map((l) => l.lcid), [1033, 1025, 1044]);
+ assert.deepStrictEqual(result.unmapped, []);
+});
+
+test('END TO END: a refused read prints one `ok: false` ASCII line on stdout, the message as written on stderr, and exits 1', () => {
+ const refuse = { status: 403, message: 'The user \u2014 is not a member of the organization.' };
+ const r = runScript({ ...process.env, FAKE_ORG_LANGUAGES: JSON.stringify({ refuse }) }, ['--require', PRELOAD]);
+ assert.strictEqual(r.status, 1);
+ assert.strictEqual(stdoutLines(r).length, 1, 'one line');
+ assert.match(r.stdout, /^[\x00-\x7e\r\n]*$/, 'pure ASCII');
+ const result = JSON.parse(stdoutLines(r)[0]);
+ assert.strictEqual(result.ok, false);
+ assert.strictEqual(result.code, 'CONNECTION_ERROR');
+ assert.ok(result.error.includes('HTTP 403') && result.error.includes('The user \u2014 is not a member of the organization.'), result.error);
+ assert.ok(!('languages' in result) && !('baseLanguage' in result), 'nothing that reads as an answer');
+ assert.ok(r.stderr.includes('The user \u2014 is not a member'), 'stderr is for people: the message, not escaped');
+});
+
+test('END TO END, with the Azure CLI not on PATH: exit 1 and an `ok: false` line — no languages, and no English default in their place', () => {
+ const { resolveExecutable } = require('../lib/process-runner.js');
+ const emptyPath = fs.mkdtempSync(path.join(os.tmpdir(), 'no-az-'));
+ try {
+ const env = { ...process.env };
+ // Windows names the variable `Path`, and a second spelling beside it would leave the child one of the two.
+ for (const key of Object.keys(env)) if (key.toUpperCase() === 'PATH') delete env[key];
+ env.PATH = emptyPath;
+ assert.strictEqual(resolveExecutable('az', { env }), null, 'the premise: no `az` is found under this PATH');
+ const r = runScript(env);
+ assert.strictEqual(r.status, 1, r.stderr);
+ assert.strictEqual(stdoutLines(r).length, 1, 'one line');
+ const result = JSON.parse(stdoutLines(r)[0]);
+ assert.strictEqual(result.ok, false);
+ assert.strictEqual(result.code, 'CONNECTION_ERROR');
+ assert.match(result.error, /Azure CLI/, 'it says what failed');
+ assert.ok(!('languages' in result) && !('baseLanguage' in result), 'no answer, not even an English one');
+ assert.match(r.stderr, /Azure CLI/);
+ } finally {
+ fs.rmSync(emptyPath, { recursive: true, force: true });
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/localization-reference.test.js b/plugins/model-apps/scripts/tests/localization-reference.test.js
index 23c014827..0c0f2af25 100644
--- a/plugins/model-apps/scripts/tests/localization-reference.test.js
+++ b/plugins/model-apps/scripts/tests/localization-reference.test.js
@@ -1,8 +1,9 @@
'use strict';
// #585 item 6: the localization reference must never decide text direction from a hand-kept LCID list.
// It named five Arabic LCIDs and Hebrew, so every other right-to-left culture — the remaining Arabic
-// regions, Persian, Urdu, Pashto and more — rendered left-to-right. Direction now comes from PAC's RTL
-// column, with a script-based fallback; these tests pin that fallback's data against culture metadata.
+// regions, Persian, Urdu, Pashto and more — rendered left-to-right. Direction now comes from the `rtl`
+// field of scripts/list-languages.js (which read PAC's RTL column before that script replaced `pac model
+// list-languages`), with a script-based fallback; these tests pin that fallback's data against culture metadata.
const test = require('node:test');
const assert = require('node:assert');
const fs = require('node:fs');
@@ -31,10 +32,10 @@ function docRtlScripts() {
return new Set([...m[1].matchAll(/"([A-Z][a-z]{3})"/g)].map((x) => x[1]));
}
-test('the localization reference takes text direction from PAC, not from a hand-kept LCID list', () => {
+test('the localization reference takes text direction from the languages script, not from a hand-kept LCID list', () => {
const section = DOC.slice(DOC.indexOf('### RTL Layout Support'), DOC.indexOf('### User Settings for Formatting'));
assert.ok(section.length > 0, 'the RTL section exists');
- assert.match(section, /\*\*RTL\*\* column of `pac model list-languages`/);
+ assert.match(section, /`rtl` field of `scripts\/list-languages\.js`/);
assert.doesNotMatch(section, /\b(1025|1037|2049|3073|4097|5121)\b/, 'no LCIDs are given as the rule');
});
diff --git a/plugins/model-apps/scripts/tests/lookup-label-default.test.js b/plugins/model-apps/scripts/tests/lookup-label-default.test.js
new file mode 100644
index 000000000..bb885c505
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/lookup-label-default.test.js
@@ -0,0 +1,1357 @@
+'use strict';
+// ADO 6691205 — a 1:N lookup column whose spec omits `lookup.displayName` must be labelled with the
+// REFERENCED (parent) table's display name, as the maker portal does, instead of a logical name.
+//
+// The gap, reproduced from the code: entity-provision.js handed `lookupDisplayName: undefined` to the
+// SDK, and the SDK's own fallback is the referenced table's LOGICAL name (`label(opts.lookupDisplayName
+// ?? opts.referencedEntity, lcid)`), so the column — and every form cell, whose label the SDK derives
+// from the column's DisplayName at push — read "new_project" where a maker expects "Project".
+//
+// Three layers are covered, because a mock would keep passing against a bundle that ignored the option:
+// 1. the pure helper (app-spec.js) every surface shares;
+// 2. the data-model phase, against the engine's own call sequence;
+// 3. the REAL vendored bundle, asserting the request body the SDK actually serializes.
+const { test } = require('node:test');
+const assert = require('node:assert');
+const os = require('node:os');
+const path = require('node:path');
+const fs = require('node:fs');
+const {
+ lookupLabelFor,
+ lookupParentNeedsEnvironment,
+ lookupColumnsFor,
+ humanizeTableName,
+ isOldLookupColumnLabel,
+ isOldLookupFieldLabel,
+ relationshipSchemaName,
+} = require('../lib/app-spec.js');
+const { makeRunner, provisionDataModel, relationshipsInCreateOrder } = require('../lib/entity-provision.js');
+const { compileFormIntent } = require('../lib/artifact-intent.js');
+
+const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
+
+const project = (extra) => ({ schemaName: 'contoso_Project', displayName: 'Project', primaryAttribute: { schemaName: 'contoso_name' }, columns: [], ...extra });
+const task = (extra) => ({ schemaName: 'contoso_Task', displayName: 'Task', primaryAttribute: { schemaName: 'contoso_name' }, columns: [], ...extra });
+const oneToMany = (referenced, lookup) => ({ type: 'OneToMany', referenced, referencing: 'contoso_task', lookup });
+const specOf = (entities, relationships, extra) => ({
+ solution: { uniqueName: 'S', publisherPrefix: 'contoso' },
+ entities,
+ relationships,
+ ...extra,
+});
+
+// ── 1. the shared helper ────────────────────────────────────────────────────────────────────────
+
+test('ADO 6691205: an omitted lookup.displayName defaults to the declared parent table\'s displayName', () => {
+ const spec = specOf([project(), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })]);
+ assert.deepStrictEqual(lookupLabelFor(spec, spec.relationships[0]), { label: 'Project', source: 'table' });
+});
+
+test('ADO 6691205: a LOCALIZED parent displayName is kept as the map, not flattened', () => {
+ const map = { 1033: 'Project', 3082: 'Proyecto' };
+ const spec = specOf([project({ displayName: map, pluralName: { 1033: 'Projects', 3082: 'Proyectos' } }), task()],
+ [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })], { languageCode: 3082 });
+ const got = lookupLabelFor(spec, spec.relationships[0]);
+ assert.deepStrictEqual(got.label, map);
+ assert.strictEqual(got.source, 'table');
+});
+
+test('ADO 6691205: an explicit lookup.displayName wins — a string or a map', () => {
+ const spec = specOf([project(), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId', displayName: 'Owning project' })]);
+ assert.deepStrictEqual(lookupLabelFor(spec, spec.relationships[0]), { label: 'Owning project', source: 'explicit' });
+ const map = { 1033: 'Owning project', 3082: 'Proyecto propietario' };
+ spec.relationships[0].lookup.displayName = map;
+ assert.deepStrictEqual(lookupLabelFor(spec, spec.relationships[0]), { label: map, source: 'explicit' });
+});
+
+test('ADO 6691205: a blank explicit label is treated as omitted, as every create site already does', () => {
+ // The runtime falls back with `x.displayName || x.schemaName`, so "" and undefined reach Dataverse
+ // identically; the default must not distinguish them either.
+ for (const blank of ['', ' ', null]) {
+ const spec = specOf([project(), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId', displayName: blank })]);
+ assert.strictEqual(lookupLabelFor(spec, spec.relationships[0]).label, 'Project', `blank ${JSON.stringify(blank)}`);
+ }
+});
+
+test('ADO 6691205: the declared parent is matched case-insensitively, like every other table reference', () => {
+ const spec = specOf([project(), task()], [oneToMany('CONTOSO_PROJECT', { schemaName: 'contoso_ProjectId' })]);
+ assert.strictEqual(lookupLabelFor(spec, spec.relationships[0]).label, 'Project');
+});
+
+test('ADO 6691205: a table the spec does not declare takes the label the environment reports', () => {
+ // `account` / `contact` / `systemuser` are never in entities[]; the build reads their DisplayName.
+ const spec = specOf([task()], [oneToMany('account', { schemaName: 'contoso_AccountId' })]);
+ assert.deepStrictEqual(lookupLabelFor(spec, spec.relationships[0], { liveReferencedLabel: 'Account' }), { label: 'Account', source: 'environment' });
+ assert.deepStrictEqual(lookupLabelFor(spec, spec.relationships[0], { liveReferencedLabel: ' ' }),
+ { label: 'Account', source: 'derived' }, 'a blank environment label is not a label');
+});
+
+test('ADO 6691205: with nothing else available the label is a humanized table name, never the logical name', () => {
+ const spec = specOf([task()], [oneToMany('account', { schemaName: 'contoso_AccountId' }), oneToMany('contoso_budgetline', { schemaName: 'contoso_LineId' })]);
+ assert.deepStrictEqual(lookupLabelFor(spec, spec.relationships[0]), { label: 'Account', source: 'derived' });
+ assert.deepStrictEqual(lookupLabelFor(spec, spec.relationships[1]), { label: 'Budgetline', source: 'derived' });
+});
+
+test('ADO 6691205: a declared parent with no displayName is humanized from its (cased) schema name', () => {
+ const spec = specOf([project({ schemaName: 'contoso_ProjectPhase', displayName: undefined }), task()], [oneToMany('contoso_projectphase', { schemaName: 'contoso_PhaseId' })]);
+ assert.deepStrictEqual(lookupLabelFor(spec, spec.relationships[0]), { label: 'Project Phase', source: 'derived' });
+});
+
+test('ADO 6691205: humanizeTableName strips the publisher prefix and title-cases the rest', () => {
+ assert.strictEqual(humanizeTableName('new_project'), 'Project');
+ assert.strictEqual(humanizeTableName('contoso_ProjectPhase'), 'Project Phase');
+ assert.strictEqual(humanizeTableName('contoso_work_item'), 'Work Item');
+ assert.strictEqual(humanizeTableName('account'), 'Account');
+ assert.strictEqual(humanizeTableName('contoso_SLA'), 'SLA');
+ assert.strictEqual(humanizeTableName(''), '');
+ assert.strictEqual(humanizeTableName(undefined), '');
+});
+
+test('ADO 6691205: lookupColumnsFor reports the effective label, not the lookup schema name', () => {
+ const spec = specOf([project(), task()], [
+ oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' }),
+ oneToMany('account', { schemaName: 'contoso_AccountId', displayName: 'Customer' }),
+ ]);
+ assert.deepStrictEqual(lookupColumnsFor(spec, 'contoso_task').map((l) => [l.logical, l.displayName]),
+ [['contoso_projectid', 'Project'], ['contoso_accountid', 'Customer']]);
+});
+
+test('ADO 6691205: lookupColumnsFor resolves a localized default in the spec\'s language', () => {
+ const spec = specOf([project({ displayName: { 1033: 'Project', 3082: 'Proyecto' }, pluralName: { 1033: 'Projects', 3082: 'Proyectos' } }), task()],
+ [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })], { languageCode: 3082 });
+ assert.strictEqual(lookupColumnsFor(spec, 'contoso_task')[0].displayName, 'Proyecto');
+});
+
+test('ADO 6691205: only EXACTLY what a build wrote on a COLUMN counts as its old default — the parent\'s lower-case logical name, and nothing else', () => {
+ const rel = oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' });
+ // What the vendored SDK actually sent as the COLUMN's label: the referenced table's LOWER-CASE logical name.
+ assert.strictEqual(isOldLookupColumnLabel(rel, 'contoso_project'), true);
+ // The lookup's own lower-case name is what the SDK leaves on a form FIELD it cannot resolve — never on a column,
+ // so a column carrying it was labelled by a person.
+ assert.strictEqual(isOldLookupColumnLabel(rel, 'contoso_projectid'), false);
+ // The capitalised schema name is how the spec spells the lookup, not a string any build wrote.
+ assert.strictEqual(isOldLookupColumnLabel(rel, 'contoso_ProjectId'), false);
+ // Not the same strings, so not the old default: a case variant, or space around it, is somebody's label.
+ assert.strictEqual(isOldLookupColumnLabel(rel, 'Contoso_Project'), false);
+ assert.strictEqual(isOldLookupColumnLabel(rel, 'CONTOSO_PROJECT'), false);
+ assert.strictEqual(isOldLookupColumnLabel(rel, ' contoso_project '), false);
+ // A correct label is never the old default — least of all when the table's name IS its label, like contact.
+ assert.strictEqual(isOldLookupColumnLabel(oneToMany('contact', { schemaName: 'contoso_ContactId' }), 'Contact'), false);
+ assert.strictEqual(isOldLookupColumnLabel(oneToMany('contact', { schemaName: 'contoso_ContactId' }), 'contact'), true);
+ // The names are lower-cased, as they are on their way to the SDK, wherever the spec capitalises them.
+ assert.strictEqual(isOldLookupColumnLabel(oneToMany('Contoso_Project', { schemaName: 'contoso_ProjectId' }), 'contoso_project'), true);
+ // A label a person wrote is never "the default".
+ assert.strictEqual(isOldLookupColumnLabel(rel, 'Project'), false);
+ assert.strictEqual(isOldLookupColumnLabel(rel, 'Owning project'), false);
+ assert.strictEqual(isOldLookupColumnLabel(rel, ''), false);
+ assert.strictEqual(isOldLookupColumnLabel(rel, undefined), false);
+ assert.strictEqual(isOldLookupColumnLabel(rel, { 1033: 'contoso_project' }), false, 'a map is never the single-language default');
+ assert.strictEqual(isOldLookupColumnLabel({ lookup: { schemaName: 'contoso_ProjectId' } }, ''), false, 'a relationship with no parent has no default to match');
+});
+
+test('ADO 6691205: a form FIELD\'s old default is the parent\'s lower-case logical name or the lookup\'s own — exactly', () => {
+ const rel = oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' });
+ // Inherited from the column…
+ assert.strictEqual(isOldLookupFieldLabel(rel, 'contoso_project'), true);
+ // …or, when the SDK cannot resolve the column at push, its control normalization defaults `label` to
+ // `fieldName`: the lookup's own LOWER-CASE logical name, not the schema name the spec spells with capitals.
+ assert.strictEqual(isOldLookupFieldLabel(rel, 'contoso_projectid'), true);
+ for (const typed of ['contoso_ProjectId', 'CONTOSO_PROJECTID', 'Contoso_Project', ' contoso_projectid ', 'Project', '', undefined, { 1033: 'contoso_projectid' }]) {
+ assert.strictEqual(isOldLookupFieldLabel(rel, typed), false, JSON.stringify(typed));
+ }
+ // Another relationship's names are somebody's label here.
+ const other = oneToMany('contoso_account', { schemaName: 'contoso_AccountId' });
+ assert.strictEqual(isOldLookupFieldLabel(other, 'contoso_project'), false);
+ assert.strictEqual(isOldLookupFieldLabel(other, 'contoso_projectid'), false);
+});
+
+// ── 2. the data-model phase ─────────────────────────────────────────────────────────────────────
+
+function engine({ existingTables = [], dataverse } = {}) {
+ const calls = [];
+ const sdk = {
+ createTable: async (o) => { calls.push(['createTable', o]); return { logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s`, metadataId: 't' }; },
+ createColumn: async (l, o) => { calls.push(['createColumn', o]); return { logicalName: o.schemaName.toLowerCase(), metadataId: 'c' }; },
+ updateColumn: async (l, c, o) => { calls.push(['updateColumn', l, c, o]); return {}; },
+ updateTable: async () => ({}),
+ createGlobalOptionSet: async () => ({ metadataId: 'g' }),
+ insertStatusValue: async () => 100000000,
+ createAlternateKey: async () => ({}),
+ createRelationship: async (o) => { calls.push(['createRelationship', o]); return { schemaName: o.schemaName, metadataId: 'r', lookupLogicalName: String(o.lookupSchemaName).toLowerCase() }; },
+ };
+ const provision = {
+ findTables: async (s) => (existingTables.includes(s.toLowerCase()) ? [{ logicalName: s.toLowerCase(), entitySetName: `${s.toLowerCase()}s` }] : []),
+ findColumns: async () => [],
+ fetchEntityMetadata: async (l) => { calls.push(['fetchEntityMetadata', l]); return { logicalName: l, displayName: l, entitySetName: `${l}s`, relationships: [] }; },
+ queryRecords: async () => [],
+ ...(dataverse ? { dataverse } : {}),
+ };
+ return { calls, sdk, provision };
+}
+
+// A raw metadata client: every path it is asked for is recorded, and `handler` answers it. `post` records each write
+// (the publish the label pass sends) and answers it with `publish` (204 by default).
+function metadataClient(handler, { publish = () => ({ status: 204, headers: {}, body: {} }) } = {}) {
+ const paths = [];
+ const posts = [];
+ return {
+ paths, posts,
+ get: async (p) => { paths.push(p); return handler(p); },
+ post: async (p, body) => { posts.push([p, body]); return publish(p, body); },
+ };
+}
+
+const label = (pairs, user) => ({
+ LocalizedLabels: pairs.map(([LanguageCode, Label]) => ({ Label, LanguageCode })),
+ UserLocalizedLabel: user ? { Label: user[1], LanguageCode: user[0] } : { Label: pairs[0][1], LanguageCode: pairs[0][0] },
+});
+
+async function build(spec, { existingTables, dataverse, warn, languageCode = 1033 } = {}) {
+ const m = engine({ existingTables, dataverse });
+ const warnings = [];
+ const events = [];
+ const runner = makeRunner({ emit: (e) => events.push(e), total: 30 });
+ const dm = await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner, spec, apply: true, preResolvedLanguageCode: languageCode, warn: warn || ((w) => warnings.push(w)) });
+ return { ...m, dm, warnings, events, created: m.calls.filter((c) => c[0] === 'createRelationship').map((c) => c[1]) };
+}
+
+test('ADO 6691205: createRelationship carries the declared parent\'s display name when the spec omits one', async () => {
+ const spec = specOf([project(), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })]);
+ const { created } = await build(spec);
+ assert.strictEqual(created.length, 1);
+ assert.strictEqual(created[0].lookupDisplayName, 'Project',
+ 'the SDK falls back to the LOGICAL name when this is undefined, which is the reported bug');
+});
+
+test('ADO 6691205: a localized parent name reaches the SDK as the full LCID map', async () => {
+ const map = { 1033: 'Project', 3082: 'Proyecto' };
+ const spec = specOf([project({ displayName: map, pluralName: { 1033: 'Projects', 3082: 'Proyectos' } }), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })]);
+ const { created } = await build(spec, { languageCode: 1033, existingTables: ['contoso_project', 'contoso_task'] });
+ assert.deepStrictEqual(created[0].lookupDisplayName, map);
+});
+
+test('ADO 6691205: an explicit lookup.displayName is sent unchanged', async () => {
+ const spec = specOf([project(), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId', displayName: 'Owning project' })]);
+ const { created } = await build(spec);
+ assert.strictEqual(created[0].lookupDisplayName, 'Owning project');
+});
+
+test('ADO 6691205: a parent the spec does not declare is labelled from the environment, in the authoring language', async () => {
+ const spec = specOf([task()], [oneToMany('account', { schemaName: 'contoso_AccountId' })]);
+ const dataverse = metadataClient((p) => {
+ if (p === "/EntityDefinitions(LogicalName='account')?$select=LogicalName,DisplayName") {
+ // The caller's UI language (French) differs from the build's authoring language (English): the
+ // label must come from the language the build stamps, not from whoever happens to be signed in.
+ return { status: 200, body: { LogicalName: 'account', DisplayName: label([[1033, 'Account'], [1036, 'Compte']], [1036, 'Compte']) } };
+ }
+ return { status: 200, body: { value: [] } };
+ });
+ const { created, warnings } = await build(spec, { existingTables: ['contoso_task'], dataverse, languageCode: 1033 });
+ assert.strictEqual(created[0].lookupDisplayName, 'Account');
+ assert.deepStrictEqual(warnings, []);
+});
+
+test('ADO 6691205: the environment is asked for a parent\'s label once, however many lookups point at it', async () => {
+ const spec = specOf([task()], [
+ oneToMany('account', { schemaName: 'contoso_AccountId' }),
+ { type: 'OneToMany', referenced: 'account', referencing: 'contoso_task', schemaName: 'contoso_account_task_second', lookup: { schemaName: 'contoso_SecondAccountId' } },
+ ]);
+ const dataverse = metadataClient((p) => (p.includes('$select=LogicalName,DisplayName')
+ ? { status: 200, body: { LogicalName: 'account', DisplayName: label([[1033, 'Account']]) } }
+ : { status: 200, body: { value: [] } }));
+ const { created } = await build(spec, { existingTables: ['contoso_task'], dataverse });
+ assert.deepStrictEqual(created.map((c) => c.lookupDisplayName), ['Account', 'Account']);
+ assert.strictEqual(dataverse.paths.filter((p) => p.includes('$select=LogicalName,DisplayName')).length, 1);
+});
+
+test('ADO 6691205: a declared parent needs no environment read at all', async () => {
+ const spec = specOf([project(), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })]);
+ const dataverse = metadataClient(() => ({ status: 200, body: { value: [] } }));
+ await build(spec, { existingTables: ['contoso_project', 'contoso_task'], dataverse });
+ assert.deepStrictEqual(dataverse.paths.filter((p) => p.includes('DisplayName')), [],
+ 'a label-bearing read before a create is the hazard documented on relationshipExists; it is not paid for a table the spec already names');
+});
+
+test('ADO 6691205: an unreadable parent label falls back to a humanized name and says so', async () => {
+ const spec = specOf([task()], [oneToMany('systemuser', { schemaName: 'contoso_OwnerId' })]);
+ const dataverse = metadataClient((p) => (p.includes('$select=LogicalName,DisplayName')
+ ? { status: 503, body: {} }
+ : { status: 200, body: { value: [] } }));
+ const { created, warnings } = await build(spec, { existingTables: ['contoso_task'], dataverse });
+ assert.strictEqual(created[0].lookupDisplayName, 'Systemuser');
+ assert.ok(warnings.some((w) => /systemuser/.test(w) && /503/.test(w) && /lookup\.displayName/.test(w)), JSON.stringify(warnings));
+});
+
+test('ADO 6691205: with no raw client (a test double) the humanized fallback applies without a warning', async () => {
+ const spec = specOf([task()], [oneToMany('account', { schemaName: 'contoso_AccountId' })]);
+ const { created, warnings } = await build(spec, { existingTables: ['contoso_task'] });
+ assert.strictEqual(created[0].lookupDisplayName, 'Account');
+ assert.deepStrictEqual(warnings, []);
+});
+
+test('ADO 6691205: the parent label is read after the existence probe and immediately before the plain-label create', async () => {
+ // The documented hazard (relationshipExists): a label-bearing metadata read makes Dataverse keep
+ // only the base-language label of the create that FOLLOWS it. The label read here belongs to a
+ // plain single-language create, so nothing can be stripped — but it must not drift away from it
+ // and into the middle of a localized one.
+ const spec = specOf([task()], [oneToMany('account', { schemaName: 'contoso_AccountId' })]);
+ const order = [];
+ const dataverse = metadataClient((p) => {
+ order.push(p.includes('$select=LogicalName,DisplayName') ? 'label-read' : 'probe');
+ return p.includes('$select=LogicalName,DisplayName')
+ ? { status: 200, body: { LogicalName: 'account', DisplayName: label([[1033, 'Account']]) } }
+ : { status: 200, body: { value: [] } };
+ });
+ const m = engine({ existingTables: ['contoso_task'], dataverse });
+ const origCreate = m.sdk.createRelationship;
+ m.sdk.createRelationship = async (o) => { order.push('create'); return origCreate(o); };
+ await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner: makeRunner({ emit: () => {}, total: 20 }), spec, apply: true, preResolvedLanguageCode: 1033 });
+ const first = (what) => order.indexOf(what);
+ assert.ok(first('probe') >= 0 && first('probe') < first('label-read'), JSON.stringify(order));
+ assert.strictEqual(order[order.indexOf('create') - 1], 'label-read', JSON.stringify(order));
+});
+
+test('ADO 6691205: an inherited LOCALIZED label keeps the narrow-probe rule — no broad metadata read before the create', async () => {
+ // `hasLocalizedLabels` used to read only the AUTHORED lookup label. With the default, a localized
+ // parent name makes the lookup label localized too, so the poisoning broad-read fallback must stay
+ // off exactly as it is for an explicitly localized one.
+ const map = { 1033: 'Project', 3082: 'Proyecto' };
+ const spec = specOf([project({ displayName: map, pluralName: { 1033: 'Projects', 3082: 'Proyectos' } }), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })]);
+ // Only the relationship probe is inconclusive; the tables still answer, so the build reaches it.
+ const inconclusive = metadataClient((p) => {
+ if (/OneToManyRelationships/.test(p)) return { status: 503, headers: {}, body: {} };
+ if (/\?\$select=LogicalName,EntitySetName/.test(p)) return { status: 200, headers: {}, body: { LogicalName: p.match(/LogicalName='([^']+)'/)[1], EntitySetName: 'x' } };
+ return { status: 200, headers: {}, body: { value: [] } };
+ });
+ const m = engine({ existingTables: ['contoso_project', 'contoso_task'], dataverse: inconclusive });
+ const broad = [];
+ m.provision.fetchEntityMetadata = async (l) => { broad.push(l); return { logicalName: l, entitySetName: `${l}s`, relationships: [] }; };
+ await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner: makeRunner({ emit: () => {}, total: 20 }), spec, apply: true, preResolvedLanguageCode: 1033 });
+ assert.deepStrictEqual(broad, [], 'the broad read is what strips every non-base language');
+ assert.ok(m.calls.some((c) => c[0] === 'createRelationship'));
+});
+
+// ── 2b. a parent the spec declares WITHOUT a displayName ──────────────────────────────────────────
+//
+// `entities[]` lists the tables the app uses, including ones that already exist: { "schemaName": "incident",
+// "existing": true } is how a spec reuses the stock Case table, and such an entry has no displayName because
+// nothing here creates it. Its name is the environment's ("Case"), exactly as for a table the spec never lists.
+
+const incident = (extra) => ({ schemaName: 'incident', existing: true, primaryAttribute: { schemaName: 'title' }, columns: [], ...extra });
+const DISPLAY_NAME_READ = /\(LogicalName='[^']+'\)\?\$select=LogicalName,DisplayName$/;
+
+// An environment whose tables answer the keyed DisplayName read with `labels` ({ logical: [[lcid, text], …] }).
+const labelledTables = (labels) => metadataClient((p) => {
+ const m = /\(LogicalName='([^']+)'\)\?\$select=LogicalName,DisplayName$/.exec(p);
+ return m && labels[m[1]]
+ ? { status: 200, body: { LogicalName: m[1], DisplayName: label(labels[m[1]]) } }
+ : { status: 200, body: { value: [] } };
+});
+const displayNameReads = (dataverse) => dataverse.paths.filter((p) => DISPLAY_NAME_READ.test(p));
+
+test('ADO 6691205: a parent declared `existing: true` with no displayName is labelled with the ENVIRONMENT\'s name — "Case", "User" — not a humanized one', async () => {
+ const spec = specOf([task(), incident(), { schemaName: 'systemuser', existing: true, primaryAttribute: { schemaName: 'fullname' }, columns: [] }], [
+ oneToMany('incident', { schemaName: 'contoso_CaseId' }),
+ oneToMany('systemuser', { schemaName: 'contoso_OwnerId' }),
+ ]);
+ const dataverse = labelledTables({ incident: [[1033, 'Case'], [1036, 'Requête']], systemuser: [[1033, 'User'], [1036, 'Utilisateur']] });
+ const { created, warnings } = await build(spec, { existingTables: ['contoso_task', 'incident', 'systemuser'], dataverse });
+ assert.deepStrictEqual(created.map((c) => c.lookupDisplayName), ['Case', 'User'], 'the label the maker portal gives, in the build\'s language');
+ assert.strictEqual(displayNameReads(dataverse).length, 2, 'one read per parent');
+ assert.deepStrictEqual(warnings, []);
+});
+
+test('ADO 6691205: a declared `existing: true` CUSTOM table with no displayName is read the same way', async () => {
+ const spec = specOf([project({ displayName: undefined, existing: true }), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })]);
+ const dataverse = labelledTables({ contoso_project: [[1033, 'Project Portfolio']] });
+ const { created } = await build(spec, { existingTables: ['contoso_project', 'contoso_task'], dataverse });
+ assert.strictEqual(created[0].lookupDisplayName, 'Project Portfolio');
+});
+
+test('ADO 6691205: a declared parent with no displayName that the data-model phase finds ALREADY THERE is read, flagged or not', async () => {
+ const spec = specOf([project({ displayName: undefined }), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })]);
+ const dataverse = labelledTables({ contoso_project: [[1033, 'Project Portfolio']] });
+ const { created } = await build(spec, { existingTables: ['contoso_project', 'contoso_task'], dataverse });
+ assert.strictEqual(created[0].lookupDisplayName, 'Project Portfolio');
+});
+
+test('ADO 6691205: a declared parent with no displayName that THIS build creates is not read — it is labelled with its schema name, so the humanized name is the better one', async () => {
+ const spec = specOf([project({ displayName: undefined }), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })]);
+ const dataverse = labelledTables({ contoso_project: [[1033, 'contoso_Project']] });
+ const { created, calls } = await build(spec, { existingTables: ['contoso_task'], dataverse });
+ assert.ok(calls.some((c) => c[0] === 'createTable' && c[1].schemaName === 'contoso_Project'));
+ assert.strictEqual(created[0].lookupDisplayName, 'Project');
+ assert.deepStrictEqual(displayNameReads(dataverse), []);
+});
+
+test('ADO 6691205: a flagged parent the build had to create is not named by the identifier it was created under', async () => {
+ // `existing` records ownership, not presence. Read back, the table this build just created reads
+ // "contoso_Project" — its schema name — which is no more a name than the logical one the bug put there.
+ const spec = specOf([project({ displayName: undefined, existing: true }), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })]);
+ const dataverse = labelledTables({ contoso_project: [[1033, 'contoso_Project']] });
+ const { created } = await build(spec, { existingTables: ['contoso_task'], dataverse });
+ assert.strictEqual(created[0].lookupDisplayName, 'Project');
+});
+
+test('ADO 6691205: a displayName the spec sets on a declared parent wins over the environment, flagged or not — and costs no read', async () => {
+ const spec = specOf([incident({ displayName: 'Support case' }), task()], [oneToMany('incident', { schemaName: 'contoso_CaseId' })]);
+ const dataverse = labelledTables({ incident: [[1033, 'Case']] });
+ const { created } = await build(spec, { existingTables: ['contoso_task', 'incident'], dataverse });
+ assert.strictEqual(created[0].lookupDisplayName, 'Support case');
+ assert.deepStrictEqual(displayNameReads(dataverse), []);
+});
+
+test('ADO 6691205: lookupLabelFor takes the environment\'s name for a declared parent that sets none, and ignores one that is only its identifier', () => {
+ const spec = specOf([incident(), task()], [oneToMany('incident', { schemaName: 'contoso_CaseId' })]);
+ const rel = spec.relationships[0];
+ assert.deepStrictEqual(lookupLabelFor(spec, rel, { liveReferencedLabel: 'Case' }), { label: 'Case', source: 'environment' });
+ assert.deepStrictEqual(lookupLabelFor(spec, rel), { label: 'Incident', source: 'derived' }, 'offline surfaces still have only the humanized name');
+ for (const identifier of ['incident', ' ']) {
+ assert.strictEqual(lookupLabelFor(spec, rel, { liveReferencedLabel: identifier }).source, 'derived', JSON.stringify(identifier));
+ }
+ const cased = specOf([project({ displayName: undefined }), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })]);
+ assert.strictEqual(lookupLabelFor(cased, cased.relationships[0], { liveReferencedLabel: 'contoso_Project' }).source, 'derived', 'the schema name as written');
+ assert.strictEqual(lookupLabelFor(cased, cased.relationships[0], { liveReferencedLabel: 'contoso_project' }).source, 'derived', 'the logical name');
+ // A name that merely looks like the table's, in another case, is a name: "Contact" is the display name of `contact`.
+ const contact = specOf([task()], [oneToMany('contact', { schemaName: 'contoso_ContactId' })]);
+ assert.deepStrictEqual(lookupLabelFor(contact, contact.relationships[0], { liveReferencedLabel: 'Contact' }), { label: 'Contact', source: 'environment' });
+ // A displayName the spec sets is not overridden by anything the environment says.
+ const named = specOf([incident({ displayName: 'Support case' }), task()], [oneToMany('incident', { schemaName: 'contoso_CaseId' })]);
+ assert.deepStrictEqual(lookupLabelFor(named, named.relationships[0], { liveReferencedLabel: 'Case' }), { label: 'Support case', source: 'table' });
+});
+
+test('ADO 6691205: lookupParentNeedsEnvironment — who must ask the environment for a parent\'s name', () => {
+ const rel = (referenced) => oneToMany(referenced, { schemaName: 'contoso_ParentId' });
+ const spec = specOf([
+ project({ displayName: undefined }),
+ { ...project({ displayName: undefined }), schemaName: 'contoso_Flagged', existing: true },
+ { ...project({ displayName: 'Named' }), schemaName: 'contoso_NamedFlagged', existing: true },
+ task(),
+ ], []);
+ assert.strictEqual(lookupParentNeedsEnvironment(spec, rel('account')), true, 'not declared');
+ assert.strictEqual(lookupParentNeedsEnvironment(spec, rel('contoso_flagged')), true, 'declared, no displayName, `existing: true`');
+ assert.strictEqual(lookupParentNeedsEnvironment(spec, rel('contoso_namedflagged')), false, 'the spec names it');
+ assert.strictEqual(lookupParentNeedsEnvironment(spec, rel('contoso_project')), false, 'declared, no displayName, not known to be there: the build creates it');
+ assert.strictEqual(lookupParentNeedsEnvironment(spec, rel('contoso_project'), { reused: new Set(['contoso_project']) }), true, '…unless the data-model phase found it already there');
+ assert.strictEqual(lookupParentNeedsEnvironment(spec, rel('CONTOSO_FLAGGED')), true, 'matched case-insensitively');
+});
+
+// ── 2c. the order relationships are created in ──────────────────────────────────────────────────────
+//
+// A parent-label read carries labels, so it is the read the localization notes warn about: ahead of a create it can
+// leave Dataverse with only the base-language label of a multi-language one. Each read sits right before its own
+// plain create — but a LOCALIZED lookup created later in the same loop would still have a label-bearing read earlier
+// in the phase. So the relationships with a localized label are created first.
+
+// Builds `spec` against tables that exist, noting every `create:<lookup>` and every parent-label `read:<table>` in
+// the one order they happen.
+async function traceRelationships(spec, existing = ['contoso_task', 'contoso_project', 'contoso_other']) {
+ const order = [];
+ const dataverse = metadataClient((p) => {
+ const probe = /\(LogicalName='([^']+)'\)\?\$select=LogicalName,EntitySetName$/.exec(p);
+ if (probe) return existing.includes(probe[1]) ? { status: 200, body: { LogicalName: probe[1], EntitySetName: `${probe[1]}s` } } : { status: 404, body: {} };
+ const read = /\(LogicalName='([^']+)'\)\?\$select=LogicalName,DisplayName$/.exec(p);
+ if (read) {
+ order.push(`read:${read[1]}`);
+ return { status: 200, body: { LogicalName: read[1], DisplayName: label([[1033, read[1].charAt(0).toUpperCase() + read[1].slice(1)]]) } };
+ }
+ return { status: 200, body: { value: [] } };
+ });
+ const m = engine({ existingTables: existing, dataverse });
+ const create = m.sdk.createRelationship;
+ m.sdk.createRelationship = async (o) => { order.push(`create:${o.lookupSchemaName}`); return create(o); };
+ await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner: makeRunner({ emit: () => {}, total: 40 }), spec, apply: true, preResolvedLanguageCode: 1033 });
+ return order;
+}
+
+const NAMES = { 1033: 'Project', 3082: 'Proyecto' };
+// Two lookups whose label is localized — one inherited from a localized parent table, one authored — and two plain
+// ones, of which both need the environment's name for their parent.
+const mixedRelationships = () => ({
+ plainAccount: oneToMany('account', { schemaName: 'contoso_AccountId' }),
+ plainUser: oneToMany('systemuser', { schemaName: 'contoso_OwnerId' }),
+ inherited: oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' }),
+ authored: oneToMany('contoso_other', { schemaName: 'contoso_OtherId', displayName: { 1033: 'Other', 3082: 'Otro' } }),
+});
+const mixedSpec = (order) => {
+ const r = mixedRelationships();
+ return specOf([project({ displayName: NAMES, pluralName: { 1033: 'Projects', 3082: 'Proyectos' } }), { ...project(), schemaName: 'contoso_Other', displayName: 'Other' }, task()], order.map((k) => r[k]));
+};
+
+function* permutations(items) {
+ if (items.length <= 1) { yield items; return; }
+ for (let i = 0; i < items.length; i += 1) {
+ for (const rest of permutations([...items.slice(0, i), ...items.slice(i + 1)])) yield [items[i], ...rest];
+ }
+}
+
+test('ADO 6691205: relationships with a LOCALIZED lookup label are created before any read of a parent\'s label', async () => {
+ // Declared plain-first, the order that used to put a label-bearing read ahead of a multi-language create:
+ // read the account label, create its lookup, then create the lookup labelled in two languages.
+ const order = await traceRelationships(mixedSpec(['plainAccount', 'inherited', 'plainUser', 'authored']));
+ assert.deepStrictEqual(order, [
+ 'create:contoso_ProjectId', 'create:contoso_OtherId', // the localized ones, in declared order
+ 'read:account', 'create:contoso_AccountId', 'read:systemuser', 'create:contoso_OwnerId', // then the plain ones, each read beside its own create
+ ]);
+});
+
+test('ADO 6691205: whatever order the spec declares them in, no localized create follows a read of a parent\'s label', async () => {
+ const keys = ['plainAccount', 'inherited', 'plainUser', 'authored'];
+ const localizedLookups = new Set(['create:contoso_ProjectId', 'create:contoso_OtherId']);
+ let seen = 0;
+ for (const declared of permutations(keys)) {
+ const order = await traceRelationships(mixedSpec(declared));
+ const firstRead = order.findIndex((step) => step.startsWith('read:'));
+ assert.ok(firstRead >= 0, `a parent label was read (${declared.join(', ')})`);
+ assert.ok(order.slice(firstRead).every((step) => !localizedLookups.has(step)), `${declared.join(' > ')}: ${JSON.stringify(order)}`);
+ assert.strictEqual(order.filter((step) => step.startsWith('create:')).length, 4, 'every relationship is still created');
+ seen += 1;
+ }
+ assert.strictEqual(seen, 24);
+});
+
+test('ADO 6691205: each group keeps the spec\'s own order, and N:N relationships — which carry no label — follow the localized ones', async () => {
+ const r = mixedRelationships();
+ const spec = specOf([project({ displayName: NAMES, pluralName: { 1033: 'Projects', 3082: 'Proyectos' } }), { ...project(), schemaName: 'contoso_Other', displayName: 'Other' }, task()], [
+ r.plainUser, { type: 'ManyToMany', entity1: 'contoso_project', entity2: 'contoso_task' }, r.authored, r.plainAccount, r.inherited,
+ ]);
+ assert.deepStrictEqual(relationshipsInCreateOrder(spec).map((x) => x.lookup ? x.lookup.schemaName : x.type),
+ ['contoso_OtherId', 'contoso_ProjectId', 'contoso_OwnerId', 'ManyToMany', 'contoso_AccountId']);
+});
+
+test('ADO 6691205: the plan lists the relationships in the order the build creates them', () => {
+ const spec = mixedSpec(['plainAccount', 'inherited', 'plainUser', 'authored']);
+ const planned = planFor(spec, { phases: ['data-model'] });
+ assert.deepStrictEqual(planned.filter((i) => /^relationship /.test(i.label)).map((i) => i.label), [
+ 'relationship 1:N contoso_project->contoso_task',
+ 'relationship 1:N contoso_other->contoso_task',
+ 'relationship 1:N account->contoso_task',
+ 'relationship 1:N systemuser->contoso_task',
+ ]);
+});
+
+// ── 3. the REAL vendored bundle ─────────────────────────────────────────────────────────────────
+
+const dirs = [];
+test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+// A real SDK over a stub transport. `routes` answers reads by URL; every write is captured.
+async function realSdk(routes) {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'lookup-label-'));
+ dirs.push(dir);
+ const writes = [];
+ const reads = [];
+ const created = { 'odata-entityid': 'https://contoso.crm.dynamics.com/api/data/v9.2/RelationshipDefinitions(11111111-1111-1111-1111-111111111111)' };
+ const httpClient = {
+ get: async (url) => {
+ const u = decodeURIComponent(url);
+ reads.push(u);
+ for (const [re, answer] of routes) if (re.test(u)) return typeof answer === 'function' ? answer(u) : answer;
+ return { status: 200, headers: {}, body: { value: [] } };
+ },
+ post: async (url, body) => { writes.push({ verb: 'POST', url: decodeURIComponent(url), body }); return { status: 204, headers: created, body: {} }; },
+ put: async (url, body, opts) => { writes.push({ verb: 'PUT', url: decodeURIComponent(url), body, headers: opts && opts.headers }); return { 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 };
+}
+
+const labelsOf = (write) => (write.body.Lookup.DisplayName.LocalizedLabels || []).map((l) => [l.LanguageCode, l.Label]);
+const exists = (logical) => [new RegExp(`EntityDefinitions\\(LogicalName='${logical}'\\)\\?\\$select=LogicalName,EntitySetName`), { status: 200, headers: {}, body: { LogicalName: logical, EntitySetName: `${logical}s` } }];
+
+test('REAL BUNDLE (ADO 6691205): the createRelationship body carries the parent\'s label at the authoring LCID', async () => {
+ const { sdk, writes } = await realSdk([exists('contoso_project'), exists('contoso_task')]);
+ const spec = specOf([project(), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })]);
+ await provisionDataModel({ sdk, provision: sdk, runner: makeRunner({ emit: () => {}, total: 20 }), spec, apply: true, preResolvedLanguageCode: 1031 });
+ const post = writes.find((w) => /\/RelationshipDefinitions$/.test(w.url));
+ assert.ok(post, JSON.stringify(writes.map((w) => w.url)));
+ assert.deepStrictEqual(labelsOf(post), [[1031, 'Project']]);
+});
+
+test('REAL BUNDLE (ADO 6691205): a localized parent name serializes as one LocalizedLabel per language', async () => {
+ const { sdk, writes } = await realSdk([exists('contoso_project'), exists('contoso_task')]);
+ const spec = specOf([project({ displayName: { 1033: 'Project', 3082: 'Proyecto' }, pluralName: { 1033: 'Projects', 3082: 'Proyectos' } }), task()],
+ [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })]);
+ await provisionDataModel({ sdk, provision: sdk, runner: makeRunner({ emit: () => {}, total: 20 }), spec, apply: true, preResolvedLanguageCode: 1033 });
+ const post = writes.find((w) => /\/RelationshipDefinitions$/.test(w.url));
+ assert.deepStrictEqual(labelsOf(post), [[1033, 'Project'], [3082, 'Proyecto']]);
+});
+
+test('REAL BUNDLE (ADO 6691205): a system parent is labelled from the keyed DisplayName read the SDK client sends', async () => {
+ // Drives the REAL client (`sdk.dataverse`) rather than an injected stub, so the request path and the
+ // response parsing are the ones a live build uses.
+ const { sdk, writes, reads } = await realSdk([
+ exists('contoso_task'),
+ [/EntityDefinitions\(LogicalName='account'\)\?\$select=LogicalName,DisplayName/, { status: 200, headers: {}, body: { LogicalName: 'account', DisplayName: label([[1033, 'Account'], [1036, 'Compte']], [1036, 'Compte']) } }],
+ ]);
+ const spec = specOf([task()], [oneToMany('account', { schemaName: 'contoso_AccountId' })]);
+ await provisionDataModel({ sdk, provision: sdk, runner: makeRunner({ emit: () => {}, total: 20 }), spec, apply: true, preResolvedLanguageCode: 1033 });
+ assert.ok(reads.some((r) => /EntityDefinitions\(LogicalName='account'\)\?\$select=LogicalName,DisplayName$/.test(r)), JSON.stringify(reads));
+ const post = writes.find((w) => /\/RelationshipDefinitions$/.test(w.url));
+ assert.deepStrictEqual(labelsOf(post), [[1033, 'Account']]);
+});
+
+test('REAL BUNDLE (ADO 6691205): the old default really was the referenced table\'s logical name', async () => {
+ // Pins the premise of the whole fix and of the repair rule's "buggy default": with no label the
+ // bundle sends the referenced entity's LOGICAL name. If a re-vendor changes that, the repair rule
+ // must be revisited, so this fails loudly instead of the rule silently going stale.
+ const { sdk, writes } = await realSdk([]);
+ await sdk.createRelationship({ type: 'OneToMany', schemaName: 'contoso_project_contoso_task', referencedEntity: 'contoso_project', referencingEntity: 'contoso_task', lookupSchemaName: 'contoso_ProjectId', languageCode: 1033 });
+ assert.deepStrictEqual(labelsOf(writes.find((w) => /\/RelationshipDefinitions$/.test(w.url))), [[1033, 'contoso_project']]);
+});
+
+test('REAL BUNDLE (ADO 6691205): a fresh build\'s auto-layout form labels the lookup cell with the parent\'s name', async () => {
+ // The symptom as a maker sees it, end to end. The environment is stateful: it keeps the DisplayName the
+ // createRelationship POST carried and answers the SDK's push-time attribute read with it, which is how
+ // the SDK labels a cell the compiled form leaves unlabelled. Before the fix that label was "contoso_project".
+ const { sdk, writes } = await realSdk([
+ exists('contoso_project'), exists('contoso_task'),
+ [/EntityDefinitions\(LogicalName='contoso_task'\)\/Attributes\?/, (u) => {
+ const created = writes.find((w) => /\/RelationshipDefinitions$/.test(w.url));
+ const asked = [...u.matchAll(/LogicalName eq '([^']+)'/g)].map((m) => m[1]);
+ const attributes = [
+ { LogicalName: 'contoso_name', AttributeType: 'String', DisplayName: label([[1033, 'Name']]) },
+ { LogicalName: 'contoso_projectid', AttributeType: 'Lookup', DisplayName: label(created.body.Lookup.DisplayName.LocalizedLabels.map((l) => [l.LanguageCode, l.Label])) },
+ ];
+ return { status: 200, headers: {}, body: { value: attributes.filter((a) => !asked.length || asked.includes(a.LogicalName)) } };
+ }],
+ ]);
+ const spec = specOf([project(), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })], { forms: [{ entity: 'contoso_task', name: 'Task', layout: 'auto' }] });
+ await provisionDataModel({ sdk, provision: sdk, runner: makeRunner({ emit: () => {}, total: 20 }), spec, apply: true, preResolvedLanguageCode: 1033 });
+
+ const intent = compileFormIntent(spec, spec.forms[0], {});
+ const lookupCell = intent.tabs[0].columns[0].sections[0].rows.flatMap((r) => r.cells).find((c) => c.control && c.control.fieldName === 'contoso_projectid');
+ assert.ok(lookupCell, 'the auto layout places the parent lookup');
+ assert.strictEqual(lookupCell.control.label, undefined, 'the cell carries no label of its own, so the column\'s decides');
+
+ const art = await sdk.createArtifact('form', { name: intent.name, entityLogicalName: intent.entityLogicalName, formType: intent.formType, status: intent.status });
+ for (const tab of intent.tabs) await sdk.addElement('form', art.id, '/tabs', tab);
+ await sdk.removeElement('form', art.id, '/tabs/0');
+ await sdk.pushArtifact('form', art.id);
+ const xml = String(writes.map((w) => w.body && w.body.formxml).find(Boolean));
+ const cell = xml.split('<cell').find((c) => /datafieldname="contoso_projectid"/.test(c));
+ assert.ok(cell, 'the lookup cell is in the pushed form');
+ assert.match(cell, /<label description="Project" languagecode="1033" \/>/);
+ assert.doesNotMatch(cell, /description="contoso_project"/);
+});
+
+// ── 4. a REBUILD repairs the old default — and only the old default ───────────────────────────────
+
+const REL = 'contoso_project_contoso_task';
+// The collection read the repair makes, once per child table:
+// GET …/EntityDefinitions(LogicalName='contoso_task')/Attributes?$select=LogicalName,DisplayName&$filter=LogicalName eq '…' or …
+const COLUMN_LABEL = /\/Attributes\?\$select=LogicalName,DisplayName&\$filter=/;
+
+// An environment in which the relationship (and so the lookup column) already exists, with the lookup
+// column labelled `labels` ([[lcid, text], ...]) — or answering `columnStatus` instead. `columns` adds the
+// labels of further columns of the child table ({ logical: [[lcid, text], ...] }) and `relationships` the
+// rows of further existing relationships; the label read answers for whichever of them it is asked about.
+function rebuildEnv({ labels, columnStatus = 200, parentLabel, parentLabels = {}, relationship = REL, referenced = 'contoso_project', lookup = 'contoso_projectid', columns = {}, relationships, publish } = {}) {
+ const known = { ...(labels ? { [lookup]: labels } : {}), ...columns };
+ const parents = { ...(parentLabel ? { [referenced]: parentLabel } : {}), ...parentLabels };
+ return metadataClient((p) => {
+ if (/OneToManyRelationships/.test(p)) {
+ return { status: 200, headers: {}, body: { value: relationships || [{ SchemaName: relationship, ReferencingEntity: 'contoso_task', ReferencingAttribute: lookup }] } };
+ }
+ if (/\?\$select=LogicalName,EntitySetName/.test(p)) return { status: 200, headers: {}, body: { LogicalName: p.match(/LogicalName='([^']+)'/)[1], EntitySetName: 'x' } };
+ if (COLUMN_LABEL.test(p)) {
+ if (columnStatus !== 200) return { status: columnStatus, headers: {}, body: {} };
+ const asked = [...p.matchAll(/LogicalName eq '([^']+)'/g)].map((m) => m[1]);
+ return { status: 200, headers: {}, body: { value: asked.filter((name) => known[name]).map((name) => ({ LogicalName: name, DisplayName: label(known[name]) })) } };
+ }
+ const parent = /LogicalName='([^']+)'\)\?\$select=LogicalName,DisplayName$/.exec(p);
+ if (parent && parents[parent[1]]) {
+ return { status: 200, headers: {}, body: { LogicalName: parent[1], DisplayName: label(parents[parent[1]]) } };
+ }
+ return { status: 200, headers: {}, body: { value: [] } };
+ }, publish ? { publish } : {});
+}
+
+async function rebuild(spec, env, extra = {}, existingTables = ['contoso_project', 'contoso_task']) {
+ const m = engine({ existingTables, dataverse: env });
+ const events = [];
+ const warnings = [];
+ const dm = await provisionDataModel({
+ sdk: m.sdk, provision: m.provision, runner: makeRunner({ emit: (e) => events.push(e), total: 40 }), spec, apply: true,
+ preResolvedLanguageCode: 1033, reconcileLookupLabels: true, warn: (w) => warnings.push(w), ...extra,
+ });
+ const updates = m.calls.filter((c) => c[0] === 'updateColumn');
+ const labelEvents = events.filter((e) => /^lookup label /.test(e.label) && e.status !== 'start');
+ return { ...m, dm, events, warnings, updates, labelEvents };
+}
+
+const omitted = () => specOf([project(), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })]);
+
+test('ADO 6691205 rebuild: a lookup labelled with the SDK\'s old default (the parent\'s logical name) is relabelled', async () => {
+ const r = await rebuild(omitted(), rebuildEnv({ labels: [[1033, 'contoso_project']] }));
+ assert.deepStrictEqual(r.updates, [['updateColumn', 'contoso_task', 'contoso_projectid', { displayName: 'Project', languageCode: 1033 }]]);
+ assert.strictEqual(r.labelEvents.length, 1);
+ assert.strictEqual(r.labelEvents[0].status, 'ok');
+ assert.match(r.labelEvents[0].label, /lookup label contoso_task\.contoso_ProjectId: "contoso_project" -> "Project"/);
+ assert.deepStrictEqual(r.dm.lookupLabels['contoso_task|contoso_projectid'], { label: 'Project' });
+});
+
+test('ADO 6691205 rebuild: the lookup\'s own lower-case logical name is NOT a column\'s old default — only a form field was ever left with it', async () => {
+ // The SDK's fallback for a form FIELD it cannot resolve at push is the field's own lower-case logical name; the label
+ // it gives the COLUMN is the referenced table's. So a column carrying `contoso_projectid` was labelled by a person
+ // (or a tool that is not this build) and a rebuild leaves it alone, like any other label that is not the old default.
+ for (const typed of ['contoso_projectid', 'contoso_ProjectId', 'CONTOSO_PROJECTID']) {
+ const r = await rebuild(omitted(), rebuildEnv({ labels: [[1033, typed]] }));
+ assert.deepStrictEqual(r.updates, [], `${typed}: not what any build wrote on a column`);
+ assert.match(r.labelEvents[0].label, new RegExp(`labelled "${typed}" — left as it is`));
+ assert.deepStrictEqual(r.dm.lookupLabels['contoso_task|contoso_projectid'], { label: typed }, 'the form phase then follows the column');
+ }
+});
+
+test('ADO 6691205 rebuild: a label a maker chose is left alone', async () => {
+ const r = await rebuild(omitted(), rebuildEnv({ labels: [[1033, 'Parent project']] }));
+ assert.deepStrictEqual(r.updates, []);
+ assert.strictEqual(r.labelEvents.length, 1);
+ assert.strictEqual(r.labelEvents[0].status, 'skip');
+ assert.match(r.labelEvents[0].label, /labelled "Parent project" — left as it is/);
+ // The forms phase aligns an old cell label with what the column says NOW.
+ assert.deepStrictEqual(r.dm.lookupLabels['contoso_task|contoso_projectid'], { label: 'Parent project' });
+});
+
+test('ADO 6691205 rebuild: a label that is not the old default is left alone, even when it equals the new default', async () => {
+ const r = await rebuild(omitted(), rebuildEnv({ labels: [[1033, 'Project']] }));
+ assert.deepStrictEqual(r.updates, []);
+ assert.match(r.labelEvents[0].label, /labelled "Project" — left as it is/);
+});
+
+test('ADO 6691205 rebuild: a label carrying several languages was edited since, so it is left alone', async () => {
+ const r = await rebuild(omitted(), rebuildEnv({ labels: [[1033, 'contoso_project'], [3082, 'proyecto']] }));
+ assert.deepStrictEqual(r.updates, []);
+ assert.match(r.labelEvents[0].label, /several languages/);
+});
+
+test('ADO 6691205 rebuild: an explicit lookup.displayName is never reapplied, even over the old default', async () => {
+ const spec = specOf([project(), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId', displayName: 'Owning project' })]);
+ const env = rebuildEnv({ labels: [[1033, 'contoso_project']] });
+ const r = await rebuild(spec, env);
+ assert.deepStrictEqual(r.updates, []);
+ assert.deepStrictEqual(r.labelEvents, [], 'the author owns this label: no step, and no read of the column');
+ assert.ok(!env.paths.some((p) => COLUMN_LABEL.test(p)), JSON.stringify(env.paths));
+});
+
+test('ADO 6691205 rebuild: a column the build just created is neither read nor repaired', async () => {
+ const env = metadataClient(() => ({ status: 200, headers: {}, body: { value: [] } }));
+ const r = await rebuild(omitted(), env);
+ assert.ok(r.calls.some((c) => c[0] === 'createRelationship'));
+ assert.deepStrictEqual(r.updates, []);
+ assert.match(r.labelEvents[0].label, /set when the relationship was created/);
+ assert.ok(!env.paths.some((p) => COLUMN_LABEL.test(p)), 'the label just written is not read back');
+});
+
+test('ADO 6691205 rebuild: an unreadable column is skipped with a warning, never repaired blind', async () => {
+ const r = await rebuild(omitted(), rebuildEnv({ columnStatus: 503 }));
+ assert.deepStrictEqual(r.updates, []);
+ assert.match(r.labelEvents[0].label, /could not be read — left as it is/);
+ assert.ok(r.warnings.some((w) => /contoso_projectid/.test(w) && /503/.test(w)), JSON.stringify(r.warnings));
+});
+
+test('ADO 6691205 rebuild: a column the environment does not have is skipped quietly', async () => {
+ const r = await rebuild(omitted(), rebuildEnv({ columnStatus: 404 }));
+ assert.deepStrictEqual(r.updates, []);
+ assert.match(r.labelEvents[0].label, /column not found/);
+ assert.deepStrictEqual(r.warnings, []);
+});
+
+test('ADO 6691205 rebuild: a lookup to a system table is repaired to the label the environment reports for it', async () => {
+ const spec = specOf([task()], [{ type: 'OneToMany', referenced: 'account', referencing: 'contoso_task', lookup: { schemaName: 'contoso_AccountId' } }]);
+ const env = rebuildEnv({ labels: [[1033, 'account']], relationship: 'contoso_account_task', referenced: 'account', lookup: 'contoso_accountid', parentLabel: [[1033, 'Account']] });
+ const r = await rebuild(spec, env);
+ assert.deepStrictEqual(r.updates, [['updateColumn', 'contoso_task', 'contoso_accountid', { displayName: 'Account', languageCode: 1033 }]]);
+});
+
+test('ADO 6691205 rebuild: a localized parent name is written in the authoring language only, never as a multi-language update', async () => {
+ // An UPDATE preceded by a label-bearing read is the shape the documented base-language hazard strips;
+ // one language cannot be stripped to less than itself.
+ const spec = specOf([project({ displayName: { 1033: 'Project', 3082: 'Proyecto' }, pluralName: { 1033: 'Projects', 3082: 'Proyectos' } }), task()],
+ [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })]);
+ const r = await rebuild(spec, rebuildEnv({ labels: [[3082, 'contoso_project']] }), { preResolvedLanguageCode: 3082 });
+ assert.deepStrictEqual(r.updates, [['updateColumn', 'contoso_task', 'contoso_projectid', { displayName: 'Proyecto', languageCode: 3082 }]]);
+});
+
+test('ADO 6691205 rebuild: a failed relabel is a warning, not a halt — it is cosmetic', async () => {
+ const m = engine({ existingTables: ['contoso_project', 'contoso_task'], dataverse: rebuildEnv({ labels: [[1033, 'contoso_project']] }) });
+ m.sdk.updateColumn = async () => { throw new Error('PUT refused'); };
+ const warnings = [];
+ const dm = await provisionDataModel({ sdk: m.sdk, provision: m.provision, runner: makeRunner({ emit: () => {}, total: 40 }), spec: omitted(), apply: true,
+ preResolvedLanguageCode: 1033, reconcileLookupLabels: true, warn: (w) => warnings.push(w) });
+ assert.ok(dm);
+ assert.ok(warnings.some((w) => /could not relabel lookup 'contoso_task\.contoso_projectid'/.test(w) && /PUT refused/.test(w) && /"contoso_project"/.test(w) && /"Project"/.test(w)), JSON.stringify(warnings));
+});
+
+test('ADO 6691205 rebuild: without the opt-in (the genpage entity builder) nothing is read or repaired', async () => {
+ const env = rebuildEnv({ labels: [[1033, 'contoso_project']] });
+ const r = await rebuild(omitted(), env, { reconcileLookupLabels: false });
+ assert.deepStrictEqual(r.updates, []);
+ assert.deepStrictEqual(r.labelEvents, []);
+ assert.ok(!env.paths.some((p) => COLUMN_LABEL.test(p)));
+});
+
+// A rebuild of a table with several lookups, every one of them still on its old default.
+const threeLookups = () => specOf([project(), task()], [
+ oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' }),
+ oneToMany('account', { schemaName: 'contoso_AccountId' }),
+ oneToMany('contact', { schemaName: 'contoso_ContactId' }),
+]);
+const LOOKUPS = ['contoso_projectid', 'contoso_accountid', 'contoso_contactid'];
+const threeLookupsEnv = (extra) => rebuildEnv({
+ columns: { contoso_projectid: [[1033, 'contoso_project']], contoso_accountid: [[1033, 'account']], contoso_contactid: [[1033, 'contact']] },
+ relationships: [
+ { SchemaName: REL, ReferencingEntity: 'contoso_task', ReferencingAttribute: 'contoso_projectid' },
+ { SchemaName: 'contoso_account_task', ReferencingEntity: 'contoso_task', ReferencingAttribute: 'contoso_accountid' },
+ { SchemaName: 'contoso_contact_task', ReferencingEntity: 'contoso_task', ReferencingAttribute: 'contoso_contactid' },
+ ],
+ parentLabels: { account: [[1033, 'Account']], contact: [[1033, 'Contact']] },
+ ...extra,
+});
+const labelReadsOf = (env) => env.paths.filter((p) => COLUMN_LABEL.test(p));
+
+test('ADO 6691205 rebuild: the labels of ALL of a table\'s lookups are read in ONE request, not one per lookup', async () => {
+ const env = threeLookupsEnv();
+ const r = await rebuild(threeLookups(), env);
+ const reads = labelReadsOf(env);
+ assert.strictEqual(reads.length, 1, JSON.stringify(reads));
+ assert.match(reads[0], /EntityDefinitions\(LogicalName='contoso_task'\)\/Attributes\?\$select=LogicalName,DisplayName&\$filter=/);
+ for (const name of LOOKUPS) assert.ok(reads[0].includes(`LogicalName eq '${name}'`), reads[0]);
+ assert.deepStrictEqual(r.updates.map((u) => [u[2], u[3].displayName]), [['contoso_projectid', 'Project'], ['contoso_accountid', 'Account'], ['contoso_contactid', 'Contact']]);
+ assert.strictEqual(r.labelEvents.length, 3, 'still one step per lookup, which is what the plan budgets');
+});
+
+// A column's label is part of its table's definition, which goes live only once the table is published, and nothing
+// else in the build is sure to publish a relabelled lookup's child table (a downloaded spec, for one, gives it no form,
+// view, chart or icon, and no enriched default views). So the pass publishes every table it relabelled itself: in one
+// request, each table once, before anything else.
+const publishesOf = (env) => env.posts.filter(([p]) => p === '/PublishXml').map(([, body]) => body.ParameterXml);
+
+test('ADO 6691205 rebuild: the table whose lookups were relabelled is published at once, in one request, named once', async () => {
+ const env = threeLookupsEnv();
+ const r = await rebuild(threeLookups(), env);
+ assert.strictEqual(r.updates.length, 3);
+ assert.deepStrictEqual(publishesOf(env), ['<importexportxml><entities><entity>contoso_task</entity></entities></importexportxml>']);
+ assert.deepStrictEqual(r.warnings, []);
+});
+
+test('ADO 6691205 rebuild: lookups relabelled on two tables publish both tables, in the same one request', async () => {
+ const step = { schemaName: 'contoso_Step', displayName: 'Step', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] };
+ const spec = specOf([project(), task(), step], [
+ oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' }),
+ { type: 'OneToMany', referenced: 'contoso_project', referencing: 'contoso_step', lookup: { schemaName: 'contoso_ProjectId' } },
+ ]);
+ const env = rebuildEnv({ labels: [[1033, 'contoso_project']], relationships: [
+ { SchemaName: REL, ReferencingEntity: 'contoso_task', ReferencingAttribute: 'contoso_projectid' },
+ { SchemaName: 'contoso_project_contoso_step', ReferencingEntity: 'contoso_step', ReferencingAttribute: 'contoso_projectid' },
+ ] });
+ const r = await rebuild(spec, env, {}, ['contoso_project', 'contoso_task', 'contoso_step']);
+ assert.deepStrictEqual(r.updates.map((u) => u[1]).sort(), ['contoso_step', 'contoso_task'], JSON.stringify(r.updates));
+ const published = publishesOf(env);
+ assert.strictEqual(published.length, 1, JSON.stringify(published));
+ assert.match(published[0], /<entity>contoso_task<\/entity>/);
+ assert.match(published[0], /<entity>contoso_step<\/entity>/);
+});
+
+test('ADO 6691205 rebuild: nothing is published when no lookup is relabelled', async () => {
+ const env = rebuildEnv({ labels: [[1033, 'Project']] });
+ const r = await rebuild(omitted(), env);
+ assert.deepStrictEqual(r.updates, []);
+ assert.deepStrictEqual(publishesOf(env), []);
+});
+
+test('ADO 6691205 rebuild: a publish of the relabelled table that fails is a warning naming the table, and the build goes on', async () => {
+ const env = rebuildEnv({ labels: [[1033, 'contoso_project']], publish: () => ({ status: 503, headers: {}, body: {} }) });
+ const r = await rebuild(omitted(), env);
+ assert.strictEqual(r.updates.length, 1);
+ assert.strictEqual(publishesOf(env).length, 1);
+ assert.ok(r.warnings.some((w) => /table contoso_task are saved but not published \(PublishXml answered HTTP 503\).*publish that table in Power Apps/.test(w)), r.warnings.join(' | '));
+ assert.deepStrictEqual(r.dm.lookupLabels['contoso_task|contoso_projectid'], { label: 'Project' }, 'the saved label still labels the form cells');
+});
+
+test('ADO 6691205 rebuild: only the lookups this run did not just create are read for', async () => {
+ // The relationship rows the environment holds omit the account lookup, so this build CREATES it and must
+ // neither read nor repair what it has just labelled.
+ const env = threeLookupsEnv({ relationships: [
+ { SchemaName: REL, ReferencingEntity: 'contoso_task', ReferencingAttribute: 'contoso_projectid' },
+ { SchemaName: 'contoso_contact_task', ReferencingEntity: 'contoso_task', ReferencingAttribute: 'contoso_contactid' },
+ ] });
+ const r = await rebuild(threeLookups(), env);
+ assert.deepStrictEqual(r.calls.filter((c) => c[0] === 'createRelationship').map((c) => c[1].lookupSchemaName), ['contoso_AccountId']);
+ const [read] = labelReadsOf(env);
+ assert.ok(read.includes("'contoso_projectid'") && read.includes("'contoso_contactid'") && !read.includes('contoso_accountid'), read);
+ assert.deepStrictEqual(r.updates.map((u) => u[2]), ['contoso_projectid', 'contoso_contactid']);
+});
+
+test('ADO 6691205 rebuild: a table whose labels cannot be read is warned about ONCE, and every lookup of it is skipped', async () => {
+ const r = await rebuild(threeLookups(), threeLookupsEnv({ columnStatus: 503 }));
+ assert.deepStrictEqual(r.updates, []);
+ assert.strictEqual(r.labelEvents.length, 3);
+ assert.ok(r.labelEvents.every((e) => /could not be read — left as it is/.test(e.label)), JSON.stringify(r.labelEvents.map((e) => e.label)));
+ const warned = r.warnings.filter((w) => /503/.test(w));
+ assert.strictEqual(warned.length, 1, JSON.stringify(r.warnings));
+ for (const name of LOOKUPS) assert.match(warned[0], new RegExp(name));
+});
+
+test('ADO 6691205 rebuild: a table that answers without the lookup column says "column not found", and is not an error', async () => {
+ const r = await rebuild(omitted(), rebuildEnv({}));
+ assert.deepStrictEqual(r.updates, []);
+ assert.match(r.labelEvents[0].label, /column not found/);
+ assert.deepStrictEqual(r.warnings, []);
+});
+
+const contactLookup = () => specOf([task()], [oneToMany('contact', { schemaName: 'contoso_ContactId' })]);
+const contactEnv = (labels, parentLabel) => rebuildEnv({ labels, relationship: 'contoso_contact_task', referenced: 'contact', lookup: 'contoso_contactid', parentLabel });
+const PARENT_READ = /\(LogicalName='contact'\)\?\$select=LogicalName,DisplayName$/;
+
+test('ADO 6691205 rebuild: a correct "Contact" is not the old default — nothing is repaired, and the table\'s name is not even read', async () => {
+ // The old default is the lower-case logical name "contact". "Contact" is the table's display name, i.e. the
+ // right answer; matching it too would cost a read of the table on EVERY rebuild just to learn that.
+ const env = contactEnv([[1033, 'Contact']], [[1033, 'Contact']]);
+ const r = await rebuild(contactLookup(), env);
+ assert.deepStrictEqual(r.updates, []);
+ assert.match(r.labelEvents[0].label, /labelled "Contact" — left as it is/);
+ assert.deepStrictEqual(env.paths.filter((p) => PARENT_READ.test(p)), []);
+});
+
+test('ADO 6691205 rebuild: a "Contact" a maker typed on a table the organization has since renamed is left alone', async () => {
+ const r = await rebuild(contactLookup(), contactEnv([[1033, 'Contact']], [[1033, 'Person']]));
+ assert.deepStrictEqual(r.updates, []);
+ assert.deepStrictEqual(r.dm.lookupLabels['contoso_task|contoso_contactid'], { label: 'Contact' });
+});
+
+test('ADO 6691205 rebuild: the lower-case logical name is still repaired, to the capitalised display name', async () => {
+ const r = await rebuild(contactLookup(), contactEnv([[1033, 'contact']], [[1033, 'Contact']]));
+ assert.deepStrictEqual(r.updates, [['updateColumn', 'contoso_task', 'contoso_contactid', { displayName: 'Contact', languageCode: 1033 }]]);
+});
+
+test('ADO 6691205 rebuild: an old default in a language other than the build\'s is left alone — a write in the build\'s language would leave two', async () => {
+ // The old default was written at 1033; this build writes French. "Projet" at 1036 beside "contoso_project"
+ // at 1033 would report success, leave the identifier on show for every English user, and make every later
+ // rebuild skip the column, because it then carries two languages.
+ const r = await rebuild(omitted(), rebuildEnv({ labels: [[1033, 'contoso_project']] }), { preResolvedLanguageCode: 1036 });
+ assert.deepStrictEqual(r.updates, []);
+ assert.match(r.labelEvents[0].label, /the old default "contoso_project" is in language 1033, not the build's 1036 — left as it is/);
+ assert.ok(r.warnings.some((w) => /contoso_projectid/.test(w) && /1033/.test(w) && /1036/.test(w) && /two languages/.test(w) && /Rename the column in Maker/.test(w) && !/Set lookup\.displayName/.test(w)), JSON.stringify(r.warnings));
+ assert.deepStrictEqual(r.dm.lookupLabels['contoso_task|contoso_projectid'], { label: 'contoso_project' }, 'what the column carries, which the form cell is aligned to');
+});
+
+test('ADO 6691205 rebuild: an old default in the build\'s own language is repaired whatever that language is', async () => {
+ const r = await rebuild(omitted(), rebuildEnv({ labels: [[1036, 'contoso_project']] }), { preResolvedLanguageCode: 1036 });
+ assert.deepStrictEqual(r.updates, [['updateColumn', 'contoso_task', 'contoso_projectid', { displayName: 'Project', languageCode: 1036 }]]);
+});
+
+test('ADO 6691205 rebuild: a lookup to a declared `existing: true` system table is repaired to the ENVIRONMENT\'s name — "Case", not a humanized "Incident"', async () => {
+ const spec = specOf([task(), incident()], [oneToMany('incident', { schemaName: 'contoso_CaseId' })]);
+ const env = rebuildEnv({ labels: [[1033, 'incident']], relationship: relationshipSchemaName(spec.relationships[0], 'contoso'), referenced: 'incident', lookup: 'contoso_caseid', parentLabel: [[1033, 'Case']] });
+ const r = await rebuild(spec, env);
+ assert.deepStrictEqual(r.updates, [['updateColumn', 'contoso_task', 'contoso_caseid', { displayName: 'Case', languageCode: 1033 }]]);
+ assert.deepStrictEqual(r.dm.lookupLabels['contoso_task|contoso_caseid'], { label: 'Case' }, 'and so is the form cell');
+});
+
+test('ADO 6691205 rebuild: a lookup to a declared `existing: true` custom table converges to the name the environment holds for it', async () => {
+ const spec = specOf([project({ displayName: undefined, existing: true }), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })]);
+ const r = await rebuild(spec, rebuildEnv({ labels: [[1033, 'contoso_project']], parentLabel: [[1033, 'Project Portfolio']] }));
+ assert.deepStrictEqual(r.updates, [['updateColumn', 'contoso_task', 'contoso_projectid', { displayName: 'Project Portfolio', languageCode: 1033 }]]);
+});
+
+test('REAL BUNDLE (ADO 6691205 rebuild): the relabel is a MergeLabels PUT of the typed lookup definition at the authoring LCID', async () => {
+ // Proves the SDK path the repair relies on — `updateColumn` on a LOOKUP — serializes what the repair
+ // means: the label replaced at one language, every other property of the definition round-tripped,
+ // and the header that keeps any other language a maker added.
+ const id = '22222222-2222-2222-2222-222222222222';
+ const { sdk, writes, reads } = await realSdk([
+ exists('contoso_project'), exists('contoso_task'),
+ [/OneToManyRelationships/, { status: 200, headers: {}, body: { value: [{ SchemaName: REL, ReferencingEntity: 'contoso_task', ReferencingAttribute: 'contoso_projectid' }] } }],
+ [COLUMN_LABEL, { status: 200, headers: {}, body: { value: [{ LogicalName: 'contoso_projectid', DisplayName: label([[1031, 'contoso_project']]) }] } }],
+ [/Attributes\(LogicalName='contoso_projectid'\)\?\$select=MetadataId,AttributeType/, { status: 200, headers: {}, body: { MetadataId: id, AttributeType: 'Lookup' } }],
+ [new RegExp(`Attributes\\(${id}\\)/Microsoft.Dynamics.CRM.LookupAttributeMetadata`), {
+ status: 200,
+ headers: {},
+ body: {
+ '@odata.context': 'x', LogicalName: 'contoso_projectid', SchemaName: 'contoso_ProjectId', AttributeType: 'Lookup', Targets: ['contoso_project'],
+ DisplayName: label([[1031, 'contoso_project']]), RequiredLevel: { Value: 'None', CanBeChanged: true, ManagedPropertyLogicalName: 'canmodifyrequirementlevelsettings' },
+ },
+ }],
+ ]);
+ await provisionDataModel({ sdk, provision: sdk, runner: makeRunner({ emit: () => {}, total: 40 }), spec: omitted(), apply: true, preResolvedLanguageCode: 1031, reconcileLookupLabels: true });
+ const put = writes.find((w) => w.verb === 'PUT');
+ assert.ok(put, JSON.stringify(writes.map((w) => `${w.verb} ${w.url}`)));
+ assert.match(put.url, new RegExp(`Attributes\\(${id}\\)$`));
+ assert.deepStrictEqual((put.body.DisplayName.LocalizedLabels || []).map((l) => [l.LanguageCode, l.Label]), [[1031, 'Project']]);
+ assert.strictEqual(put.body.SchemaName, 'contoso_ProjectId', 'the rest of the definition is carried back unchanged');
+ assert.deepStrictEqual(put.body.Targets, ['contoso_project']);
+ assert.strictEqual(put.headers['MSCRM.MergeLabels'], 'true');
+ assert.ok(!writes.some((w) => w.verb === 'POST' && /RelationshipDefinitions/.test(w.url)), 'the relationship itself is not recreated');
+ // The label read the real client sent: ONE collection request for the child table's lookups, filtered by logical name.
+ const labelReads = reads.filter((r) => /\/Attributes\?\$select=LogicalName,DisplayName&\$filter=/.test(r));
+ assert.strictEqual(labelReads.length, 1, JSON.stringify(labelReads));
+ assert.match(labelReads[0], /\/EntityDefinitions\(LogicalName='contoso_task'\)\/Attributes\?\$select=LogicalName,DisplayName&\$filter=LogicalName eq 'contoso_projectid'$/);
+});
+
+// ── 5. the plan budgets exactly the steps the phase emits ─────────────────────────────────────────
+
+const { planFor } = require('../lib/sdk-build.js');
+
+test('ADO 6691205 plan: one step per lookup the build labels, none for an explicit label — and the phase emits exactly those', async () => {
+ // The runner's total is fixed from the plan, so a step the phase emits and the plan does not budget
+ // overruns it ([37/36]); one the plan budgets and the phase never emits leaves it short.
+ const spec = specOf([project(), task()], [
+ oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' }),
+ oneToMany('account', { schemaName: 'contoso_AccountId' }),
+ oneToMany('contact', { schemaName: 'contoso_ContactId', displayName: 'Primary contact' }),
+ { type: 'ManyToMany', entity1: 'contoso_project', entity2: 'contoso_task' },
+ ]);
+ const planned = planFor(spec, { phases: ['data-model'] }).filter((i) => /^lookup label /.test(i.label));
+ assert.deepStrictEqual(planned.map((i) => i.label), [
+ 'lookup label contoso_task.contoso_ProjectId (default "Project")',
+ 'lookup label contoso_task.contoso_AccountId (default the display name of account)',
+ ]);
+ assert.ok(planned.every((i) => i.phase === 'data-model' && !i.key), 'unkeyed, so the live plan leaves them unprobed');
+ const r = await rebuild(spec, rebuildEnv({ labels: [[1033, 'contoso_project']] }));
+ assert.strictEqual(r.labelEvents.length, planned.length, JSON.stringify(r.labelEvents.map((e) => e.label)));
+});
+
+test('ADO 6691205 plan: a spec that labels every lookup itself plans no label step at all', () => {
+ const spec = specOf([project(), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId', displayName: 'Project' })]);
+ assert.deepStrictEqual(planFor(spec, { phases: ['data-model'] }).filter((i) => /^lookup label /.test(i.label)), []);
+});
+
+test('ADO 6691205 plan: a declared `existing: true` parent with no displayName is planned as the environment\'s name, like an undeclared one', () => {
+ const spec = specOf([task(), incident(), project()], [
+ oneToMany('incident', { schemaName: 'contoso_CaseId' }),
+ oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' }),
+ ]);
+ assert.deepStrictEqual(planFor(spec, { phases: ['data-model'] }).filter((i) => /^lookup label /.test(i.label)).map((i) => i.label), [
+ 'lookup label contoso_task.contoso_CaseId (default the display name of incident)',
+ 'lookup label contoso_task.contoso_ProjectId (default "Project")',
+ ]);
+});
+
+test('ADO 6691205 plan: a declared parent with no displayName that the build may find already there says its label can come from the environment', () => {
+ // Not flagged, so the build creates the table — unless it is already there, in which case the lookup takes the label
+ // the environment holds. The plan cannot know which, so it says both rather than only the humanized name.
+ const spec = specOf([project({ displayName: undefined }), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })]);
+ assert.deepStrictEqual(planFor(spec, { phases: ['data-model'] }).filter((i) => /^lookup label /.test(i.label)).map((i) => i.label),
+ ['lookup label contoso_task.contoso_ProjectId (default "Project", or the label from the environment if contoso_project is already there)']);
+ // A parent that names itself, and one that is not declared, are planned as before.
+ const named = specOf([project(), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' }), oneToMany('account', { schemaName: 'contoso_AccountId' })]);
+ assert.deepStrictEqual(planFor(named, { phases: ['data-model'] }).filter((i) => /^lookup label /.test(i.label)).map((i) => i.label), [
+ 'lookup label contoso_task.contoso_ProjectId (default "Project")',
+ 'lookup label contoso_task.contoso_AccountId (default the display name of account)',
+ ]);
+});
+
+// ── 6. an existing FORM's lookup cell (REAL bundle) ───────────────────────────────────────────────
+
+const { repairLookupCellLabels } = require('../lib/lookup-cell-labels.js');
+
+// A real form carrying the lookup's cell, labelled `cellLabel`, beside an ordinary field cell.
+async function formWithLookupCell(cellLabel, lookupField = 'contoso_projectid') {
+ const real = await realSdk([]);
+ const art = await real.sdk.createArtifact('form', { entityLogicalName: 'contoso_task', name: 'Task', formType: 'Main', status: 'Active' });
+ await real.sdk.addElement('form', art.id, '/tabs', {
+ name: 'tab_general', label: 'General', expanded: true, visible: true,
+ columns: [{ width: '100%', sections: [{ name: 'section_general', label: 'General', visible: true, showLabel: false, columns: 1, rows: [
+ { cells: [{ control: { fieldName: 'contoso_name', label: 'Name', isRequired: true } }] },
+ { cells: [{ control: { fieldName: lookupField, label: cellLabel, isRequired: true } }] },
+ ] }] }],
+ });
+ await real.sdk.removeElement('form', art.id, '/tabs/0');
+ return { ...real, formId: art.id };
+}
+
+const lookupControl = async (sdk, formId) => {
+ const form = await sdk.getArtifact('form', formId);
+ const cells = form.tabs.flatMap((t) => t.columns.flatMap((c) => c.sections.flatMap((s) => s.rows.flatMap((r) => r.cells))));
+ return cells.map((c) => c.control).find((c) => c && c.fieldName === 'contoso_projectid');
+};
+
+const repairArgs = (extra) => ({
+ entityLogical: 'contoso_task',
+ spec: omitted(),
+ lookupLabels: { 'contoso_task|contoso_projectid': { label: 'Project' } },
+ ...extra,
+});
+
+test('REAL BUNDLE (ADO 6691205 rebuild): a form field the SDK labelled with its OWN logical name — it could not resolve the column at push — is relabelled too', async () => {
+ // The lookup's own lower-case logical name is the second old default (see the premise test below). It is what a
+ // build that could not read the column's metadata left on the field; the column's label was never that.
+ const { sdk, formId, writes } = await formWithLookupCell('contoso_projectid');
+ const repaired = await repairLookupCellLabels({ provision: sdk, formId, ...repairArgs() });
+ assert.deepStrictEqual(repaired, ['contoso_projectid']);
+ const after = await lookupControl(sdk, formId);
+ assert.strictEqual(after.label, 'Project');
+ assert.strictEqual(after.isRequired, true);
+ await sdk.pushArtifact('form', formId);
+ const xml = writes.map((w) => w.body && w.body.formxml).find(Boolean);
+ assert.match(xml, /<label description="Project" languagecode="1033" \/>/);
+ assert.doesNotMatch(xml, /description="contoso_projectid"/);
+});
+
+test('REAL BUNDLE (ADO 6691205 rebuild): the capitalised schema name a spec spells is not a label any build wrote, so a field carrying it is left alone', async () => {
+ const { sdk, formId } = await formWithLookupCell('contoso_ProjectId');
+ assert.deepStrictEqual(await repairLookupCellLabels({ provision: sdk, formId, ...repairArgs() }), []);
+ assert.strictEqual((await lookupControl(sdk, formId)).label, 'contoso_ProjectId');
+});
+
+test('REAL BUNDLE (ADO 6691205): the SDK labels a form field it cannot resolve a column for with the field\'s lower-case logical name', async () => {
+ // Pins the premise of the second old default. With no label on the cell and no column metadata to take one from,
+ // the bundle writes control.fieldName — `contoso_projectid`, not the `contoso_ProjectId` the spec spells.
+ const { sdk, writes } = await realSdk([]);
+ const art = await sdk.createArtifact('form', { name: 'Task', entityLogicalName: 'contoso_task', formType: 'Main', status: 'Active' });
+ await sdk.addElement('form', art.id, '/tabs', {
+ name: 'tab_general', label: 'General', expanded: true, visible: true,
+ columns: [{ width: '100%', sections: [{ name: 'section_general', label: 'General', visible: true, showLabel: false, columns: 1, rows: [
+ { cells: [{ control: { fieldName: 'contoso_projectid' } }] },
+ ] }] }],
+ });
+ await sdk.removeElement('form', art.id, '/tabs/0');
+ await sdk.pushArtifact('form', art.id);
+ const xml = String(writes.map((w) => w.body && w.body.formxml).find(Boolean));
+ const cell = xml.split('<cell').find((c) => /datafieldname="contoso_projectid"/.test(c));
+ assert.ok(cell, 'the lookup cell is in the pushed form');
+ assert.match(cell, /<label description="contoso_projectid" languagecode="1033" \/>/);
+});
+
+test('REAL BUNDLE (ADO 6691205 rebuild): a form cell still labelled with the old default is relabelled, and the rest of its control survives', async () => {
+ const { sdk, formId, writes } = await formWithLookupCell('contoso_project');
+ const before = await lookupControl(sdk, formId);
+ const repaired = await repairLookupCellLabels({ provision: sdk, formId, ...repairArgs() });
+ assert.deepStrictEqual(repaired, ['contoso_projectid']);
+ const after = await lookupControl(sdk, formId);
+ assert.strictEqual(after.label, 'Project');
+ assert.strictEqual(after.isRequired, true, 'updateElement merged the patch instead of replacing the control');
+ assert.strictEqual(after.id, before.id);
+ assert.strictEqual(after.classId, before.classId);
+ // ...and it is what the SDK would push.
+ await sdk.pushArtifact('form', formId);
+ const xml = writes.map((w) => w.body && w.body.formxml).find(Boolean);
+ assert.match(xml, /<label description="Project" languagecode="1033" \/>/);
+ assert.doesNotMatch(xml, /description="contoso_project"/);
+});
+
+test('REAL BUNDLE (ADO 6691205 rebuild): a form cell a maker relabelled is left alone', async () => {
+ const { sdk, formId } = await formWithLookupCell('Parent project');
+ assert.deepStrictEqual(await repairLookupCellLabels({ provision: sdk, formId, ...repairArgs() }), []);
+ assert.strictEqual((await lookupControl(sdk, formId)).label, 'Parent project');
+});
+
+test('REAL BUNDLE (ADO 6691205 rebuild): a cell is aligned to the label the COLUMN carries now, even a maker\'s', async () => {
+ const { sdk, formId } = await formWithLookupCell('contoso_project');
+ await repairLookupCellLabels({ provision: sdk, formId, ...repairArgs({ lookupLabels: { 'contoso_task|contoso_projectid': { label: 'Parent project' } } }) });
+ assert.strictEqual((await lookupControl(sdk, formId)).label, 'Parent project');
+});
+
+test('REAL BUNDLE (ADO 6691205 rebuild): with no record of the column\'s label the cell is left as it is', async () => {
+ const { sdk, formId } = await formWithLookupCell('contoso_project');
+ assert.deepStrictEqual(await repairLookupCellLabels({ provision: sdk, formId, ...repairArgs({ lookupLabels: {} }) }), []);
+ assert.deepStrictEqual(await repairLookupCellLabels({ provision: sdk, formId, ...repairArgs({ lookupLabels: undefined }) }), []);
+ assert.strictEqual((await lookupControl(sdk, formId)).label, 'contoso_project');
+});
+
+test('REAL BUNDLE (ADO 6691205 rebuild): an explicit lookup.displayName in the spec is never reapplied to a cell', async () => {
+ const { sdk, formId } = await formWithLookupCell('contoso_project');
+ const spec = specOf([project(), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId', displayName: 'Owning project' })]);
+ assert.deepStrictEqual(await repairLookupCellLabels({ provision: sdk, formId, ...repairArgs({ spec }) }), []);
+ assert.strictEqual((await lookupControl(sdk, formId)).label, 'contoso_project');
+});
+
+test('REAL BUNDLE (ADO 6691205 rebuild): a form that does not carry the lookup\'s cell is untouched', async () => {
+ const { sdk, formId } = await formWithLookupCell('contoso_project', 'contoso_ownerid');
+ const repaired = await repairLookupCellLabels({ provision: sdk, formId, ...repairArgs() });
+ assert.deepStrictEqual(repaired, []);
+ const form = await sdk.getArtifact('form', formId);
+ const labels = form.tabs.flatMap((t) => t.columns.flatMap((c) => c.sections.flatMap((s) => s.rows.flatMap((r) => r.cells.map((cell) => cell.control.label)))));
+ assert.deepStrictEqual(labels, ['Name', 'contoso_project']);
+});
+
+// A real form carrying the lookup's field TWICE, as a maker can place it: once in the first section and once in a
+// second one, each cell with a label of its own.
+async function formWithLookupCellTwice(firstLabel, secondLabel) {
+ const real = await realSdk([]);
+ const art = await real.sdk.createArtifact('form', { entityLogicalName: 'contoso_task', name: 'Task', formType: 'Main', status: 'Active' });
+ await real.sdk.addElement('form', art.id, '/tabs', {
+ name: 'tab_general', label: 'General', expanded: true, visible: true,
+ columns: [{ width: '100%', sections: [
+ { name: 'section_general', label: 'General', visible: true, showLabel: false, columns: 1, rows: [
+ { cells: [{ control: { fieldName: 'contoso_name', label: 'Name', isRequired: true } }] },
+ { cells: [{ control: { fieldName: 'contoso_projectid', label: firstLabel, isRequired: true } }] },
+ ] },
+ { name: 'section_more', label: 'More', visible: true, showLabel: false, columns: 1, rows: [
+ { cells: [{ control: { fieldName: 'contoso_projectid', label: secondLabel } }] },
+ ] },
+ ] }],
+ });
+ await real.sdk.removeElement('form', art.id, '/tabs/0');
+ return { ...real, formId: art.id };
+}
+
+const lookupControls = async (sdk, formId) => {
+ const form = await sdk.getArtifact('form', formId);
+ const cells = form.tabs.flatMap((t) => t.columns.flatMap((c) => c.sections.flatMap((s) => s.rows.flatMap((r) => r.cells))));
+ return cells.map((c) => c.control).filter((c) => c && c.fieldName === 'contoso_projectid');
+};
+
+// The labels of the lookup's cells in what the SDK would push, in form order.
+const pushedLookupLabels = async (sdk, formId, writes) => {
+ await sdk.pushArtifact('form', formId);
+ const xml = String(writes.map((w) => w.body && w.body.formxml).filter(Boolean).pop());
+ return xml.split('<cell').filter((c) => /datafieldname="contoso_projectid"/.test(c)).map((c) => (/<label description="([^"]*)"/.exec(c) || [])[1]);
+};
+
+test('REAL BUNDLE (ADO 6691205 rebuild): a lookup the form holds twice has its SECOND cell relabelled when the first is already right', async () => {
+ const { sdk, formId, writes } = await formWithLookupCellTwice('Project', 'contoso_project');
+ assert.strictEqual((await lookupControls(sdk, formId)).length, 2, 'the bundle keeps both cells of the field');
+ const before = await lookupControls(sdk, formId);
+ assert.deepStrictEqual(await repairLookupCellLabels({ provision: sdk, formId, ...repairArgs() }), ['contoso_projectid'], 'the lookup is named once');
+ const after = await lookupControls(sdk, formId);
+ assert.deepStrictEqual(after.map((c) => c.label), ['Project', 'Project']);
+ assert.deepStrictEqual(after.map((c) => c.id), before.map((c) => c.id), 'each cell keeps its control');
+ assert.deepStrictEqual(await pushedLookupLabels(sdk, formId, writes), ['Project', 'Project']);
+});
+
+test('REAL BUNDLE (ADO 6691205 rebuild): a lookup the form holds twice keeps a maker\'s label on one cell and has the old default on the other relabelled', async () => {
+ const { sdk, formId, writes } = await formWithLookupCellTwice('Parent project', 'contoso_project');
+ assert.deepStrictEqual(await repairLookupCellLabels({ provision: sdk, formId, ...repairArgs() }), ['contoso_projectid']);
+ assert.deepStrictEqual((await lookupControls(sdk, formId)).map((c) => c.label), ['Parent project', 'Project']);
+ assert.deepStrictEqual(await pushedLookupLabels(sdk, formId, writes), ['Parent project', 'Project']);
+});
+
+test('REAL BUNDLE (ADO 6691205 rebuild): both cells of a lookup the form holds twice, each with an old default, are relabelled', async () => {
+ const { sdk, formId } = await formWithLookupCellTwice('contoso_project', 'contoso_projectid');
+ assert.deepStrictEqual(await repairLookupCellLabels({ provision: sdk, formId, ...repairArgs() }), ['contoso_projectid']);
+ const after = await lookupControls(sdk, formId);
+ assert.deepStrictEqual(after.map((c) => c.label), ['Project', 'Project']);
+ assert.deepStrictEqual(after.map((c) => c.isRequired), [true, undefined], 'each cell keeps the rest of its own control');
+});
+
+test('REAL BUNDLE (ADO 6691205 rebuild): a lookup the form holds twice with no old default on either cell is untouched', async () => {
+ const { sdk, formId } = await formWithLookupCellTwice('Project', 'Parent project');
+ assert.deepStrictEqual(await repairLookupCellLabels({ provision: sdk, formId, ...repairArgs() }), []);
+ assert.deepStrictEqual((await lookupControls(sdk, formId)).map((c) => c.label), ['Project', 'Parent project']);
+});
+
+// ── 7. the whole engine: data-model repair, then the existing form ────────────────────────────────
+
+const { runSdkBuild } = require('../lib/sdk-build.js');
+const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');
+
+// An existing app whose `contoso_task` form carries the lookup's cell, labelled `cellLabel`, rebuilt by the whole
+// engine against a column the environment labels `columnLabel`.
+async function engineRebuild({ columnLabel, cellLabel }) {
+ // Wiring: reconcileLookupLabels is switched on by the app build, and the forms phase reads what the
+ // data-model phase recorded (`dataModel.lookupLabels`) — neither is visible to a unit test of one half.
+ const { sdk, calls } = makeSimpleMockSdk();
+ sdk.queryRecords = async (set) => (set === 'solution' ? [] : set === 'systemform' ? [{ formid: 'form-1' }] : set === 'organization' ? [{ languagecode: 1033 }] : [{ publisherid: 'pub-1' }]);
+ sdk.dataverse = rebuildEnv({ labels: [[1033, columnLabel]] });
+ sdk.updateColumn = async (...args) => { calls.push(['updateColumn', ...args]); };
+ // The simple mock REPLACES on updateElement; the real SDK merges an object patch, which the repair relies on.
+ sdk.updateElement = async (type, id, pointer, patch) => {
+ const art = await sdk.getArtifact(type, id);
+ const tokens = pointer.split('/').slice(1);
+ const last = tokens.pop();
+ const holder = tokens.reduce((cur, token) => cur[token], art);
+ const merge = holder[last] && typeof holder[last] === 'object' && patch && typeof patch === 'object' && !Array.isArray(patch);
+ holder[last] = merge ? { ...holder[last], ...patch } : JSON.parse(JSON.stringify(patch));
+ return art;
+ };
+ await sdk.fetchArtifact('form', 'form-1');
+ await sdk.addElement('form', 'form-1', '/tabs/0/columns/0/sections/0/rows', { cells: [{ control: { fieldName: 'contoso_name', label: 'Name' } }] });
+ await sdk.addElement('form', 'form-1', '/tabs/0/columns/0/sections/0/rows', { cells: [{ control: { fieldName: 'contoso_projectid', label: cellLabel, isRequired: true } }] });
+
+ const spec = specOf([project(), task()], [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })], {
+ app: { name: 'Tasks' },
+ forms: [{ entity: 'contoso_task', name: 'Task', layout: 'auto' }],
+ });
+ const events = [];
+ await runSdkBuild(spec, { sdk, apply: true, emit: (e) => events.push(e), phases: ['solution', 'data-model', 'forms'], preResolvedLanguageCode: 1033 });
+ const cell = (await sdk.getArtifact('form', 'form-1')).tabs[0].columns[0].sections[0].rows.map((r) => r.cells[0].control).find((c) => c.fieldName === 'contoso_projectid');
+ return { updates: calls.filter((c) => c[0] === 'updateColumn').map((c) => c.slice(1)), cell, events };
+}
+
+test('ADO 6691205 rebuild: the engine relabels the column in the data-model phase and then the cell on the existing form', async () => {
+ const { updates, cell, events } = await engineRebuild({ columnLabel: 'contoso_project', cellLabel: 'contoso_project' });
+ assert.deepStrictEqual(updates, [['contoso_task', 'contoso_projectid', { displayName: 'Project', languageCode: 1033 }]]);
+ assert.strictEqual(cell.label, 'Project', 'the cell follows the column');
+ assert.strictEqual(cell.isRequired, true);
+ const terminal = events.filter((e) => e.status !== 'start');
+ assert.ok(terminal.every((e) => e.n <= e.total), `a step overran the plan: ${JSON.stringify(terminal.filter((e) => e.n > e.total))}`);
+});
+
+test('ADO 6691205 rebuild: a label a maker set on the column survives the engine, and a cell still holding the old default follows it', async () => {
+ // Measured on a live environment: a lookup relabelled "Owning Project" through the SDK kept that label across
+ // the rebuild, and the form cell that still held the old default then showed "Owning Project", not the
+ // build's own default and not the identifier.
+ const { updates, cell } = await engineRebuild({ columnLabel: 'Owning Project', cellLabel: 'contoso_project' });
+ assert.deepStrictEqual(updates, [], 'the maker\'s label is not overwritten');
+ assert.strictEqual(cell.label, 'Owning Project', 'the cell follows the column\'s current label');
+ assert.strictEqual(cell.isRequired, true, 'and nothing else about it changes');
+});
+
+test('ADO 6691205 rebuild: a cell a maker relabelled differently from its column is left alone', async () => {
+ const { cell } = await engineRebuild({ columnLabel: 'Owning Project', cellLabel: 'Parent' });
+ assert.strictEqual(cell.label, 'Parent');
+});
+
+// ── 8. every surface that SHOWS a lookup label goes through the same rule ─────────────────────────
+
+const { schemaFacts } = require('../lib/schema-facts.js');
+const { renderFormWireframe } = require('../lib/form-preview.js');
+const { renderAppPreview } = require('../lib/app-preview.js');
+const { renderAppSpecDoc } = require('../lib/app-spec-doc.js');
+
+const shown = () => specOf([project(), task()], [
+ oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' }),
+ oneToMany('account', { schemaName: 'contoso_AccountId' }),
+ oneToMany('contact', { schemaName: 'contoso_ContactId', displayName: 'Primary contact' }),
+]);
+
+test('ADO 6691205 surfaces: the eval data facts carry the label the build will write', () => {
+ const facts = schemaFacts(shown()).relationships.map((r) => [r.lookup.logicalName, r.lookup.displayName]);
+ assert.deepStrictEqual(facts, [['contoso_accountid', 'Account'], ['contoso_contactid', 'Primary contact'], ['contoso_projectid', 'Project']]);
+});
+
+test('ADO 6691205 surfaces: a form wireframe labels a lookup field with its label, not its logical name', () => {
+ const spec = shown();
+ spec.forms = [{ entity: 'contoso_task', name: 'Task', formType: 'Main', tabs: [{ label: 'General', sections: [{ label: 'Details', fields: ['contoso_name', 'contoso_projectid', 'contoso_contactid'] }] }] }];
+ const wire = renderFormWireframe(spec, spec.forms[0]);
+ assert.match(wire, /Project\b.*\[lookup\]/);
+ assert.match(wire, /Primary contact\b.*\[lookup\]/);
+ assert.doesNotMatch(wire, /contoso_projectid|contoso_contactid/);
+});
+
+test('ADO 6691205 surfaces: the auto-layout wireframe shows the lookup it will place, by label', () => {
+ const spec = shown();
+ spec.forms = [{ entity: 'contoso_task', name: 'Task', formType: 'Main', layout: 'auto' }];
+ const wire = renderFormWireframe(spec, spec.forms[0]);
+ assert.match(wire, /Project\b.*\[lookup\]/);
+ assert.doesNotMatch(wire, /contoso_projectid/);
+});
+
+test('ADO 6691205 surfaces: the app preview names each lookup\'s label', () => {
+ const out = renderAppPreview(shown());
+ assert.match(out, /1:N {2}contoso_project {2}→ {2}contoso_task {2}\(lookup contoso_ProjectId — "Project"\)/);
+ assert.match(out, /\(lookup contoso_ContactId — "Primary contact"\)/);
+});
+
+test('ADO 6691205 surfaces: the design document lists the label beside the lookup', () => {
+ const doc = renderAppSpecDoc(shown());
+ assert.match(doc, /\| Kind \| From \| To \| Lookup \| Label \|/);
+ assert.match(doc, /\| 1:N \| contoso_project \| contoso_task \| contoso_ProjectId \| Project \|/);
+ assert.match(doc, /\| 1:N \| contact \| contoso_task \| contoso_ContactId \| Primary contact \|/);
+});
+
+test('ADO 6691205 surfaces: a localized default is shown in the spec\'s language', () => {
+ const spec = specOf([project({ displayName: { 1033: 'Project', 3082: 'Proyecto' }, pluralName: { 1033: 'Projects', 3082: 'Proyectos' } }), task()],
+ [oneToMany('contoso_project', { schemaName: 'contoso_ProjectId' })], { languageCode: 3082 });
+ assert.strictEqual(schemaFacts(spec).relationships[0].lookup.displayName, 'Proyecto');
+ assert.match(renderAppPreview(spec), /\(lookup contoso_ProjectId — "Proyecto"\)/);
+ assert.doesNotMatch(renderAppSpecDoc(spec), /\[object Object\]/);
+});
+
+
diff --git a/plugins/model-apps/scripts/tests/lookup-label-download.test.js b/plugins/model-apps/scripts/tests/lookup-label-download.test.js
new file mode 100644
index 000000000..d4af68ff3
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/lookup-label-download.test.js
@@ -0,0 +1,141 @@
+'use strict';
+// ADO 6691205 (download half): a lookup whose live label is exactly what a rebuild would write when the
+// spec omits `lookup.displayName` is downloaded WITHOUT one, so downloaded specs stay minimal; a label
+// that differs is written as before. See lookupLabelFor (app-spec.js) for the rule the comparison uses.
+const { test } = require('node:test');
+const assert = require('node:assert');
+const { readRelationships } = require('../download-model-app.js');
+const { lookupColumnsFor, validateAppSpec } = require('../lib/app-spec.js');
+
+const label = (...pairs) => ({ LocalizedLabels: pairs.map(([LanguageCode, Label]) => ({ Label, LanguageCode })) });
+const rel = (o) => ({ IsCustomRelationship: true, ...o });
+
+// The reads `readRelationships` performs. `parents` answers the stock-parent probe
+// (`?$select=IsCustomEntity,DisplayName`) with the table's label.
+function makeSdk({ m2o = {}, lookups = {}, parents = {} } = {}) {
+ const ofEntity = (p) => (p.match(/LogicalName='([^']+)'/) || [])[1];
+ return {
+ dataverse: {
+ get: async (p) => {
+ const e = ofEntity(p);
+ if (/\/ManyToOneRelationships/.test(p)) return { status: 200, body: { value: m2o[e] || [] } };
+ if (/\/ManyToManyRelationships/.test(p)) return { status: 200, body: { value: [] } };
+ if (/LookupAttributeMetadata/.test(p)) return { status: 200, body: { value: lookups[e] || [] } };
+ if (/\?\$select=IsCustomEntity/.test(p)) return { status: 200, body: { IsCustomEntity: false, ...(parents[e] ? { DisplayName: parents[e] } : {}) } };
+ return { status: 404, body: null };
+ },
+ },
+ };
+}
+
+const ticketToCustomer = (displayName) => ({
+ m2o: { new_ticket: [rel({ SchemaName: 'new_customer_new_ticket', ReferencedEntity: 'new_customer', ReferencingEntity: 'new_ticket', ReferencingAttribute: 'new_customerid' })] },
+ lookups: { new_ticket: [{ LogicalName: 'new_customerid', SchemaName: 'new_CustomerId', DisplayName: displayName, Targets: ['new_customer'] }] },
+});
+const customer = (displayName) => ({ schemaName: 'new_customer', displayName });
+const ticket = () => ({ schemaName: 'new_ticket', displayName: 'Ticket' });
+const read = (sdk, entities) => readRelationships(sdk, ['new_customer', 'new_ticket'], 'new', undefined, { entities });
+
+test('ADO 6691205 download: a lookup labelled like its in-app parent omits displayName', async () => {
+ const { relationships } = await read(makeSdk(ticketToCustomer(label([1033, 'Customer']))), [customer('Customer'), ticket()]);
+ assert.deepStrictEqual(relationships[0].lookup, { schemaName: 'new_CustomerId' });
+});
+
+test('ADO 6691205 download: a lookup whose label differs from its parent keeps displayName, exactly as before', async () => {
+ const { relationships } = await read(makeSdk(ticketToCustomer(label([1033, 'Account holder']))), [customer('Customer'), ticket()]);
+ assert.deepStrictEqual(relationships[0].lookup, { schemaName: 'new_CustomerId', displayName: 'Account holder' });
+});
+
+test('ADO 6691205 download: a label that still holds the old default (the parent\'s logical name) is left out, so a rebuild repairs it', async () => {
+ // An explicit label is never repaired on a rebuild, so writing the identifier out would carry the defect through
+ // download -> edit -> rebuild for good; leaving it out is what hands the label to the rebuild's repair.
+ const { relationships } = await read(makeSdk(ticketToCustomer(label([1033, 'new_customer']))), [customer('Customer'), ticket()]);
+ assert.deepStrictEqual(relationships[0].lookup, { schemaName: 'new_CustomerId' });
+});
+
+test('ADO 6691205 download: only the parent\'s logical name is the old default of a COLUMN — the lookup\'s own name is somebody\'s label, and is carried', async () => {
+ // The SDK labels a column with the referenced table's logical name. The lookup's own lower-case name is what it
+ // leaves on a form FIELD it could not resolve; no build wrote it on a column, so a column carrying it was labelled
+ // by a person, which a rebuild must keep — as it must a schema name with capitals or a case variant.
+ for (const typed of ['new_customerid', 'new_CustomerId', 'NEW_Customer']) {
+ const carried = await read(makeSdk(ticketToCustomer(label([1033, typed]))), [customer('Customer'), ticket()]);
+ assert.strictEqual(carried.relationships[0].lookup.displayName, typed, typed);
+ }
+});
+
+test('ADO 6691205 download: an old default on a lookup to a stock table is left out as well, with no stock label to compare', async () => {
+ const sdk = makeSdk({
+ m2o: { new_ticket: [rel({ SchemaName: 'new_systemuser_new_ticket', ReferencedEntity: 'systemuser', ReferencingEntity: 'new_ticket', ReferencingAttribute: 'new_agentid' })] },
+ lookups: { new_ticket: [{ LogicalName: 'new_agentid', SchemaName: 'new_AgentId', DisplayName: label([1033, 'systemuser']), Targets: ['systemuser'] }] },
+ });
+ const { relationships } = await read(sdk, [ticket()]);
+ assert.deepStrictEqual(relationships[0].lookup, { schemaName: 'new_AgentId' });
+});
+
+test('ADO 6691205 download: a correct label that merely reads like the table\'s name is carried, not mistaken for the old default', async () => {
+ // "Contact" is the display name of `contact`; the old default is the lower-case logical name.
+ const sdk = makeSdk({
+ m2o: { new_ticket: [rel({ SchemaName: 'new_contact_new_ticket', ReferencedEntity: 'contact', ReferencingEntity: 'new_ticket', ReferencingAttribute: 'new_contactid' })] },
+ lookups: { new_ticket: [{ LogicalName: 'new_contactid', SchemaName: 'new_ContactId', DisplayName: label([1033, 'Contact']), Targets: ['contact'] }] },
+ });
+ const { relationships } = await read(sdk, [ticket()]);
+ assert.strictEqual(relationships[0].lookup.displayName, 'Contact', 'no stock label was read to prove it is the default, so nothing is assumed');
+});
+
+test('ADO 6691205 download: a localized lookup label equal to a localized parent name omits displayName', async () => {
+ const map = { 1033: 'Customer', 3082: 'Cliente' };
+ const { relationships } = await read(makeSdk(ticketToCustomer(label([1033, 'Customer'], [3082, 'Cliente']))), [customer(map), ticket()]);
+ assert.deepStrictEqual(relationships[0].lookup, { schemaName: 'new_CustomerId' });
+});
+
+test('ADO 6691205 download: a single-language lookup label is not "the default" of a localized parent', async () => {
+ // A rebuild writes the parent's whole map; this lookup carries one language, so they are not the same
+ // label and the one it has is kept.
+ const map = { 1033: 'Customer', 3082: 'Cliente' };
+ const { relationships } = await read(makeSdk(ticketToCustomer(label([1033, 'Customer']))), [customer(map), ticket()]);
+ assert.strictEqual(relationships[0].lookup.displayName, 'Customer');
+});
+
+test('ADO 6691205 download: a lookup to a stock table compares with the label the environment reports for it', async () => {
+ const stock = (lookupLabel) => makeSdk({
+ m2o: { new_ticket: [rel({ SchemaName: 'new_systemuser_new_ticket', ReferencedEntity: 'systemuser', ReferencingEntity: 'new_ticket', ReferencingAttribute: 'new_agentid' })] },
+ lookups: { new_ticket: [{ LogicalName: 'new_agentid', SchemaName: 'new_AgentId', DisplayName: lookupLabel, Targets: ['systemuser'] }] },
+ parents: { systemuser: label([1033, 'User'], [1036, 'Utilisateur']) },
+ });
+ const same = await read(stock(label([1033, 'User'])), [ticket()]);
+ assert.deepStrictEqual(same.relationships[0].lookup, { schemaName: 'new_AgentId' }, 'equal at the lookup\'s own language');
+ const french = await read(stock(label([1036, 'Utilisateur'])), [ticket()]);
+ assert.deepStrictEqual(french.relationships[0].lookup, { schemaName: 'new_AgentId' }, 'the comparison is made in the language the lookup was written in');
+ const other = await read(stock(label([1033, 'Assigned agent'])), [ticket()]);
+ assert.strictEqual(other.relationships[0].lookup.displayName, 'Assigned agent');
+});
+
+test('ADO 6691205 download: a stock parent whose label could not be read keeps the lookup\'s label', async () => {
+ const sdk = makeSdk({
+ m2o: { new_ticket: [rel({ SchemaName: 'new_systemuser_new_ticket', ReferencedEntity: 'systemuser', ReferencingEntity: 'new_ticket', ReferencingAttribute: 'new_agentid' })] },
+ lookups: { new_ticket: [{ LogicalName: 'new_agentid', SchemaName: 'new_AgentId', DisplayName: label([1033, 'User']), Targets: ['systemuser'] }] },
+ });
+ const { relationships } = await read(sdk, [ticket()]);
+ assert.strictEqual(relationships[0].lookup.displayName, 'User', 'no label to compare with, so nothing is assumed');
+});
+
+test('ADO 6691205 download: without the downloaded tables to compare against, every label is written as before', async () => {
+ const { relationships } = await readRelationships(makeSdk(ticketToCustomer(label([1033, 'Customer']))), ['new_customer', 'new_ticket'], 'new');
+ assert.strictEqual(relationships[0].lookup.displayName, 'Customer');
+});
+
+test('ADO 6691205 download: a minimal downloaded relationship validates and rebuilds with the same label', async () => {
+ const { relationships } = await read(makeSdk(ticketToCustomer(label([1033, 'Customer']))), [customer('Customer'), ticket()]);
+ const spec = {
+ solution: { uniqueName: 'S', publisherPrefix: 'new' },
+ app: { name: 'A' },
+ entities: [
+ { schemaName: 'new_customer', displayName: 'Customer', primaryAttribute: { schemaName: 'new_name' }, columns: [] },
+ { schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name' }, columns: [] },
+ ],
+ relationships,
+ };
+ const checked = validateAppSpec(spec, { profile: 'structural' });
+ assert.deepStrictEqual(checked.errors.filter((e) => /lookup|relationship/i.test(e)), []);
+ assert.strictEqual(lookupColumnsFor(spec, 'new_ticket')[0].displayName, 'Customer');
+});
diff --git a/plugins/model-apps/scripts/tests/map-limit.test.js b/plugins/model-apps/scripts/tests/map-limit.test.js
index 5e80fb189..e5a6f94c0 100644
--- a/plugins/model-apps/scripts/tests/map-limit.test.js
+++ b/plugins/model-apps/scripts/tests/map-limit.test.js
@@ -41,3 +41,55 @@ test('mapLimit rethrows the first failure when several in-flight items fail', as
(err) => err === first,
);
});
+
+// verify and download fan out READS whose report must not depend on which response came back first.
+test('the runner and the module export are one limiter', () => {
+ assert.strictEqual(require('../lib/entity-provision.js').mapLimit, mapLimit);
+});
+
+test('firstInOrder rethrows the failure of the lowest-indexed item, not the first to settle', async () => {
+ const low = new Error('item 0 (slow to fail)');
+ const high = new Error('item 1 (fails first)');
+ const started = [];
+ await assert.rejects(
+ mapLimit(['slow', 'quick', 'never'], 2, async (item) => {
+ started.push(item);
+ if (item === 'slow') { await sleep(40); throw low; }
+ await sleep(2);
+ throw high;
+ }, { firstInOrder: true }),
+ (err) => err === low,
+ );
+ assert.deepStrictEqual(started, ['slow', 'quick'], 'nothing is started after a failure');
+});
+
+test('without firstInOrder the same two failures report the first to settle (the build contract)', async () => {
+ const low = new Error('item 0 (slow to fail)');
+ const high = new Error('item 1 (fails first)');
+ await assert.rejects(
+ mapLimit(['slow', 'quick'], 2, async (item) => {
+ if (item === 'slow') { await sleep(40); throw low; }
+ await sleep(2);
+ throw high;
+ }),
+ (err) => err === high,
+ );
+});
+
+test('firstInOrder keeps the output order and the drain-before-report rule', async () => {
+ const out = await mapLimit([30, 5, 15], 2, async (ms, idx) => { await sleep(ms); return idx; }, { firstInOrder: true });
+ assert.deepStrictEqual(out, [0, 1, 2]);
+ const events = [];
+ const failure = new Error('item 1');
+ await assert.rejects(
+ mapLimit(['ok-slow', 'fails', 'later'], 2, async (item) => {
+ if (item === 'fails') { await sleep(2); events.push('failed'); throw failure; }
+ if (item === 'ok-slow') { await sleep(40); events.push('slow landed'); return item; }
+ events.push('started after the failure');
+ return item;
+ }, { firstInOrder: true }),
+ (err) => err === failure,
+ );
+ events.push('reported');
+ assert.deepStrictEqual(events, ['failed', 'slow landed', 'reported']);
+});
diff --git a/plugins/model-apps/scripts/tests/oracle-loaders.test.js b/plugins/model-apps/scripts/tests/oracle-loaders.test.js
new file mode 100644
index 000000000..700e03dde
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/oracle-loaders.test.js
@@ -0,0 +1,48 @@
+'use strict';
+// The oracle loaders (helpers/typescript-oracle.js). A parser or a lexer that a test is pointed at by an environment variable must load: the CI job that runs the oracle tests (test-model-apps-lexer-oracles) sets the three
+// variables, and a wrong path or a renamed file must fail the job, not skip every oracle test and pass. Unset, a loader answers null and its tests skip.
+const { test } = require('node:test');
+const assert = require('node:assert');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const HELPER = path.join(__dirname, 'helpers', 'typescript-oracle.js');
+const VARIABLES = ['TYPESCRIPT_ORACLE_PATH', 'BABEL_ORACLE_PATH', 'BASE_LIB_PATH'];
+const LOADERS = [['loadTypescriptOracle', 'TYPESCRIPT_ORACLE_PATH'], ['loadBabelOracle', 'BABEL_ORACLE_PATH'], ['loadBaseLexer', 'BASE_LIB_PATH']];
+
+// One loader in a process of its own, with the three variables removed from the environment and `env` added: the loaders read it when they are called, and a child keeps the test from changing what the tests that run after it see.
+function load(loader, env) {
+ const script = `const h = require(${JSON.stringify(HELPER)}); try { const r = h.${loader}(); console.log(JSON.stringify({ loaded: r === null ? null : typeof r })); } catch (e) { console.log(JSON.stringify({ error: e.message })); }`;
+ const base = { ...process.env };
+ for (const name of VARIABLES) delete base[name];
+ const result = spawnSync(process.execPath, ['-e', script], { env: { ...base, ...env }, encoding: 'utf8' });
+ assert.strictEqual(result.status, 0, result.stderr);
+ return JSON.parse(result.stdout.trim());
+}
+
+test('an oracle that no variable points at loads as null, so the tests that need it skip', () => {
+ for (const [loader] of LOADERS) assert.deepStrictEqual(load(loader, {}), { loaded: null }, loader);
+ // An empty variable is unset.
+ for (const [loader, variable] of LOADERS) assert.deepStrictEqual(load(loader, { [variable]: '' }), { loaded: null }, `${loader} with ${variable} empty`);
+});
+
+test('an oracle that a variable points at and that does not load throws, naming the variable, so the tests that need it fail', () => {
+ const missing = path.join(__dirname, 'no-such-oracle');
+ for (const [loader, variable] of LOADERS) {
+ const result = load(loader, { [variable]: missing });
+ assert.strictEqual(result.loaded, undefined, `${loader} did not load`);
+ assert.ok(result.error.startsWith(`${variable} is set to `), `${loader}: ${result.error}`);
+ assert.ok(result.error.includes('does not load as'), `${loader}: ${result.error}`);
+ }
+ // A directory that holds no package, where a package is wanted, and a directory without the lexer's file, are the same.
+ assert.ok(load('loadTypescriptOracle', { TYPESCRIPT_ORACLE_PATH: path.join(__dirname, 'helpers') }).error.startsWith('TYPESCRIPT_ORACLE_PATH is set to '));
+ assert.ok(load('loadBaseLexer', { BASE_LIB_PATH: path.join(__dirname, 'helpers') }).error.startsWith('BASE_LIB_PATH is set to '));
+});
+
+test('an oracle that a variable points at and that loads is returned', () => {
+ // Any module stands for a package here; the lexer's own scripts/lib stands for the base.
+ const module = path.join(__dirname, 'helpers', 'misread-page.js');
+ assert.deepStrictEqual(load('loadTypescriptOracle', { TYPESCRIPT_ORACLE_PATH: module }), { loaded: 'object' });
+ assert.deepStrictEqual(load('loadBabelOracle', { BABEL_ORACLE_PATH: module }), { loaded: 'object' });
+ assert.deepStrictEqual(load('loadBaseLexer', { BASE_LIB_PATH: path.join(__dirname, '..', 'lib') }), { loaded: 'object' });
+});
diff --git a/plugins/model-apps/scripts/tests/pageref-resolver.test.js b/plugins/model-apps/scripts/tests/pageref-resolver.test.js
index 4d9712af3..81589dbbf 100644
--- a/plugins/model-apps/scripts/tests/pageref-resolver.test.js
+++ b/plugins/model-apps/scripts/tests/pageref-resolver.test.js
@@ -8,7 +8,9 @@ const path = require('node:path');
const fs = require('node:fs');
const vm = require('node:vm');
const { execFileSync } = require('node:child_process');
-const { loadTypescriptOracle } = require('./helpers/typescript-oracle.js');
+const { loadTypescriptOracle, loadBaseLexer } = require('./helpers/typescript-oracle.js');
+const { tokenVocabulary } = require('./helpers/angle-frames.js');
+const { RESOLVED_PAGES, REFUSED_PAGES, HIDDEN_CLOSING_TAG_PAGES } = require('./helpers/live-shaped-pages.js');
const { OBJECT_DIVISION_PAGE, MISREAD_PAGES, HIDDEN_CALL_PAGE, PREFIX_INCREMENT_PAGE, TEMPLATE_LINE_PAGE, JSX_TEXT_PAGE, ELEMENT_AFTER_OPERATOR_PAGES, ELEMENT_LOOKALIKE_PAGES, ELEMENT_PAGE_TOKEN_LINE, FUNCTION_TYPE_PAGES, FUNCTION_TYPE_CALL_LINE, LONG_KEY, lookBehindPage, runnable } = require('./helpers/misread-page.js');
const { AMBIGUITY_KINDS } = require('../lib/source-literals.js');
const { pageStructureProblems } = require('../lib/page-structure.js');
@@ -1126,7 +1128,7 @@ test('a navigateTo spelling whose callee is not the callee, or whose object is n
// The `(` that opens a parenthesised callee begins a navigation call only after a token that cannot END a callable operand. The
// tokens that can are many and easy to miss — `!` (a non-null assertion), `>` (a generic instantiation), a back-tick (a tagged
// template), `}` (a function expression) — so the tokens that may stand there are listed, and everything else is refused:
-// the start of the source ; { ( [ , : ? (a ternary) any operator ending in = => && || ??
+// the start of the source ; { ( [ , : ? (a ternary) any operator ending in = => && || ?? the keyword `return` on the line of the `(`
// What a call or a member access would continue is then refused whether or not anyone thought of it.
test('a parenthesised callee is a call only after a token on the allowlist', () => {
const callee = `(navigateTo)(${OBJ})`;
@@ -1136,7 +1138,9 @@ test('a parenthesised callee is a call only after a token on the allowlist', ()
['x = ', ';'], ['x == ', ''], ['x === ', ''], ['x != ', ''], ['x !== ', ''], ['x += ', ''], ['x -= ', ''], ['x *= ', ''], ['x /= ', ''], ['x %= ', ''],
['x <= ', ''], ['x >= ', ''], ['x **= ', ''], ['x <<= ', ''], ['x >>= ', ''], ['x >>>= ', ''], ['x &= ', ''], ['x |= ', ''], ['x ^= ', ''],
['x &&= ', ''], ['x ||= ', ''], ['x ??= ', ''], ['() => ', ''], ['async (x) => ', ''], ['a && ', ''], ['a || ', ''], ['a ?? ', ''],
- ['\n', ''], ['/* c */ ', ''], ['// c\n', ''], ['void 0, ', '']];
+ ['\n', ''], ['/* c */ ', ''], ['// c\n', ''], ['void 0, ', ''],
+ // The keyword `return`, on the line of the `(`: an expression starts right after it (see the test below for what else is checked).
+ ['return ', ''], ['function f() { return ', ' }'], ['if (x) return ', ''], ['switch (x) { case 1: return ', ' }']];
for (const [before, after] of allowed) {
const code = `${before}${callee}${after}`;
assert.deepStrictEqual(extractNavTargets(code).map((t) => [t.kind, t.key]), [['pageref', 'detail']], JSON.stringify(code));
@@ -1146,7 +1150,7 @@ test('a parenthesised callee is a call only after a token on the allowlist', ()
// keyword, `)`, `]`, `.`, `?.`, `}` (also at the end of a block), `!`, a `>` that is not `=>`, a quote or a back-tick, `++`/`--`,
// and the operators that are not on the list.
const refused = ['x', 'x ', 'foo', 'foo(a)', 'foo[0]', 'foo.', 'foo?.', 'foo?. ', '1', '$', '_', 'αβ', 'a)', 'a]',
- 'new ', 'await ', 'return ', 'typeof ', 'void ', 'while ', 'else ', 'in ', 'of ', 'delete ', 'throw ', 'yield ', 'case ', 'do ', 'instanceof ',
+ 'new ', 'await ', 'typeof ', 'void ', 'while ', 'else ', 'in ', 'of ', 'delete ', 'throw ', 'yield ', 'case ', 'do ', 'instanceof ',
'{}', 'x = {}', '{ a(); }\n', 'function f() {}\n', 'if (a) { }\n', 'function () { return f; }',
'a!', 'a! ', 'factory!', 'a<unknown>', 'factory<unknown>', 'a > ', 'a >> ', 'a >>> ',
'`tag`', '`x${y}`', 'tag`x`', '"s"', "'s'", 'a++', 'a--', 'a++ ', 'a-- ',
@@ -1166,6 +1170,171 @@ test('a parenthesised callee is a call only after a token on the allowlist', ()
assert.deepStrictEqual(extractNavTargets(inTemplate(`x = ${callee}`)).map((t) => [t.kind, t.key]), [['pageref', 'detail']], 'after an `=` inside the body it is a call again');
});
+// ─── `return (navigateTo)({ … })` ─────────────────────────────────────────────────────────────────────────────────
+//
+// After the keyword `return` an expression starts, so a parenthesised callee there is the callee of a call (followsReturnKeyword). The keyword has to be the whole word, with the `(` on its line — a line
+// break after `return` ends the statement, `return;`, and the call after it is one that never runs — and no `.` may stand before it, which makes it a member's name. `await` and `yield` are not on the
+// list: outside an async function and a generator they are identifiers, and TypeScript parses `function f() { await (navigateTo)({ … }) }` as a call of a function named `await`.
+const RETURN_CALLEE = `(navigateTo)(${OBJ})`;
+const RETURNS_THAT_NAVIGATE = [
+ ['return ', ''], ['return', ''], ['return\t', ''], ['return\u00a0', ''], ['return\u0085', ''], ['return\u200b', ''], ['return\ufeff', ''], ['return /* c */ ', ''], ['return/* c */', ''], ['return /* a */ /* b */ ', ''],
+ ['function f() { return ', ' }'], ['function f() {\n return ', '\n}'], ['function f() {\n x();\n return ', ';\n}'], ['if (x) return ', ''], ['if (x)return ', ''], ['if (x) {} else return ', ''],
+ ['do return ', '; while (x)'], ['switch (x) { case 1: return ', ' }'], ['lbl: return ', ''], [';return ', ''], ['{return ', '}'], ['x()\nreturn ', ''], ['x = 1 // c\nreturn ', ''],
+ ['const f = () => { return ', ' };'], ['async function f() { return ', ' }'], ['function* g() { return ', ' }'], ['const o = { m() { return ', ' } };'], ['class C { m() { return ', ' } }'],
+ ['function f() { return ', '.then(r) }'], ['function f() { return ', '?.then(r) }'], ['function f() { return (', ') }'], ['function f() { return Xrm.Navigation, ', ' }'],
+];
+// A line terminator of any kind between `return` and the `(` — a comment that holds one included — ends the statement there (ECMA-262 §12.10.1, a restricted production): TypeScript parses the call after
+// it as a statement of its own, and the page does not navigate.
+const RETURNS_AFTER_A_LINE_BREAK = ['return\n', 'return\r\n', 'return\r', 'return\u2028', 'return\u2029', 'return // c\n', 'return /* c\n */ ', 'return /* a */ /* b\n */ ', 'return\n\n ', 'return /* c */\n'];
+// A word that is not the keyword: a member named `return`, and names that end or start with it, with an escape in them, or beyond ASCII.
+const NOT_THE_KEYWORD_RETURN = ['a.return ', 'a?.return ', 'a . return ', 'a.\nreturn ', 'a?.\n/* c */ return ', 'a./* c */return ', 'this.return ', 'a.b.return ', 'f().return ', 'a[0].return ', 'a!.return ',
+ 'xreturn ', '$return ', '_return ', 'return1 ', 'returns ', 'returned ', 'Return ', 'RETURN ', 'éreturn ', 'returné ', 'αreturn ', 'return$ ', 'return_ ', '\\u0061return ', '\\u{61}return ', 'r\\u0065turn ',
+ '\\u0072eturn ', 'return\\u0061 ', 'x\\u{61}return ', 'a.#return ', '#return ', '}return ', '1.return '];
+
+// What TypeScript makes of the call whose first argument is the object literal that holds the token: { callee, statement } — the callee with its parentheses stripped, as text, and the kind of the statement the
+// call stands in (the nearest one that holds it) — or null where the program does not parse or has no such call.
+function callReading(ts, code) {
+ const source = ts.createSourceFile('page.tsx', code, ts.ScriptTarget.ES2022, true, ts.ScriptKind.TSX);
+ if (source.parseDiagnostics.length > 0) return null;
+ let found = null;
+ const visit = (node) => {
+ if (found === null && ts.isCallExpression(node) && node.arguments.length > 0 && ts.isObjectLiteralExpression(node.arguments[0]) && node.arguments[0].getText(source).includes('PAGEREF_detail')) {
+ let callee = node.expression;
+ while (ts.isParenthesizedExpression(callee)) callee = callee.expression;
+ let statement = node.parent;
+ while (statement && !/Statement$/.test(ts.SyntaxKind[statement.kind])) statement = statement.parent;
+ found = { callee: callee.getText(source), statement: statement ? ts.SyntaxKind[statement.kind] : null };
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ return found;
+}
+const navigates = (code) => extractNavTargets(code).some((target) => target.kind === 'pageref' && target.key === 'detail');
+
+test('a parenthesised callee after `return` is a call when the `(` is on its line; after a line break, a `.` or in a longer word it is not', (t) => {
+ for (const [before, after] of RETURNS_THAT_NAVIGATE) {
+ const code = `${before}${RETURN_CALLEE}${after}`;
+ assert.deepStrictEqual(extractNavTargets(code).map((target) => [target.kind, target.key]), [['pageref', 'detail']], JSON.stringify(code));
+ assert.deepStrictEqual(strayPageRefs(code), [], JSON.stringify(code));
+ assert.strictEqual(resolveOne(code).deployment.get('x'), code.replace('"PAGEREF_detail"', '"gp-detail"'), `${JSON.stringify(code)}: the token is resolved`);
+ }
+ for (const before of [...RETURNS_AFTER_A_LINE_BREAK, ...NOT_THE_KEYWORD_RETURN]) {
+ const code = `${before}${RETURN_CALLEE}`;
+ assert.deepStrictEqual(extractNavTargets(code), [], JSON.stringify(code));
+ assert.deepStrictEqual(strayPageRefs(code).map((r) => r.token), ['PAGEREF_detail'], JSON.stringify(code));
+ assert.strictEqual(resolveOne(code).deployment.get('x'), code, `${JSON.stringify(code)}: never rewritten`);
+ }
+ // A word in a string, a template, a regex, a comment or JSX text is blank in the mask and no token.
+ for (const code of [`const s = "return ${RETURN_CALLEE}";`, `const s = \`return \${x} ${RETURN_CALLEE}\`;`, `const r = /return/ ${RETURN_CALLEE};`, `/* return */ x ${RETURN_CALLEE}`, `const e = <p>return ${RETURN_CALLEE}</p>;`]) {
+ assert.deepStrictEqual(extractNavTargets(code), [], JSON.stringify(code));
+ }
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.diagnostic('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to check the readings');
+ // TypeScript: every accepted program parses, and the call in it is a call of navigateTo, in the return statement itself.
+ for (const [before, after] of RETURNS_THAT_NAVIGATE) {
+ const code = `${before}${RETURN_CALLEE}${after}`;
+ assert.deepStrictEqual(callReading(ts, code), { callee: 'navigateTo', statement: 'ReturnStatement' }, JSON.stringify(code));
+ }
+ // After a line break the program parses and the call is a statement of its own, which `return;` precedes; and a word that is not the keyword is a call of another function, or no program.
+ for (const before of RETURNS_AFTER_A_LINE_BREAK) {
+ assert.deepStrictEqual(callReading(ts, `${before}${RETURN_CALLEE}`), { callee: 'navigateTo', statement: 'ExpressionStatement' }, JSON.stringify(before));
+ }
+ for (const before of NOT_THE_KEYWORD_RETURN) {
+ const reading = callReading(ts, `${before}${RETURN_CALLEE}`);
+ assert.ok(reading === null || reading.callee !== 'navigateTo', `${JSON.stringify(before)}: TypeScript reads ${JSON.stringify(reading)}`);
+ }
+});
+
+// The page an author writes: a handler that returns the navigation, and a component that calls it. The callee is parenthesised (a generator of pages may spell it so), and the call is the whole `return` statement,
+// so the token is resolved and nothing is left over; after a line break, where `return;` is a statement of its own, the same page is refused.
+const returnPage = (statement) => `import * as React from "react";\n\nexport default function DetailsPage() {\n const openDetail = () => {\n ${statement}\n };\n return (\n <div>\n <button onClick={openDetail}>Open</button>\n </div>\n );\n}\n`;
+test('an everyday page that returns a parenthesised navigation call resolves: the call is read, the token is resolved, no token is left and the page is complete', () => {
+ const page = returnPage(`return (navigateTo)({ pageType: "generative", pageId: "PAGEREF_detail" });`);
+ assert.deepStrictEqual(strayPageRefs(page), []);
+ assert.deepStrictEqual(navReferencedKeys(page), ['detail']);
+ assert.deepStrictEqual(pageStructureProblems(page), []);
+ assert.strictEqual(navigationFrontier(page), null, 'no guess is named');
+ const { deployment, unresolved, residual } = resolveOne(page);
+ assert.strictEqual(deployment.get('x'), page.replace('"PAGEREF_detail"', '"gp-detail"'));
+ assert.deepStrictEqual([unresolved, residual].map((found) => found.length), [0, 0]);
+ // A line break after `return` makes the call a statement that never runs; and `await` is a name outside an async function: both are refused, and the token halts the build as stray.
+ for (const statement of ['return\n (navigateTo)({ pageType: "generative", pageId: "PAGEREF_detail" });', 'await (navigateTo)({ pageType: "generative", pageId: "PAGEREF_detail" });']) {
+ const refused = returnPage(statement);
+ assert.deepStrictEqual(strayPageRefs(refused).map((found) => found.token), ['PAGEREF_detail'], JSON.stringify(statement));
+ assert.strictEqual(resolveOne(refused).deployment.get('x'), refused, `${JSON.stringify(statement)}: never rewritten`);
+ }
+});
+
+// The claim, as a property: wherever the lexer reads `(navigateTo)({ … })` after `return` as a navigation call, TypeScript — for the programs it parses — reads the same call, with navigateTo as its callee and the
+// object as its argument. Every punctuator and keyword TypeScript has stands in front of the `return`, adjacent to it, after a space, a line break and a comment; every kind of white space TypeScript skips stands
+// between `return` and the `(`; and each program is put in the places a statement stands, a class or an interface stands, an object literal, a template and JSX.
+test('sweep (TypeScript parser): a parenthesised callee after `return` that the lexer reads as a call is a call of navigateTo to TypeScript', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const frames = ['function f() { @ }', '@', '{ @ }', 'const o = { @ };', 'class C { @ }', 'interface I { @ }', 'type T = { @ };', 'if (a) @', 'if (a) {} else @', 'switch (a) { case 1: @ }', 'lbl: @', 'async function f() { @ }',
+ 'function* g() { @ }', 'x = @', '`${@}`', 'const e = <p>@</p>;', 'const e = <p a={@}/>;', 'class C { m() { @ } }', 'enum E { @ }', 'const o = { m() { @ } };'];
+ const before = [...tokenVocabulary(ts), 'x', '$', '_', 'é', '1', '.5', '\\u0061', 'x\\u{61}', '#', 'a.', 'a?.', 'a . ', 'a.\n', '"s"', '`t`', '/re/'];
+ const separators = ['', ' ', '\n', '/*c*/'];
+ const gaps = ['', ' ', '\t', '\u00a0', '\u0085', '\u200b', '\ufeff', '/*c*/', '\n', '\r\n', '\u2028', '/*\n*/', '//c\n'];
+ const stats = { programs: 0, valid: 0, accepted: 0, otherCallee: 0, lineBreak: 0, refusedNavigations: 0 };
+ const unsound = [];
+ for (const frame of frames) {
+ for (const prefix of before) {
+ for (const separator of separators) {
+ for (const gap of gaps) {
+ const call = `${prefix}${separator}return${gap}${RETURN_CALLEE}`;
+ const code = `declare const a: any, navigateTo: any;\n${frame.replace('@', call)}\n`;
+ stats.programs += 1;
+ const reading = callReading(ts, code);
+ if (reading === null) continue;
+ stats.valid += 1;
+ if (reading.callee !== 'navigateTo') stats.otherCallee += 1;
+ if (navigates(code)) {
+ stats.accepted += 1;
+ if (reading.callee !== 'navigateTo') unsound.push(JSON.stringify(call));
+ } else if (reading.callee === 'navigateTo') {
+ stats.refusedNavigations += 1;
+ if (/[\n\r\u2028\u2029]/.test(gap)) stats.lineBreak += 1;
+ }
+ }
+ }
+ }
+ }
+ t.diagnostic(`${stats.programs} programs, ${stats.valid} valid to TypeScript: ${stats.accepted} read as a navigation (TypeScript agrees on all but ${unsound.length}), ${stats.otherCallee} have another callee in TypeScript; `
+ + `${stats.refusedNavigations} navigations of TypeScript are refused, ${stats.lineBreak} of them for a line break between \`return\` and the \`(\``);
+ assert.deepStrictEqual(unsound.slice(0, 5), [], 'a call read as navigateTo that TypeScript reads with another callee');
+ assert.ok(stats.valid >= 10000 && stats.accepted >= 5000 && stats.otherCallee >= 5000, `${stats.valid} valid, ${stats.accepted} accepted, ${stats.otherCallee} with another callee: the sweep proves little`);
+ // What stays refused is the line break (and a keyword that the lexer cannot tell from a name: a `.` before it, a letter or a digit glued to it).
+ assert.ok(stats.lineBreak > 0 && stats.refusedNavigations >= stats.lineBreak, 'the refused navigations include the line breaks');
+});
+
+// `await` and `yield` before a parenthesised callee stay refused. TypeScript parses them as keywords inside an async function and a generator, and as identifiers anywhere else, where the call is `await(navigateTo)` and
+// its result is called with the object: the same text is a navigation in one function and no navigation in the next, and the lexer does not track the function. JavaScript reads them the same way.
+test('`await` and `yield` before a parenthesised callee are refused: they are identifiers outside an async function and a generator', (t) => {
+ const programs = [
+ ['an async function', 'async function f() { await ', ' }', 'navigateTo'], ['a plain function', 'function f() { await ', ' }', 'await (navigateTo)'], ['an async arrow', 'const f = async () => { await ', ' };', 'navigateTo'],
+ ['a plain arrow, in an async function', 'async function f() { const g = () => { await ', ' }; }', 'await (navigateTo)'], ['a plain function, in an async function', 'async function f() { function g() { await ', ' } }', 'await (navigateTo)'],
+ ['an async arrow with an expression body', 'const f = async () => await ', ';', 'navigateTo'], ['a plain arrow with an expression body, in an async function', 'async function f() { const g = () => await ', '; }', 'await (navigateTo)'],
+ ['a generator', 'function* g() { yield ', ' }', 'navigateTo'], ['a plain function', 'function g() { yield ', ' }', 'yield (navigateTo)'], ['a plain arrow, in a generator', 'function* g() { const h = () => { yield ', ' }; }', 'yield (navigateTo)'],
+ ];
+ const ts = loadTypescriptOracle();
+ for (const [what, before, after, callee] of programs) {
+ const code = `${before}${RETURN_CALLEE}${after}`;
+ assert.deepStrictEqual(extractNavTargets(code), [], `${what}: ${JSON.stringify(code)}`);
+ assert.deepStrictEqual(strayPageRefs(code).map((r) => r.token), ['PAGEREF_detail'], what);
+ if (ts) assert.strictEqual(callReading(ts, code).callee, callee, `${what}: the callee TypeScript reads`);
+ }
+ if (!ts) t.diagnostic('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to check the readings');
+ // JavaScript: outside an async function `await (navigateTo)(…)` calls a function named `await`, which does not exist here, and inside one it calls navigateTo.
+ const calls = [];
+ const sandbox = { navigateTo: (arg) => calls.push(arg.pageId) };
+ vm.runInNewContext(`async function f() { await ${RETURN_CALLEE}; } f();`, sandbox);
+ assert.deepStrictEqual(calls, ['PAGEREF_detail'], 'in an async function');
+ assert.throws(() => vm.runInNewContext(`function f() { await ${RETURN_CALLEE}; } f();`, sandbox), /await is not defined/, 'in a plain function');
+ assert.deepStrictEqual(calls, ['PAGEREF_detail'], 'and nothing more was called');
+});
+
test('spellings that are not a navigateTo call with an object literal are not mistaken for one', () => {
const notCalls = {
'a different member name': `Xrm.Navigation["navigateToX"](${OBJ})`,
@@ -1832,7 +2001,7 @@ test('the page whose "/" after an object literal hid a call is refused, naming t
test('each misread page is refused at its first guess: every token at or after it, or in a call that reaches it, is stray, and nothing there is rewritten', () => {
assert.deepStrictEqual(Object.keys(MISREAD_PAGES), [
'brace', 'paren', 'keyword', 'identifier', 'angle', 'jsx-type-arguments', 'newline', 'generic', 'generic, in JSX text',
- 'generic, with await', 'generic, with yield', 'operator, after ">="',
+ 'generic, with await', 'generic, with yield', 'generic, a regex after a line comment', 'generic, a regex that holds a closing tag after a line comment', 'operator, after ">="',
'operator, after ">>=" that ends type arguments', 'operator, after ">>>=" that ends nested type arguments', 'operator, after ">>=" that ends the type arguments of satisfies', 'jsx-attribute',
'inside an options object',
]);
@@ -2159,6 +2328,83 @@ test('a call or construct signature with no return type is code: the token in th
}
});
+// ─── Pages shaped like a generative page's own text ────────────────────────────────────────────────────────────────────────────────────────────────────
+//
+// The `PAGEREF_` tokens of a page as TypeScript reads it: those in the `pageId` of the options object of a call are real, every other one — in a string, a template, a regex, a comment, text — is data. Null where the page
+// does not parse (a diagnostic of the parser; the type checker is not asked, as it rejects an initializer in a type that the parser accepts).
+function pageIdTokens(ts, code) {
+ const source = ts.createSourceFile('page.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ if (source.parseDiagnostics.length > 0) return null;
+ const spans = [];
+ const visit = (node) => {
+ if (ts.isCallExpression(node) && node.arguments.length > 0 && ts.isObjectLiteralExpression(node.arguments[0])) {
+ for (const property of node.arguments[0].properties) {
+ if (ts.isPropertyAssignment(property) && ts.isIdentifier(property.name) && property.name.text === 'pageId' && ts.isStringLiteralLike(property.initializer)) spans.push([property.initializer.getStart(source), property.initializer.getEnd()]);
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ const tokens = [...code.matchAll(/PAGEREF_[A-Za-z0-9_-]+/g)].map((match) => match.index);
+ const real = tokens.filter((at) => spans.some(([from, to]) => at >= from && at < to));
+ return { real, data: tokens.filter((at) => !real.includes(at)) };
+}
+
+// A component whose text holds prose in parentheses — a note, a hint, a URL on a line of its own, a path that starts a line, a bracketed word, a link with a URL, an apostrophe or a comment opener in its text — or a callee in
+// parentheses, with one real call in a handler. The text is JSX text, or no type's members, for certain: the page is read right, the one call is rewritten, and no token is left.
+test('a page with prose, a URL or a path after a parenthesis in JSX text is read for certain: the one real call is rewritten, and nothing else', (t) => {
+ assert.strictEqual(RESOLVED_PAGES.length, 22);
+ const ts = loadTypescriptOracle();
+ for (const { name, code } of RESOLVED_PAGES) {
+ assert.strictEqual(navigationFrontier(code), null, `${name}: no guess is involved`);
+ assert.deepStrictEqual(extractNavTargets(code).map((target) => [target.kind, target.key, 'afterFrontier' in target]), [['pageref', 'detail', false]], name);
+ assert.deepStrictEqual([strayPageRefs(code), navMalformedRefs(code), pageStructureProblems(code)], [[], [], []], name);
+ const { deployment, unresolved, residual } = resolveOne(code);
+ const resolved = deployment.get('x');
+ assert.strictEqual(resolved, code.replace('"PAGEREF_detail"', '"gp-detail"'), `${name}: the token of the call is the one rewritten`);
+ assert.strictEqual(resolved.split('gp-detail').length - 1, 1, `${name}: one id is written`);
+ assert.deepStrictEqual([unresolved, residual], [[], []], name);
+ if (ts) {
+ const reading = pageIdTokens(ts, code);
+ assert.ok(reading, `${name}: valid TSX`);
+ assert.deepStrictEqual([reading.real.length, reading.data.length], [1, 0], `${name}: TypeScript reads one real call, and no token that is data`);
+ }
+ }
+ if (!ts) t.diagnostic('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to check the pages');
+});
+
+// A call signature whose default value has a `/` after a line comment, and one whose type has a member named by a number with a signed exponent, a nested element in an expression, or a nested tag that is no element (type
+// arguments, a comparison, the type parameters of a signature): each holds a token that is data in a string, a template or a regex, which a type holds the closing tag of its head in. The head may be the element that ends
+// there, so the lexer names the guess at the `<`: both tokens — the data and the real call that follows the head — are stray, and nothing is rewritten. (An element read as the head took the token that is data for a call,
+// and rewrote it.)
+test('a signature whose text can hold the closing tag of its head after a number name, a nested tag or a `/` after a comment is a guess: no token in the page is rewritten', (t) => {
+ const ts = loadTypescriptOracle();
+ const pages = [...REFUSED_PAGES, ...HIDDEN_CLOSING_TAG_PAGES];
+ assert.strictEqual(pages.length, 39);
+ for (const { name, code } of pages) {
+ const at = code.indexOf('<T>');
+ assert.deepStrictEqual(navigationFrontier(code), { start: at, kind: 'generic', ...positionOf(code, at) }, `${name}: the guess is named at the head`);
+ const found = strayPageRefs(code);
+ assert.deepStrictEqual(found.map((r) => r.frontier.kind), ['generic', 'generic'], `${name}: both tokens are stray, after the guess`);
+ const { deployment, unresolved, residual } = resolveOne(code);
+ assert.strictEqual(deployment.get('x'), code, `${name}: nothing is rewritten`);
+ assert.deepStrictEqual([unresolved, navMalformedRefs(code), residual.length], [[], [], 2], name);
+ if (ts) {
+ const reading = pageIdTokens(ts, code);
+ assert.ok(reading, `${name}: valid TSX`);
+ assert.deepStrictEqual([reading.real.length, reading.data.length], [1, 1], `${name}: TypeScript reads one real call and one token that is data`);
+ assert.ok(reading.data.every((token) => found.some((r) => r.start === token)), `${name}: the token that is data is stray`);
+ }
+ }
+ if (!ts) t.diagnostic('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to check the pages');
+ // The released lexer, where it is given, shows what the pages are for: it rewrites the token that is data in some of them.
+ const base = loadBaseLexer();
+ if (base) {
+ const rewritten = pages.filter(({ code }) => base.resolvePageRefs(new Map([['x', { code }]]), new Map([['detail', 'gp-detail']])).deployment.get('x').split('gp-detail').length - 1 === 2);
+ assert.ok(rewritten.length >= 8, `the released lexer rewrites the token that is data in only ${rewritten.length} of the pages`);
+ }
+});
+
// A refusal the author can act on names the construct. The page of a live run declared a navigation call that the lexer could not see — `of/2`
// is read as the start of a regex, whose `/*` opens a comment over the call — and the build said only "declared-but-absent: [detail]".
test('navigationFrontier and frontierNote name the first place the lexer guessed, and are empty for a page with none', () => {
@@ -2263,6 +2509,13 @@ test('a self-closing tag with trivia between its "/" and its ">", a regex whose
['a signature with no return type and a closing tag after it', `interface I { <T>(x) }\n${TS_DECOY_STRING('T')}\n${DETAIL_CALL}`],
['text that starts with a parenthesis and holds a slash', `const e = <p>(a), 1/2 done</p>;\n${TS_DECOY_STRING('p')}\n${DETAIL_CALL}`],
['text that starts with a parenthesis and a URL', `const e = <p>(a), see https://x.y</p>;\n${TS_DECOY_STRING('p')}\n${DETAIL_CALL}`],
+ // After an `=`, a `(`, a `[`, a `:` or an `=>` no member of a type begins, so the head is an element, whatever its text holds; and an unclosed `(` or an initializer in a line is read for what TypeScript says of it.
+ ['text that starts with a parenthesis and holds a line comment, after an `=`', `const e = <p>(a); // c </p>;\n${TS_DECOY_STRING('p')}\n${DETAIL_CALL}`],
+ ['text that starts with a parenthesis and a regex-like line, in an argument', `f(<p>(a);\n /b</p>);\n${TS_DECOY_STRING('p')}\n${DETAIL_CALL}`],
+ ['a line that opens a parenthesis, a comment, and a path', `const e = <p>(optional);\n foo( // note\n /docs</p>;\n${TS_DECOY_STRING('p')}\n${DETAIL_CALL}`],
+ ['a line that ends in an initializer, a comment, and a path', `const e = <p>(optional);\n x = // note\n /docs</p>;\n${TS_DECOY_STRING('p')}\n${DETAIL_CALL}`],
+ ['a link with a keyword attribute and a URL in its text', `const e = <p>(a); <button type="button">see https://x.y</button></p>;\n${TS_DECOY_STRING('p')}\n${DETAIL_CALL}`],
+ ['a fragment after a comma and a comment in its text', `const e = <p>(a), <>x // y</> more</p>;\n${TS_DECOY_STRING('p')}\n${DETAIL_CALL}`],
];
for (const [what, code] of pages) {
assert.strictEqual(navigationFrontier(code), null, `${what}: no guess is involved`);
@@ -2281,7 +2534,8 @@ test('a signature whose parameter list or text holds its closing tag in a string
`interface I { <T>(x: "</T>") }\n${TS_DECOY_STRING('T')}\n${DETAIL_CALL}`,
`type L = { <T>(x: '</T>'); m: 1 };\n${TS_DECOY_STRING('T')}\n${DETAIL_CALL}`,
`interface I { <T>(x /* </T> */) }\n${TS_DECOY_STRING('T')}\n${DETAIL_CALL}`,
- `const e = <p>(a); // c </p>;\n${TS_DECOY_STRING('p')}\n${DETAIL_CALL}`,
+ // Where a member of a type may begin at the head (after a `return`), the element with a comment in its text is a guess; after an `=` it is not.
+ `function g() { return <p>(a); // c </p>; }\n${TS_DECOY_STRING('p')}\n${DETAIL_CALL}`,
]) {
const frontier = navigationFrontier(code);
assert.ok(frontier && frontier.kind === 'generic', JSON.stringify(code));
diff --git a/plugins/model-apps/scripts/tests/process-runner.test.js b/plugins/model-apps/scripts/tests/process-runner.test.js
index 0aee405a7..df3d0c080 100644
--- a/plugins/model-apps/scripts/tests/process-runner.test.js
+++ b/plugins/model-apps/scripts/tests/process-runner.test.js
@@ -180,3 +180,368 @@ test('a native executable receives any argument unchanged through the runner', {
const out = runner.runSync('fakenode', ['-e', 'process.stdout.write(JSON.stringify(process.argv.slice(1)))', ...values], { encoding: 'utf8', timeout: 30000 }, { env });
assert.deepStrictEqual(JSON.parse(out), values);
});
+
+// ── killProcessTree ──────────────────────────────────────────────────────────────────────────────────────────────────────────────
+// A call that ran out of time must end the process it started AND everything under it. On Windows pac is often a `pac.cmd` shim — cmd.exe, which
+// runs pac.exe — and ending the shim alone leaves the stalled pac running. The kill goes through the runner (taskkill resolved to an absolute path,
+// never from the current directory) and never throws: the caller is already handling a failure.
+const fakeChild = (pid) => {
+ const killed = [];
+ return { pid, killed, kill: (signal) => { killed.push(signal); return true; } };
+};
+
+test('killProcessTree ends the Windows tree with taskkill /T /F, and asks the process itself to die as well', () => {
+ const runs = [];
+ const child = fakeChild(4242);
+ runner.killProcessTree(child, { platform: 'win32', run: (name, args, options) => { runs.push({ name, args, options }); return { status: 0 }; } });
+ assert.deepStrictEqual(runs.map((r) => [r.name, r.args]), [['taskkill', ['/pid', '4242', '/T', '/F']]]);
+ assert.strictEqual(runs[0].options.stdio, 'ignore');
+ assert.ok(runs[0].options.timeout > 0, 'taskkill itself is bounded');
+ assert.deepStrictEqual(child.killed, ['SIGKILL'], 'a tree kill that missed the process cannot leave it running');
+});
+
+// A recording `ps` for the POSIX tree kill: the `-A` listing is `rows` (pid, parent pid, start time), and `ps -o lstart= -p <pid>` answers with
+// `now[pid]` when given (a process that started at another time, or `null` for one that is gone), else with the listing's own start time.
+function fakePs(rows, now = {}) {
+ const runs = [];
+ const listing = rows.map(([pid, ppid, started]) => `${String(pid).padStart(5)} ${String(ppid).padStart(5)}${started ? ` ${started}` : ''}`).join('\n');
+ const run = (name, args, options) => {
+ runs.push({ name, args, options });
+ if (args[0] === '-A') return { status: 0, stdout: `${listing}\n` };
+ const pid = Number(args[args.indexOf('-p') + 1]);
+ const answer = Object.prototype.hasOwnProperty.call(now, pid) ? now[pid] : (rows.find(([p]) => p === pid) || [])[2];
+ return answer == null ? { status: 1, stdout: '' } : { status: 0, stdout: `${answer}\n` };
+ };
+ return { runs, run };
+}
+
+test('killProcessTree kills a POSIX process and every descendant ps lists under it — and nothing else', () => {
+ // PID PPID STARTED (the `=` after each name in `-o pid=,ppid=,lstart=` leaves no header line)
+ const ps = fakePs([
+ [1, 0, 'Mon Oct 12 08:00:00 2026'], [100, 1, 'Mon Oct 12 08:00:01 2026'], [4242, 100, 'Mon Oct 12 09:12:30 2026'],
+ [5000, 4242, 'Mon Oct 12 09:12:31 2026'], [5001, 5000, 'Mon Oct 12 09:12:32 2026'], [5002, 4242, 'Mon Oct 5 09:12:33 2026'],
+ [7000, 100, 'Mon Oct 12 09:12:34 2026'],
+ ]);
+ const killedPids = [];
+ const child = fakeChild(4242);
+ runner.killProcessTree(child, { platform: 'linux', run: ps.run, kill: (pid, signal) => { killedPids.push([pid, signal]); } });
+ assert.deepStrictEqual(ps.runs[0].args, ['-A', '-o', 'pid=,ppid=,lstart='], 'one listing, with each process\'s start time');
+ assert.strictEqual(ps.runs[0].options.encoding, 'utf8');
+ assert.deepStrictEqual(killedPids.map(([pid]) => pid).sort(), [5000, 5001, 5002], 'the grandchild too; not the parent, its sibling or init');
+ assert.ok(killedPids.every(([, signal]) => signal === 'SIGKILL'), 'a stalled process may ignore SIGTERM');
+ assert.deepStrictEqual(child.killed, ['SIGKILL']);
+ // The grandchild goes before the child it hangs from is gone for good: deepest first, so no process is orphaned into init half-killed.
+ assert.ok(killedPids.findIndex(([pid]) => pid === 5001) < killedPids.findIndex(([pid]) => pid === 5000));
+ // Each one is looked at again just before its signal, by itself: the pid must still name the process the listing saw. The order is the listing's
+ // breadth-first walk reversed (4242's children 5000 and 5002, then 5000's child 5001), so 5001 comes before the 5000 it hangs from.
+ assert.deepStrictEqual(ps.runs.slice(1).map((r) => r.args), [5001, 5002, 5000].map((pid) => ['-o', 'lstart=', '-p', String(pid)]));
+});
+
+// The listing is a moment old by the time each descendant is signalled. One that exited since can have its pid given to an unrelated process, and
+// SIGKILL by that number would end it — so a pid that now names a process that started at another time, or names none, is left alone.
+test('killProcessTree does not signal a descendant whose pid now names another process, or none — only one that is still the same', () => {
+ const ps = fakePs(
+ [[4242, 100, 'Mon Oct 12 09:12:30 2026'], [5000, 4242, 'Mon Oct 12 09:12:31 2026'], [5001, 4242, 'Mon Oct 12 09:12:32 2026'], [5002, 4242, 'Mon Oct 12 09:12:33 2026']],
+ { 5000: 'Mon Oct 12 09:14:02 2026', 5002: null },
+ );
+ const killed = [];
+ const child = fakeChild(4242);
+ runner.killProcessTree(child, { platform: 'linux', run: ps.run, kill: (pid) => killed.push(pid) });
+ assert.deepStrictEqual(killed, [5001], '5000 now started later (its pid was given out again) and 5002 is gone');
+ assert.deepStrictEqual(child.killed, ['SIGKILL'], 'the child itself is still ended');
+ // A recheck that throws, or a listing that printed no start time (a ps that ignored lstart), signals nothing but the child either.
+ for (const run of [
+ (name, args) => (args[0] === '-A' ? { status: 0, stdout: ' 4242 100 Mon Oct 12 09:12:30 2026\n 5000 4242 Mon Oct 12 09:12:31 2026\n' } : (() => { throw new Error('spawn ps ENOENT'); })()),
+ (name, args) => (args[0] === '-A' ? { status: 0, stdout: ' 4242 100\n 5000 4242\n' } : { status: 0, stdout: '' }),
+ ]) {
+ const other = fakeChild(4242);
+ const signalled = [];
+ assert.doesNotThrow(() => runner.killProcessTree(other, { platform: 'linux', run, kill: (pid) => signalled.push(pid) }));
+ assert.deepStrictEqual(signalled, []);
+ assert.deepStrictEqual(other.killed, ['SIGKILL']);
+ }
+});
+
+test('startTimes reads each pid\'s start time from a ps listing as one-spaced text, and none from a line without one', () => {
+ const text = [' 1 0 Mon Oct 12 08:00:00 2026', ' 4242 100 Mon Oct 5 09:12:30 2026 ', '\t5000\t4242', 'PID PPID STARTED', ''].join('\r\n');
+ const started = runner.startTimes(text);
+ assert.strictEqual(started.get(1), 'Mon Oct 12 08:00:00 2026');
+ assert.strictEqual(started.get(4242), 'Mon Oct 5 09:12:30 2026', 'runs of spaces are one, as the recheck reads them');
+ assert.strictEqual(started.has(5000), false);
+ assert.strictEqual(runner.startTimes(undefined).size, 0);
+ // The same listing still gives the tree.
+ assert.deepStrictEqual(runner.descendantPids(100, text), [4242, 5000]);
+});
+
+test('killProcessTree still ends the process when taskkill or ps fails, throws or is absent, and never throws', () => {
+ for (const [platform, run] of [
+ ['win32', () => ({ status: 128, stdout: '' })],
+ ['win32', () => { throw new Error('spawn taskkill ENOENT'); }],
+ ['win32', () => ({ status: null, error: new Error('timed out') })],
+ ['linux', () => ({ status: 1, stdout: '' })],
+ ['linux', () => { throw new Error('spawn ps ENOENT'); }],
+ ['linux', () => ({ status: 0, stdout: 'not a process listing' })],
+ ]) {
+ const child = fakeChild(4242);
+ const kills = [];
+ assert.doesNotThrow(() => runner.killProcessTree(child, { platform, run, kill: (pid) => kills.push(pid) }));
+ assert.deepStrictEqual(child.killed, ['SIGKILL'], `${platform}: the process itself is killed`);
+ assert.deepStrictEqual(kills, [], `${platform}: nothing else is guessed at`);
+ }
+ // A process that is already gone, or one whose kill throws, is not an error either.
+ const gone = { pid: 4242, kill: () => { throw new Error('ESRCH'); } };
+ assert.doesNotThrow(() => runner.killProcessTree(gone, { platform: 'linux', run: () => ({ status: 0, stdout: '' }), kill: () => { throw new Error('ESRCH'); } }));
+});
+
+// A child that has already exited can no longer be named by its pid: 'exit' comes before 'close' when a process the child started still holds its pipes — the case a call that runs out
+// of time is stopped in — and the number can belong to another process by then, so a tree kill by it could end that one and everything it started. No tool is run against such a child.
+test('killProcessTree does not end a tree by the pid of a child that has already exited — it only asks the child to die', () => {
+ for (const [what, exited] of [['exited with a code', { exitCode: 0 }], ['exited non-zero', { exitCode: 1 }], ['ended by a signal', { exitCode: null, signalCode: 'SIGTERM' }]]) {
+ for (const platform of ['win32', 'linux']) {
+ const child = { ...fakeChild(4242), ...exited };
+ const runs = [];
+ const kills = [];
+ assert.doesNotThrow(() => runner.killProcessTree(child, { platform, run: (...a) => { runs.push(a); return { status: 0, stdout: ' 4243 4242\n' }; }, kill: (pid) => kills.push(pid) }));
+ assert.deepStrictEqual(runs, [], `${what}, ${platform}: no taskkill, no ps`);
+ assert.deepStrictEqual(kills, [], `${what}, ${platform}: no process is signalled by that number`);
+ assert.deepStrictEqual(child.killed, ['SIGKILL'], `${what}, ${platform}: the child is still asked to die`);
+ }
+ }
+ // A child that is running — a ChildProcess reports null for both until it exits — is ended as before.
+ for (const platform of ['win32', 'linux']) {
+ const child = { ...fakeChild(4242), exitCode: null, signalCode: null };
+ const runs = [];
+ runner.killProcessTree(child, { platform, run: (name, ...rest) => { runs.push(name); return { status: 0, stdout: '' }; } });
+ assert.deepStrictEqual(runs, [platform === 'win32' ? 'taskkill' : 'ps'], platform);
+ }
+});
+
+test('killProcessTree leaves a real child that has exited alone, and ends one that is still running', async () => {
+ const { spawn } = require('node:child_process');
+ const exited = spawn(process.execPath, ['-e', ''], { stdio: 'ignore' });
+ await new Promise((resolve) => exited.once('exit', resolve));
+ assert.notStrictEqual(exited.exitCode, null, 'the child has exited');
+ const runs = [];
+ runner.killProcessTree(exited, { run: (...a) => { runs.push(a); return { status: 0, stdout: '' }; }, kill: (pid) => runs.push(['kill', pid]) });
+ assert.deepStrictEqual(runs, [], 'its pid is not used');
+ // One that is running gets the tree kill — through a recording runner, so no real process tree is touched — and is itself killed.
+ const running = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 60000)'], { stdio: 'ignore' });
+ try {
+ assert.strictEqual(running.exitCode, null);
+ const started = [];
+ runner.killProcessTree(running, { run: (name, ...rest) => { started.push(name); return { status: 0, stdout: '' }; }, kill: () => {} });
+ assert.strictEqual(started.length, 1, 'the tool was run for the running child');
+ await new Promise((resolve) => running.once('exit', resolve));
+ assert.ok(running.signalCode === 'SIGKILL' || running.exitCode !== null, 'and the child was ended');
+ } finally {
+ try { running.kill('SIGKILL'); } catch { /* already gone */ }
+ }
+});
+
+test('killProcessTree asks only the child to die when it never started (no pid), and runs nothing', () => {
+ for (const pid of [undefined, null, 0, -1, 'x']) {
+ const child = fakeChild(pid);
+ const runs = [];
+ runner.killProcessTree(child, { platform: 'win32', run: (...a) => { runs.push(a); return { status: 0 }; } });
+ assert.deepStrictEqual(runs, [], `pid ${String(pid)}`);
+ assert.deepStrictEqual(child.killed, ['SIGKILL'], `pid ${String(pid)}`);
+ }
+ assert.doesNotThrow(() => runner.killProcessTree(null));
+ assert.doesNotThrow(() => runner.killProcessTree({ pid: 5 }));
+});
+
+// taskkill.exe is in System32. A PATH without that folder (a service, a CI runner, a stripped-down shell) would make the lookup find nothing, and the kill would then end only the
+// shim, leaving the stalled pac running. The one lookup is therefore made with System32 first on PATH — which also means no earlier folder can stand in for taskkill.
+test('killProcessTree looks taskkill up with the System32 folder first on PATH, whatever PATH it is given, and leaves the caller\'s environment alone', () => {
+ const system32 = 'C:\\Windows\\System32';
+ for (const [what, env, first] of [
+ ['a PATH without System32', { PATH: 'C:\\tools;C:\\other', ComSpec: 'C:\\Windows\\System32\\cmd.exe' }, system32],
+ ['a differently cased Path, which Node would also have passed on', { Path: 'C:\\tools', SystemRoot: 'D:\\Win' }, 'D:\\Win\\System32'],
+ ['a ComSpec in another folder', { PATH: 'C:\\tools', ComSpec: 'E:\\Sys\\cmd.exe' }, 'E:\\Sys'],
+ ['no PATH at all', { SystemRoot: 'C:\\Windows' }, system32],
+ ]) {
+ const given = JSON.stringify(env);
+ const seen = [];
+ runner.killProcessTree(fakeChild(4242), { platform: 'win32', env, run: (name, args, options, deps) => { seen.push({ name, deps }); return { status: 0 }; } });
+ assert.strictEqual(seen.length, 1, what);
+ const lookupPath = seen[0].deps.env.PATH;
+ assert.ok(lookupPath === first || lookupPath.startsWith(`${first};`), `${what}: PATH is ${lookupPath}`);
+ assert.strictEqual(Object.keys(seen[0].deps.env).filter((k) => k.toUpperCase() === 'PATH').length, 1, `${what}: one spelling of PATH reaches the lookup`);
+ assert.strictEqual(JSON.stringify(env), given, `${what}: the environment it was given is not modified`);
+ }
+ // The folders the caller had stay on PATH, after System32.
+ const seen = [];
+ runner.killProcessTree(fakeChild(4242), { platform: 'win32', env: { PATH: 'C:\\tools;C:\\other', ComSpec: `${system32}\\cmd.exe` }, run: (n, a, o, deps) => { seen.push(deps.env.PATH); return { status: 0 }; } });
+ assert.deepStrictEqual(seen, [`${system32};C:\\tools;C:\\other`]);
+});
+
+test('killProcessTree finds taskkill in System32 through the runner\'s own lookup even when PATH has no such folder, and hides its window', () => {
+ // The real lookup (invocation), fed what killProcessTree passes it, over a file system where taskkill exists only in System32.
+ const exists = (p) => p === 'C:\\Windows\\System32\\taskkill.exe';
+ const options = [];
+ let resolved = null;
+ runner.killProcessTree(fakeChild(4242), {
+ platform: 'win32',
+ env: { PATH: 'C:\\tools;C:\\other', SystemRoot: 'C:\\Windows' },
+ run: (name, args, opts, deps) => {
+ options.push(opts);
+ resolved = runner.invocation(name, args, { ...deps, platform: 'win32', exists });
+ return { status: 0 };
+ },
+ });
+ assert.ok(resolved, 'taskkill was found');
+ assert.strictEqual(resolved.file, 'C:\\Windows\\System32\\taskkill.exe');
+ assert.deepStrictEqual(resolved.args, ['/pid', '4242', '/T', '/F']);
+ assert.strictEqual(options[0].windowsHide, true, 'no console window opens for the kill');
+ assert.strictEqual(resolved.options.windowsHide, true);
+ // A folder that is earlier on PATH cannot stand in for it.
+ const planted = (p) => p === 'C:\\tools\\taskkill.exe' || p === 'C:\\Windows\\System32\\taskkill.exe';
+ let first = null;
+ runner.killProcessTree(fakeChild(4242), {
+ platform: 'win32',
+ env: { PATH: 'C:\\tools', SystemRoot: 'C:\\Windows' },
+ run: (name, args, opts, deps) => { first = runner.invocation(name, args, { ...deps, platform: 'win32', exists: planted }).file; return { status: 0 }; },
+ });
+ assert.strictEqual(first, 'C:\\Windows\\System32\\taskkill.exe');
+});
+
+test('killProcessTree\'s POSIX path is left as it was: ps with its own arguments and options, no Windows lookup path, no hidden-window flag', () => {
+ const runs = [];
+ runner.killProcessTree(fakeChild(4242), { platform: 'linux', env: { PATH: '/usr/bin' }, run: (...a) => { runs.push(a); return { status: 0, stdout: '' }; } });
+ assert.strictEqual(runs.length, 1);
+ assert.strictEqual(runs[0][0], 'ps');
+ assert.strictEqual(runs[0].length, 3, 'ps is run with its arguments and options only');
+ assert.strictEqual(runs[0][2].windowsHide, undefined);
+});
+
+test('killProcessTree still ends the process, and never throws, when the environment it was given cannot be read', () => {
+ // The PATH for the lookup is worked out inside the guarded block: an environment that makes that throw must cost the tree kill, not the caller's error handling.
+ const child = fakeChild(4242);
+ const runs = [];
+ assert.doesNotThrow(() => runner.killProcessTree(child, { platform: 'win32', env: null, run: (...a) => { runs.push(a); return { status: 0 }; } }));
+ assert.deepStrictEqual(child.killed, ['SIGKILL']);
+ assert.deepStrictEqual(runs, [], 'there was no PATH to look taskkill up with');
+});
+
+test('descendantPids reads a ps listing: every depth, irregular spacing and CRLF, garbage ignored, a cycle cannot hang it', () => {
+ const text = [' 10 1', '\t11\t10', ' 12 11 ', '13 12\r', 'PID PPID', 'x y', '', ' 14 99', ' 15 14', ' 20 21', ' 21 20'].join('\r\n');
+ assert.deepStrictEqual(runner.descendantPids(10, text).sort((a, b) => a - b), [11, 12, 13]);
+ assert.deepStrictEqual(runner.descendantPids(14, text), [15]);
+ assert.deepStrictEqual(runner.descendantPids(20, text), [21], 'a pair that name each other as parent ends the walk');
+ assert.deepStrictEqual(runner.descendantPids(999, text), []);
+ assert.deepStrictEqual(runner.descendantPids(10, ''), []);
+ assert.deepStrictEqual(runner.descendantPids(10, undefined), []);
+});
+
+// The same two checks, and the ones a real tree answers below, written for a recording runner: `run` and `kill` stand in for taskkill, ps and the signal, so
+// no test here can end a process it did not start.
+test('killProcessTree on Windows asks taskkill for the whole tree of the process, found beside cmd.exe, and then asks the process itself to die as well', () => {
+ const calls = [];
+ const child = fakeChild(4321);
+ runner.killProcessTree(child, {
+ platform: 'win32',
+ env: { SystemRoot: 'C:\\Windows', Path: 'C:\\elsewhere' },
+ run: (name, args, options, deps) => { calls.push({ name, args, options, path: deps.env.PATH }); return { status: 0 }; },
+ });
+ assert.deepStrictEqual(calls.map((c) => [c.name, c.args]), [['taskkill', ['/pid', '4321', '/T', '/F']]]);
+ assert.strictEqual(calls[0].path, 'C:\\Windows\\System32;C:\\elsewhere', 'taskkill is looked for in the directory cmd.exe lives in first, never the current directory');
+ assert.strictEqual(calls[0].options.stdio, 'ignore');
+ assert.deepStrictEqual(child.killed, ['SIGKILL'], 'a tree kill that missed the process cannot leave it running');
+});
+
+test('killProcessTree falls back to the process\'s own kill when taskkill cannot end the tree, off Windows, or with no pid — and never throws', () => {
+ const kills = [];
+ const child = (pid) => ({ pid, kill: () => { kills.push(pid); } });
+ const env = { SystemRoot: 'C:\\Windows', Path: 'C:\\elsewhere' };
+ const signalled = [];
+ const kill = (pid) => signalled.push(pid);
+ runner.killProcessTree(child(1), { platform: 'win32', env, run: () => ({ status: 128 }), kill });
+ runner.killProcessTree(child(2), { platform: 'win32', env, run: () => ({ status: null, error: new Error('spawn taskkill ENOENT') }), kill });
+ runner.killProcessTree(child(3), { platform: 'win32', env, run: () => { throw new Error('taskkill exploded'); }, kill });
+ runner.killProcessTree(child(4), { platform: 'linux', run: () => { throw new Error('spawn ps ENOENT'); }, kill });
+ runner.killProcessTree({ kill: () => kills.push('no pid') }, { platform: 'win32', env, run: () => { throw new Error('no pid, no taskkill'); }, kill });
+ assert.deepStrictEqual(kills, [1, 2, 3, 4, 'no pid']);
+ assert.deepStrictEqual(signalled, [], 'no process is signalled by its number when the tool that lists the tree gave nothing');
+ runner.killProcessTree(null);
+ runner.killProcessTree(undefined, { platform: 'win32' });
+ runner.killProcessTree({ pid: 5, kill: () => { throw new Error('already gone'); } }, { platform: 'linux', run: () => ({ status: 0, stdout: '' }), kill });
+ assert.deepStrictEqual(signalled, []);
+});
+
+// The premise and the fix, on a real cmd.exe. A batch shim runs its program as cmd.exe's CHILD, exactly as az.cmd runs
+// Python, and Node's own kill ends only the cmd.exe it started.
+const processAlive = (pid) => { try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } };
+const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+// Starts `fakecli.cmd` (which runs a node process that records its pid and idles) and waits until that process runs.
+async function startShimmedProgram() {
+ const dir = scratch('process-runner-tree-');
+ const pidFile = path.join(dir, 'program.pid');
+ const script = path.join(dir, 'idle.js');
+ // The timer is a backstop: whatever a failing test leaves behind ends by itself.
+ fs.writeFileSync(script, `require('fs').writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); setTimeout(() => process.exit(0), 120000);\n`, 'utf8');
+ fs.writeFileSync(path.join(dir, 'fakecli.cmd'), `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`, 'utf8');
+ const env = { ...process.env, Path: dir, PATH: dir };
+ const wrapper = runner.execFileAsync('fakecli', ['x'], { windowsHide: true }, () => {}, { env });
+ let program = 0;
+ for (let i = 0; i < 150 && !program; i += 1) {
+ await pause(100);
+ program = fs.existsSync(pidFile) ? Number(fs.readFileSync(pidFile, 'utf8')) : 0;
+ }
+ assert.ok(program > 0 && processAlive(program), 'the shim started its program');
+ assert.notStrictEqual(program, wrapper.pid, 'which is a different process from the cmd.exe Node started');
+ return { wrapper, program };
+}
+
+test('Node\'s own kill of a batch shim leaves the program the shim started running (why killProcessTree exists)', { skip: process.platform !== 'win32' }, async () => {
+ const { wrapper, program } = await startShimmedProgram();
+ try {
+ wrapper.kill();
+ await pause(1500);
+ assert.ok(processAlive(program), 'only the cmd.exe wrapper was ended');
+ } finally {
+ try { process.kill(program); } catch { /* already gone */ }
+ }
+});
+
+test('killProcessTree ends a batch shim AND the program it started (real cmd.exe)', { skip: process.platform !== 'win32' }, async () => {
+ const { wrapper, program } = await startShimmedProgram();
+ try {
+ runner.killProcessTree(wrapper);
+ for (let i = 0; i < 50 && processAlive(program); i += 1) await pause(100);
+ assert.ok(!processAlive(program), 'the program the shim started is gone too');
+ } finally {
+ try { process.kill(program); } catch { /* already gone */ }
+ }
+});
+
+// The same on Linux and macOS, with the real `ps`: the tree is listed with each process's start time and every descendant is read again before its
+// signal, so this also proves that `ps -A -o pid=,ppid=,lstart=` and `ps -o lstart= -p <pid>` print a process's start time the same way there.
+test('killProcessTree ends a real POSIX child and the grandchild it started, through the real ps', { skip: process.platform === 'win32' }, async () => {
+ const { spawn, spawnSync } = require('node:child_process');
+ // A zombie still answers `kill -0` until something reaps it, so a process counts as running only while ps lists it in a state other than Z.
+ const running = (pid) => {
+ const r = spawnSync('ps', ['-o', 'stat=', '-p', String(pid)], { encoding: 'utf8' });
+ return r.status === 0 && !/^\s*Z/.test(r.stdout);
+ };
+ const script = "const { spawn } = require('node:child_process');"
+ + "const g = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 60000)'], { stdio: 'ignore' });"
+ + "process.stdout.write(g.pid + '\\n'); setTimeout(() => {}, 60000);";
+ const child = spawn(process.execPath, ['-e', script], { stdio: ['ignore', 'pipe', 'ignore'] });
+ let grandchild = 0;
+ try {
+ grandchild = await new Promise((resolve, reject) => {
+ let out = '';
+ child.stdout.on('data', (d) => { out += d; const m = /(\d+)\n/.exec(out); if (m) resolve(Number(m[1])); });
+ child.once('error', reject);
+ child.once('exit', () => reject(new Error('the child exited before it reported its grandchild')));
+ });
+ assert.ok(running(grandchild), 'the grandchild runs');
+ runner.killProcessTree(child);
+ for (let i = 0; i < 100 && running(grandchild); i += 1) await pause(100);
+ assert.ok(!running(grandchild), 'the grandchild was ended with the child');
+ } finally {
+ try { child.kill('SIGKILL'); } catch { /* already gone */ }
+ if (grandchild) { try { process.kill(grandchild, 'SIGKILL'); } catch { /* already gone */ } }
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/production-scripts-helper.test.js b/plugins/model-apps/scripts/tests/production-scripts-helper.test.js
new file mode 100644
index 000000000..1e1efc3f2
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/production-scripts-helper.test.js
@@ -0,0 +1,98 @@
+'use strict';
+// The source scans that pin "no production script does X" (helpers/production-scripts.js scriptsMatching) read a script's CODE, not its comments.
+// Their comment stripper is the plugin's literal-aware lexer (lib/source-literals.js commentRanges): the regex it replaced took a `//` or `/*` inside a
+// string, a template or a regular expression for a comment and dropped the code after it — `const s = 'a // b'; cleanWorkspace();` hid the call, and a
+// scan for it passed.
+const test = require('node:test');
+const assert = require('node:assert');
+const fs = require('node:fs');
+const { productionScripts, withoutComments } = require('./helpers/production-scripts.js');
+const { loadTypescriptOracle } = require('./helpers/typescript-oracle.js');
+
+test('withoutComments keeps the code after a comment marker that sits in a string, a template or a regular expression', () => {
+ const kept = [
+ "const s = 'a // b'; cleanWorkspace();",
+ 'const s = "a /* b"; cleanWorkspace(); const t = "*/";',
+ 'const t = `a // b ${x} /* c`; cleanWorkspace();',
+ "const u = 'https://contoso.crm.dynamics.com/api'; cleanWorkspace();",
+ 'const r = /a\\/\\/b/; cleanWorkspace();',
+ 'const r = /[/*]/g; cleanWorkspace();',
+ ];
+ for (const code of kept) {
+ assert.match(withoutComments(code), /cleanWorkspace\(\)/, code);
+ }
+});
+
+test('withoutComments drops real comments — line and block, between code — and keeps every offset and line break', () => {
+ const code = 'const a = 1; // cleanWorkspace()\n/* cleanWorkspace()\n spans */ const b = 2;\n';
+ const out = withoutComments(code);
+ assert.doesNotMatch(out, /cleanWorkspace/);
+ assert.strictEqual(out.length, code.length, 'a comment becomes blank space, so offsets are the source\'s');
+ assert.deepStrictEqual(out.split('\n').length, code.split('\n').length, 'and line breaks are kept');
+ assert.match(out, /^const a = 1; +\n +\n +const b = 2;\n$/);
+});
+
+test('every production script reads through the lexer: its code keeps every byte that is not a comment, and its line breaks', () => {
+ const scripts = productionScripts();
+ assert.ok(scripts.length > 40, `found ${scripts.length} scripts`);
+ for (const file of scripts) {
+ const code = fs.readFileSync(file, 'utf8');
+ const out = withoutComments(code);
+ assert.strictEqual(out.length, code.length, file);
+ for (let i = 0; i < code.length; i += 1) {
+ if (out[i] !== code[i]) assert.strictEqual(out[i], ' ', `${file}: offset ${i} changed to something other than a blank`);
+ if (code[i] === '\n' || code[i] === '\r') assert.strictEqual(out[i], code[i], `${file}: a line break at ${i} is kept`);
+ }
+ }
+});
+
+// The comments TypeScript's own parser finds in `code`, as [start, end] pairs in source order. Every comment is trivia between two tokens: TypeScript reports one on a
+// line of its own as LEADING trivia of the token after it (the end-of-file token included), and one on the same line after code (`x; // note`, `catch { /* … */ }`) as
+// TRAILING trivia of the token before it — so the union of both, over every node, is all of them. A JSDoc is not walked into: its nodes (`@param {number} x`) sit
+// INSIDE the comment, and the trivia "after" one of them is the comment's own text — `/** @param {number} x // a count */` would yield a second comment at `//`.
+// The JSDoc itself is still found, as leading trivia of the token it documents.
+function typescriptComments(ts, file, code) {
+ const source = ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
+ const found = new Map();
+ const visit = (node) => {
+ if (ts.isJSDoc(node)) return;
+ for (const c of ts.getLeadingCommentRanges(code, node.pos) || []) found.set(c.pos, c.end);
+ for (const c of ts.getTrailingCommentRanges(code, node.end) || []) found.set(c.pos, c.end);
+ if (node.kind === ts.SyntaxKind.EndOfFileToken) return;
+ for (const child of node.getChildren(source)) visit(child);
+ };
+ visit(source);
+ return [...found].sort((a, b) => a[0] - b[0]);
+}
+
+const oracle = { skip: !process.env.TYPESCRIPT_ORACLE_PATH && 'TYPESCRIPT_ORACLE_PATH is not set' };
+
+// With TypeScript pointed at (TYPESCRIPT_ORACLE_PATH, the lexer-oracle CI job), the comments the lexer finds in each production script are exactly the
+// ones TypeScript's own parser finds: so the scans cannot be blinded (code read as a comment) or polluted (a comment read as code) by a script's text.
+test('the comments the lexer finds in every production script are the ones TypeScript finds', oracle, () => {
+ const ts = loadTypescriptOracle();
+ const { commentRanges } = require('../lib/source-literals.js');
+ for (const file of productionScripts()) {
+ const code = fs.readFileSync(file, 'utf8');
+ // A `#!` line is the parser's shebang, not a comment it reports; the lexer hears it as one.
+ const ours = commentRanges(code).filter((c) => !c.text.startsWith('#!')).map((c) => [c.start, c.end]);
+ assert.deepStrictEqual(ours, typescriptComments(ts, file, code), file);
+ }
+});
+
+// The oracle itself must not invent a comment: a `//` inside a JSDoc is the JSDoc's text. Walking into the JSDoc's own nodes found a second "comment" from there to
+// the JSDoc's end, and failed the comparison above for a script whose comments the lexer had read correctly.
+test('the TypeScript oracle reads a JSDoc as one comment, with no comment inside it', oracle, () => {
+ const ts = loadTypescriptOracle();
+ const { commentRanges } = require('../lib/source-literals.js');
+ const cases = [
+ ['/** @param {number} x // a count */\nfunction f(x) {}\n', [[0, 35]]],
+ ['/** {@link f} // x */\nfunction f() {}\n', [[0, 21]]],
+ ['class C {\n /** @returns {number} // n */\n m() { return 1; } // after\n}\n', [[12, 41], [62, 70]]],
+ ["/** @type {string} */ const s = 'a // b'; // tail\n", [[0, 21], [42, 49]]],
+ ];
+ for (const [code, expected] of cases) {
+ assert.deepStrictEqual(typescriptComments(ts, 'case.js', code), expected, code);
+ assert.deepStrictEqual(commentRanges(code).map((c) => [c.start, c.end]), expected, `the lexer agrees: ${code}`);
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/provision-entities.test.js b/plugins/model-apps/scripts/tests/provision-entities.test.js
index 2b0cf9777..0e22a39ba 100644
--- a/plugins/model-apps/scripts/tests/provision-entities.test.js
+++ b/plugins/model-apps/scripts/tests/provision-entities.test.js
@@ -125,6 +125,54 @@ test('dry-run plan includes non-trivial provision steps and skips non-actions',
]);
});
+test('dry-run plan lists the relationships in the order the apply creates them — a lookup labelled in several languages first', async () => {
+ // The plan used to follow the declared order while the apply creates a lookup with a language-map label before
+ // the others (lib/entity-provision.js relationshipsInCreateOrder), so the two disagreed whenever a spec — which
+ // this entry point accepts as well — gave one of them an LCID map.
+ const bilingual = {
+ solution: { uniqueName: 'Default', publisherPrefix: 'cr' },
+ entities: [
+ { schemaName: 'cr_parent', displayName: 'Parent', primaryAttribute: { schemaName: 'cr_name' }, columns: [] },
+ { schemaName: 'cr_child', displayName: 'Child', primaryAttribute: { schemaName: 'cr_name' }, columns: [] },
+ { schemaName: 'cr_other', displayName: 'Other', primaryAttribute: { schemaName: 'cr_name' }, columns: [] },
+ ],
+ relationships: [
+ { type: 'ManyToMany', schemaName: 'cr_parent_child_nn', entity1: 'cr_parent', entity2: 'cr_child' },
+ { type: 'OneToMany', schemaName: 'cr_parent_children', referenced: 'cr_parent', referencing: 'cr_child', lookup: { schemaName: 'cr_parentid' } },
+ { type: 'OneToMany', schemaName: 'cr_other_children', referenced: 'cr_other', referencing: 'cr_child', lookup: { schemaName: 'cr_otherid', displayName: { 1033: 'Other', 3082: 'Otro' } } },
+ ],
+ };
+ const dry = await provisionEntities(bilingual, { apply: false }, mockDeps());
+ assert.deepStrictEqual(dry.plan.filter((p) => /^relationship /.test(p)), [
+ 'relationship 1:N cr_other->cr_child',
+ 'relationship N:N cr_parent<->cr_child',
+ 'relationship 1:N cr_parent->cr_child',
+ ]);
+
+ const d = mockDeps();
+ const created = [];
+ d.sdk.createRelationship = async (o) => { created.push(o.schemaName); return { schemaName: o.schemaName, metadataId: `rel-${o.schemaName}` }; };
+ const applied = await provisionEntities(bilingual, { apply: true }, { sdk: d.sdk, provision: d.provision, provisionedLanguages: [1033, 3082] });
+ assert.strictEqual(applied.ok, true, JSON.stringify(applied));
+ assert.deepStrictEqual(created, ['cr_other_children', 'cr_parent_child_nn', 'cr_parent_children'], 'the apply creates them in the order the plan lists');
+});
+
+test('a spec with no language-map lookup label keeps the declared order in the plan', async () => {
+ const plain = {
+ solution: { uniqueName: 'Default', publisherPrefix: 'cr' },
+ entities: [
+ { schemaName: 'cr_parent', displayName: 'Parent', primaryAttribute: { schemaName: 'cr_name' }, columns: [] },
+ { schemaName: 'cr_child', displayName: 'Child', primaryAttribute: { schemaName: 'cr_name' }, columns: [] },
+ ],
+ relationships: [
+ { type: 'ManyToMany', schemaName: 'cr_parent_child_nn', entity1: 'cr_parent', entity2: 'cr_child' },
+ { type: 'OneToMany', schemaName: 'cr_parent_children', referenced: 'cr_parent', referencing: 'cr_child', lookup: { schemaName: 'cr_parentid' } },
+ ],
+ };
+ const dry = await provisionEntities(plain, { apply: false }, mockDeps());
+ assert.deepStrictEqual(dry.plan.filter((p) => /^relationship /.test(p)), ['relationship N:N cr_parent<->cr_child', 'relationship 1:N cr_parent->cr_child']);
+});
+
test('apply surfaces fallback metadata for existing columns and relationships', async () => {
const existingInput = {
solution: { uniqueName: 'Default', publisherPrefix: 'cr' },
@@ -454,3 +502,77 @@ test('CLI provisions the requested input and cleans its workspace before emit',
fs.rmSync(dir, { recursive: true, force: true });
}
});
+
+// --- primaryAttribute.maxLength through this entry point -----------------------------------------------------------
+// This is the entry point of /genpage and /app-builder: it writes the publisher and the solution BEFORE its first table, and
+// puts the name column's length in both table creates as it is written. The input gate is the only thing between a value the
+// platform refuses (or a string, which would be sent as a string) and those writes.
+
+function withPrimaryAttribute(primaryAttribute, columns) {
+ return { ...input, entities: [{ ...input.entities[0], primaryAttribute, ...(columns ? { columns } : {}) }] };
+}
+
+test('an invalid primaryAttribute.maxLength is refused before anything is called — no publisher, no solution, no table', async () => {
+ for (const maxLength of ['120', 5000, 851, 0, 1.5, -3, null]) {
+ const d = mockDeps();
+ const touched = [];
+ const watch = (target) => new Proxy(target, { get: (t, key) => (typeof t[key] === 'function' ? (...args) => { touched.push(String(key)); return t[key](...args); } : t[key]) });
+ const r = await provisionEntities(withPrimaryAttribute({ schemaName: 'cr_name', maxLength }), { apply: true }, { sdk: watch(d.sdk), provision: watch(d.provision) });
+ assert.strictEqual(r.ok, false, `${JSON.stringify(maxLength)} must be refused`);
+ assert.ok(r.errors.some((e) => /^entity 'cr_candidate': primaryAttribute\.maxLength must be a whole number from 1 to 850 \(got /.test(e)), JSON.stringify(r.errors));
+ assert.deepStrictEqual(touched, [], `${JSON.stringify(maxLength)}: nothing was called`);
+ }
+});
+
+test('the name column asks for the length given (1 to 850), else 100 — auto-numbered or not — in the table create', async () => {
+ const askedBy = async (primaryAttribute) => {
+ const d = mockDeps();
+ const creates = [];
+ d.sdk.createTable = async (o) => { creates.push(o); return { logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s`, metadataId: 'tbl' }; };
+ // Reads the length back as asked, so a given length needs no update.
+ d.provision.dataverse = { get: async (url) => (/StringAttributeMetadata/.test(url) ? { status: 200, body: { MaxLength: primaryAttribute.maxLength } } : { status: 404, body: null }) };
+ const r = await provisionEntities(withPrimaryAttribute(primaryAttribute), { apply: true }, { sdk: d.sdk, provision: d.provision });
+ assert.strictEqual(r.ok, true, JSON.stringify(r));
+ return creates[0].primaryColumnMaxLength;
+ };
+ // 100 is what the previous release always sent, for a plain and an auto-numbered name column alike.
+ assert.strictEqual(await askedBy({ schemaName: 'cr_name' }), 100);
+ assert.strictEqual(await askedBy({ schemaName: 'cr_name', autoNumberFormat: 'CAND-{SEQNUM:4}' }), 100);
+ assert.strictEqual(await askedBy({ schemaName: 'cr_name', maxLength: 1 }), 1);
+ assert.strictEqual(await askedBy({ schemaName: 'cr_name', maxLength: 850 }), 850);
+ assert.strictEqual(await askedBy({ schemaName: 'cr_name', maxLength: 120, autoNumberFormat: 'CAND-{SEQNUM:4}' }), 120);
+});
+
+test('primary column length: the step is planned AND counted, so [n/total] never drifts, whether it updates, finds the length right, or fails', async () => {
+ const sized = withPrimaryAttribute({ schemaName: 'cr_name', maxLength: 120 });
+ const dry = await provisionEntities(sized, { apply: false }, mockDeps());
+ // Listed where the build runs it: last in the data model, after the relationships — the length is set once nothing labelled is left to create.
+ assert.deepStrictEqual(dry.plan, ['solution Default', 'table cr_candidate', 'column cr_candidate.cr_status (Choice)', 'primary column length cr_candidate.cr_name']);
+ const related = {
+ ...sized,
+ entities: [...sized.entities, { schemaName: 'cr_note', displayName: 'Note', primaryAttribute: { schemaName: 'cr_name' }, columns: [] }],
+ relationships: [{ type: 'OneToMany', schemaName: 'cr_candidate_notes', referenced: 'cr_candidate', referencing: 'cr_note', lookup: { schemaName: 'cr_candidateid' } }],
+ };
+ assert.deepStrictEqual((await provisionEntities(related, { apply: false }, mockDeps())).plan, [
+ 'solution Default', 'table cr_candidate', 'column cr_candidate.cr_status (Choice)', 'table cr_note', 'relationship 1:N cr_candidate->cr_note', 'primary column length cr_candidate.cr_name',
+ ]);
+ const plain = await provisionEntities(input, { apply: false }, mockDeps());
+ assert.ok(!plain.plan.some((p) => /primary column length/.test(p)), 'no step when the input gives no length');
+
+ for (const [what, read, updateFails] of [['updated', 850, false], ['already right', 120, false], ['update fails', 850, true]]) {
+ const d = mockDeps();
+ const updates = [];
+ d.provision.dataverse = { get: async (url) => (/StringAttributeMetadata/.test(url) ? { status: 200, body: { MaxLength: read } } : { status: 404, body: null }) };
+ d.sdk.updateColumn = async (table, column, opts) => { updates.push([table, column, opts]); if (updateFails) throw new Error('refused'); return {}; };
+ const events = [];
+ const r = await provisionEntities(related, { apply: true }, { sdk: d.sdk, provision: d.provision, emit: (e) => events.push(e), warn: () => {} });
+ assert.strictEqual(r.ok, true, what);
+ const done = events.filter((e) => e.status !== 'start');
+ assert.ok(events.every((e) => e.n <= e.total), `${what}: no step emits n > total`);
+ assert.strictEqual(done[done.length - 1].n, done[0].total, `${what}: the last step is the total`);
+ assert.strictEqual(done.filter((e) => /^primary column length /.test(e.label)).length, 1, `${what}: the step is narrated once`);
+ assert.match(done[done.length - 1].label, /^primary column length cr_candidate\.cr_name/, `${what}: and it is the last step, after the relationship`);
+ assert.ok(done.findIndex((e) => /^relationship /.test(e.label)) < done.length - 1, `${what}: the relationship came before it`);
+ assert.deepStrictEqual(updates, read === 120 ? [] : [['cr_candidate', 'cr_name', { maxLength: 120 }]], what);
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/rebuild-writes-real-bundle.test.js b/plugins/model-apps/scripts/tests/rebuild-writes-real-bundle.test.js
new file mode 100644
index 000000000..7ddc53b36
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/rebuild-writes-real-bundle.test.js
@@ -0,0 +1,855 @@
+'use strict';
+// An UNCHANGED rebuild must write (almost) nothing.
+//
+// Measured on a mid-sized app: `build --apply --publish --verify` straight after a successful build of the same spec
+// still sent ~59 writes — an AddSolutionComponent per reused component, a PATCH and a PublishXml per existing view and
+// form, and more. These tests drive the REAL vendored SDK against a stateful fake Dataverse (helpers/fake-dataverse.js)
+// and count what actually reaches the wire, so each skipped write is proven against what the SDK really sends, and
+// each one that must NOT be skipped is proven to still go out.
+//
+// Every test name starts "rebuild writes:". Four write-skipping behaviours are covered, in this order:
+// views an existing view is pushed only when the reconcile changed it (columns / description), or an
+// interrupted run left an edit in the workspace
+// publishes with --publish, a reconcile's own publish is left to the one phase-8 publish, and a failure of that
+// publish names the views, forms and charts it carried (a first build's included); without --publish,
+// each still publishes its own
+// forms an existing form is pushed only when the reconcile changed it
+// membership solution membership is read once; only components the solution does not already hold are added
+// An edit a maker made in Dataverse since the last build must be converged, never skipped as "unchanged".
+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 { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');
+const { runSdkBuild, settleOwedPublishes } = require('../lib/sdk-build.js');
+const { createFakeDataverse } = require('./helpers/fake-dataverse.js');
+
+const COMPONENT = { view: 26, chart: 59, form: 60 };
+const dirs = [];
+test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+const ENTITIES = {
+ new_ticket: { attributes: { new_name: 'String', new_code: 'String', new_area: 'String', new_extra: 'String', new_taskid: 'Lookup' } },
+ new_task: { attributes: { new_name: 'String', new_due: 'String' } },
+};
+
+// Two tables the build did not create (`existing: true`: no default-form promotion, no default-view enrichment — both
+// are the SDK's or another path's writes, accounted for separately below): a view and a form on each, a Quick View
+// form hosted on the ticket form, and a chart. This is the shape of the measured app, scaled down.
+function specFor({ viewColumns = ['new_name', 'new_code'], viewDescription, ticketColumns = ['new_code', 'new_area'], authoredFilter = false } = {}) {
+ return {
+ $schemaVersion: '1.0',
+ solution: { uniqueName: 'ContosoSD', displayName: 'Contoso SD', publisherPrefix: 'new' },
+ app: { name: 'Support Desk', uniqueName: 'new_supportdesk' },
+ entities: [
+ { schemaName: 'new_ticket', displayName: 'Ticket', pluralName: 'Tickets', existing: true,
+ primaryAttribute: { schemaName: 'new_name', displayName: 'Name' },
+ columns: ticketColumns.map((c) => ({ schemaName: c, displayName: c, type: 'Text' })) },
+ { schemaName: 'new_task', displayName: 'Task', pluralName: 'Tasks', existing: true,
+ primaryAttribute: { schemaName: 'new_name', displayName: 'Name' },
+ columns: [{ schemaName: 'new_due', displayName: 'Due', type: 'Text' }] },
+ ],
+ views: [
+ { entity: 'new_ticket', name: 'Open Tickets', columns: viewColumns, ...(viewDescription ? { description: viewDescription } : {}),
+ ...(authoredFilter ? { filters: [{ attr: 'new_code', op: 'eq', value: 'A' }] } : {}) },
+ { entity: 'new_task', name: 'My Tasks', columns: ['new_name', 'new_due'] },
+ ],
+ charts: [{ entity: 'new_ticket', name: 'By Area', chartType: 'Pie', groupBy: 'new_area', measure: 'count' }],
+ forms: [
+ { entity: 'new_ticket', name: 'Ticket', layout: 'auto', quickViews: [{ lookup: 'new_taskid', targetEntity: 'new_task', form: 'Task Card' }] },
+ { entity: 'new_task', name: 'Task', layout: 'auto' },
+ { entity: 'new_task', name: 'Task Card', formType: 'QuickView', layout: 'auto' },
+ ],
+ };
+}
+
+// The same two tables with NO form in the spec: the view's table is carried by a view and the chart's by a chart, so each
+// publish's vehicle is not a form. A column-only view change and a chart description are the two edits it can carry.
+function formlessSpec(viewColumns, chartDescription) {
+ return {
+ $schemaVersion: '1.0',
+ solution: { uniqueName: 'ContosoSD', displayName: 'Contoso SD', publisherPrefix: 'new' },
+ app: { name: 'Support Desk', uniqueName: 'new_supportdesk' },
+ entities: [
+ { schemaName: 'new_ticket', displayName: 'Ticket', pluralName: 'Tickets', existing: true, primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns: [{ schemaName: 'new_code', displayName: 'Code', type: 'Text' }, { schemaName: 'new_area', displayName: 'Area', type: 'Text' }] },
+ { schemaName: 'new_task', displayName: 'Task', pluralName: 'Tasks', existing: true, primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns: [{ schemaName: 'new_due', displayName: 'Due', type: 'Text' }] },
+ ],
+ views: [{ entity: 'new_task', name: 'My Tasks', columns: viewColumns }],
+ charts: [{ entity: 'new_ticket', name: 'By Area', chartType: 'Pie', groupBy: 'new_area', measure: 'count', ...(chartDescription ? { description: chartDescription } : {}) }],
+ };
+}
+
+// One durable workspace and one fake environment per scenario; each build gets a FRESH SDK instance over the same
+// workspace directory, as every CLI run does.
+function scenario(fakeOptions = {}) {
+ const fake = createFakeDataverse({ entities: ENTITIES, ...fakeOptions });
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rebuild-writes-'));
+ dirs.push(dir);
+ const sdkOver = async (workspace = dir, { withoutDiff = false } = {}) => {
+ const real = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(workspace), instanceUrl: 'https://contoso.crm.dynamics.com', httpClient: fake.httpClient });
+ await real.initWorkspace();
+ if (!withoutDiff) return real;
+ // An SDK without the dirty-tracking method: a method the engine finds missing must make it write as before.
+ return new Proxy(real, { get: (target, key) => (key === 'diffArtifact' ? undefined : (typeof target[key] === 'function' ? target[key].bind(target) : target[key])) });
+ };
+ async function build(spec, { publish = true, phases, sdk, warnings = [] } = {}) {
+ const mark = fake.mark();
+ const useSdk = sdk || await sdkOver();
+ const result = await runSdkBuild(spec, { sdk: useSdk, apply: true, publish, phases: phases || PHASES, warn: (w) => warnings.push(String(w)) });
+ return { result, mark, writes: fake.writeCounts(mark), warnings, sdk: useSdk };
+ }
+ return { fake, dir, sdkOver, build };
+}
+
+const PHASES = ['views', 'charts', 'forms', 'publish'];
+
+// --------------------------------------------------------------------------------------------- the baseline
+
+test('rebuild writes: an unchanged rebuild sends nothing but the one phase-8 publish', async () => {
+ const s = scenario();
+ const first = await s.build(specFor());
+ assert.deepEqual(first.writes, {
+ 'POST savedqueries': 2, 'POST savedqueryvisualizations': 1, 'POST systemforms': 3, 'PATCH systemforms': 1, 'POST AddSolutionComponent': 6, 'POST PublishXml': 1,
+ }, 'the first build creates every component (the PATCH places the quick view on its host form), adds each to the solution, and publishes once');
+ assert.deepEqual(s.fake.unpublished(), []);
+
+ const again = await s.build(specFor());
+ assert.deepEqual(again.writes, { 'POST PublishXml': 1 }, 'the only write left is phase 8\'s single envelope for the tables the spec touches');
+ assert.equal(again.result.ok, true);
+ assert.deepEqual(s.fake.unpublished(), [], 'nothing is left saved but unpublished');
+ assert.equal(s.fake.requests.slice(again.mark).filter((e) => e.method === 'POST' && e.path === '/PublishXml').length, 1);
+});
+
+// ------------------------------------------------------------------------------------ views: pushed only when changed
+
+test('rebuild writes: an existing view the reconcile changes is still pushed once, with its new column', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ const changed = await s.build(specFor({ viewColumns: ['new_name', 'new_code', 'new_area'] }));
+ assert.equal(changed.writes['PATCH savedqueries'], 1, JSON.stringify(changed.writes));
+ const [save] = s.fake.saves(changed.mark);
+ assert.match(save.body.layoutxml, /<cell name="new_area"/, 'the added column reaches the layout');
+ assert.match(save.body.layoutxml, /<cell name="new_code"/, 'the columns already there are kept');
+ assert.equal(changed.writes['POST AddSolutionComponent'], undefined, 'it is already a member');
+ assert.deepEqual(s.fake.unpublished(), [], 'and the change is published (by phase 8)');
+});
+
+test('rebuild writes: a changed view description is pushed; the same description a second time is not', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ const first = await s.build(specFor({ viewDescription: 'Open work, newest first.' }));
+ const [save] = s.fake.saves(first.mark);
+ assert.ok(save, JSON.stringify(first.writes));
+ assert.equal(save.body.description, 'Open work, newest first.');
+ const second = await s.build(specFor({ viewDescription: 'Open work, newest first.' }));
+ assert.equal(second.writes['PATCH savedqueries'], undefined, 'an ordinary rebuild issues no extra write');
+});
+
+test('rebuild writes: a view edit an interrupted run left in the workspace is still pushed', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ // The run that wants a new column dies at the push: the workspace copy keeps the edit, the server never sees it.
+ s.fake.failWritesWhen((req) => (req.method === 'PATCH' && /^\/savedqueries\(/.test(req.path) ? 500 : undefined));
+ await assert.rejects(s.build(specFor({ viewColumns: ['new_name', 'new_code', 'new_area'] })), /push|500|simulated/i);
+ s.fake.failWritesWhen(null);
+ const savedBefore = s.fake.rows('savedqueries').filter((r) => r.data.name === 'Open Tickets')[0].data.layoutxml;
+ assert.doesNotMatch(savedBefore, /new_area/, 'the server still lacks the column');
+
+ // The next run reconciles the SAME spec. Against the server copy the view already "has" the column only because the
+ // workspace kept the unpushed edit — comparing what this run computed with what was fetched would call it unchanged.
+ const retry = await s.build(specFor({ viewColumns: ['new_name', 'new_code', 'new_area'] }));
+ assert.equal(retry.writes['PATCH savedqueries'], 1, JSON.stringify(retry.writes));
+ assert.match(s.fake.rows('savedqueries').filter((r) => r.data.name === 'Open Tickets')[0].data.layoutxml, /new_area/);
+ assert.deepEqual(s.fake.unpublished(), []);
+});
+
+test('rebuild writes: the "authored filters are NOT reapplied" warning still fires on an unchanged rebuild', async () => {
+ const s = scenario();
+ const spec = specFor({ authoredFilter: true });
+ await s.build(spec);
+ const again = await s.build(spec);
+ assert.equal(again.writes['PATCH savedqueries'], undefined);
+ assert.ok(again.warnings.some((w) => /view 'Open Tickets' already exists/.test(w) && /NOT reapplied/.test(w)), again.warnings.join('\n'));
+});
+
+test('rebuild writes: an SDK without dirty tracking pushes an existing view exactly as before', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ const again = await s.build(specFor(), { sdk: await s.sdkOver(s.dir, { withoutDiff: true }) });
+ assert.equal(again.writes['PATCH savedqueries'], 2, 'both views pushed, as before');
+ assert.equal(again.writes['PATCH systemforms'], 3, 'and all three forms');
+});
+
+// -------------------------------------------------- publishes: left to phase 8 with --publish, per artifact without it
+
+test('rebuild writes: with --publish a reconcile\'s own publish is left to phase 8, which publishes every table it touched', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ // Both tables change: a view column on the ticket, a form field on the task.
+ const spec = specFor({ viewColumns: ['new_name', 'new_code', 'new_area'] });
+ spec.entities[1].columns.push({ schemaName: 'new_extra', displayName: 'Extra', type: 'Text' });
+ const changed = await s.build(spec);
+ assert.equal(changed.writes['POST PublishXml'], 1, `one envelope, not one publish per reconciled artifact: ${JSON.stringify(changed.writes)}`);
+ const publishXml = s.fake.since(changed.mark).filter((e) => e.path === '/PublishXml')[0];
+ assert.match(publishXml.body.ParameterXml, /<entity>new_ticket<\/entity>/);
+ assert.match(publishXml.body.ParameterXml, /<entity>new_task<\/entity>/);
+ assert.deepEqual(s.fake.unpublished(), []);
+});
+
+test('rebuild writes: a table whose only reconciled artifact is a view, and one whose only artifact is a chart, are still published', async () => {
+ const s = scenario();
+ const spec = formlessSpec;
+ await s.build(spec(['new_name']));
+ const changed = await s.build(spec(['new_name', 'new_due'], 'Tickets by area.'));
+ assert.equal(changed.writes['PATCH savedqueries'], 1, 'the task view gains its column');
+ assert.equal(changed.writes['PATCH savedqueryvisualizations'], 1, 'the chart description is written');
+ assert.equal(changed.writes['POST PublishXml'], 1, JSON.stringify(changed.writes));
+ const xml = s.fake.since(changed.mark).find((e) => e.path === '/PublishXml').body.ParameterXml;
+ assert.match(xml, /<entity>new_task<\/entity>/, 'the view\'s table (no form in the spec names it) is in the envelope');
+ assert.match(xml, /<entity>new_ticket<\/entity>/, 'the chart\'s table is in the envelope');
+ assert.deepEqual(s.fake.unpublished(), []);
+});
+
+test('rebuild writes: without --publish every reconciled view and form still publishes its own table, as before', async () => {
+ const s = scenario();
+ await s.build(specFor(), { publish: false });
+ const again = await s.build(specFor(), { publish: false });
+ // Nothing was pushed (unchanged), but a clean workspace copy is the UNPUBLISHED layer: it cannot show that an earlier
+ // run which pushed and then stopped ever published, so the per-artifact publish stays — 2 views + 3 forms.
+ assert.equal(again.writes['POST PublishXml'], 5, JSON.stringify(again.writes));
+ assert.equal(again.writes['PATCH savedqueries'], undefined);
+ assert.equal(again.writes['PATCH systemforms'], undefined);
+ assert.equal(again.writes['POST AddSolutionComponent'], undefined);
+});
+
+test('rebuild writes: without --publish a view the earlier run pushed but never published is published by the rebuild', async () => {
+ const s = scenario();
+ await s.build(specFor(), { publish: false });
+ // An earlier run saved a new column and stopped before any publish: simulated by a push that no publish follows.
+ const sdk = await s.sdkOver();
+ const view = s.fake.rows('savedqueries').find((r) => r.data.name === 'Open Tickets');
+ await sdk.fetchArtifact('view', view.data.savedqueryid);
+ await sdk.updateElement('view', view.data.savedqueryid, '/columns', [...(await sdk.getArtifact('view', view.data.savedqueryid)).columns, { name: 'new_area', width: 100, order: 2 }]);
+ await sdk.pushArtifact('view', view.data.savedqueryid);
+ assert.ok(s.fake.unpublished().some((r) => r.name === 'Open Tickets'), 'saved but unpublished');
+ const again = await s.build(specFor({ viewColumns: ['new_name', 'new_code', 'new_area'] }), { publish: false });
+ assert.equal(again.writes['PATCH savedqueries'], undefined, 'the server already has the column: nothing to push');
+ assert.deepEqual(s.fake.unpublished().filter((r) => r.name === 'Open Tickets'), [], 'the rebuild still publishes it');
+});
+
+test('rebuild writes: a build that halts after a reconcile hands its caller the publish it owes, and settling it makes the change live', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ // The view is pushed (its publish deferred), then a form push fails and halts the forms phase before phase 8.
+ s.fake.failWritesWhen((req) => (req.method === 'PATCH' && /^\/systemforms\(/.test(req.path) && req.body && req.body.formxml ? 500 : undefined));
+ const spec = specFor({ viewColumns: ['new_name', 'new_code', 'new_area'] });
+ spec.entities[0].columns.push({ schemaName: 'new_extra', displayName: 'Extra', type: 'Text' });
+ const sdk = await s.sdkOver();
+ const halted = await runSdkBuild(spec, { sdk, apply: true, publish: true, phases: PHASES }).then(() => null, (e) => e);
+ assert.ok(halted, 'the build halts');
+ s.fake.failWritesWhen(null);
+ assert.ok(Array.isArray(halted.owedPublishes) && halted.owedPublishes.length >= 1, 'the halt carries what it owes');
+ assert.ok(halted.owedPublishes.every(([type, id]) => type && id));
+ assert.ok(s.fake.unpublished().some((r) => r.name === 'Open Tickets'), 'the saved view waits for its publish');
+ assert.equal(Object.keys(halted).includes('owedPublishes'), false, 'it rides along, never into a serialized error');
+
+ const warnings = [];
+ await settleOwedPublishes(sdk, halted.owedPublishes, (w) => warnings.push(w));
+ assert.deepEqual(s.fake.unpublished().filter((r) => r.name === 'Open Tickets'), [], 'a halted build leaves the saved view live, as it did before publishes were deferred');
+ assert.deepEqual(warnings, []);
+});
+
+// Settling happens only for a halt the build THROWS: a process killed outright (Ctrl-C, a crash) settles nothing, and
+// no marker outlives it. That is a documented limit, so what it leaves must be exactly what a re-run repairs.
+test('rebuild writes: a build killed between its reconcile and its publish leaves the edit saved, and the next build publishes it without writing it again', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ const grown = () => specFor({ viewColumns: ['new_name', 'new_code', 'new_area'] });
+ // The process dies as phase 8 starts. Nothing here calls settleOwedPublishes, which is the point.
+ const killed = (e) => { if (e.phase === 'publish' && e.status === 'start') throw new Error('process killed'); };
+ const sdk = await s.sdkOver();
+ await assert.rejects(runSdkBuild(grown(), { sdk, apply: true, publish: true, phases: PHASES, emit: killed }), /process killed/);
+ assert.ok(s.fake.unpublished().some((r) => r.name === 'Open Tickets'), 'the saved view waits for a publish nothing will send');
+
+ const again = await s.build(grown());
+ assert.equal(again.writes['PATCH savedqueries'], undefined, 'the column is already on the server: nothing to write again');
+ assert.deepEqual(s.fake.unpublished(), [], 'the next build publishes it');
+});
+
+// A deferred publish is ONE for a whole table, so the lines it prints when it fails or cannot be confirmed name the
+// saved views and forms it was to publish, as the per-artifact publish it replaced did. Naming whichever artifact stands
+// for the table (its Main form, usually untouched) would send a maker looking for the wrong thing.
+const changedTicketSpec = () => {
+ const spec = specFor({ viewColumns: ['new_name', 'new_code', 'new_area'] });
+ spec.entities[0].columns.push({ schemaName: 'new_extra', displayName: 'Extra', type: 'Text' });
+ return spec;
+};
+const PUBLISH_XML_DOWN = (req) => (req.method === 'POST' && req.path === '/PublishXml' ? 500 : undefined);
+
+test('rebuild writes: a phase-8 publish that fails names the views and forms that were saved but are not live', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ s.fake.failWritesWhen(PUBLISH_XML_DOWN);
+ const warnings = [];
+ const changed = await s.build(changedTicketSpec(), { warnings });
+ s.fake.failWritesWhen(null);
+ assert.equal(changed.result.ok, true, 'a refused publish is reported and left to the next build');
+ assert.ok(s.fake.unpublished().some((r) => r.name === 'Open Tickets'), 'the saved view really is not live');
+
+ const failed = warnings.filter((w) => /FAILED/.test(w));
+ assert.equal(failed.length, 2, `one line per table: ${warnings.join('\n')}`);
+ const ticket = failed.find((w) => /Open Tickets/.test(w));
+ assert.match(ticket, /^publish view Open Tickets, form Ticket FAILED: /, 'the view that changed, and the form that rode with it');
+ assert.match(ticket, /the change is SAVED but the runtime still serves the previously published copy/);
+ const task = failed.find((w) => /My Tasks/.test(w));
+ assert.ok(task && /form Task\b/.test(task) && /form Task Card/.test(task), `every reconciled artifact of the table is named: ${task}`);
+ assert.ok(failed.every((w) => !/\b[0-9a-f]{8}-[0-9a-f]{4}-/.test(w)), `no bare artifact id stands in for a name: ${failed.join('\n')}`);
+});
+
+test('rebuild writes: a phase-8 publish that cannot be confirmed names the views and forms it covers', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ // The SDK says `unverifiable` when the published projection cannot be read back; the build reports what it is told.
+ const real = await s.sdkOver();
+ const sdk = new Proxy(real, {
+ get: (target, key) => {
+ if (key === 'publishArtifacts') {
+ return async (items, options) => (await target.publishArtifacts(items, options)).map((r) => ({ ...r, shipped: false, publish: { kind: 'unverifiable', reason: 'the published projection could not be read' } }));
+ }
+ return typeof target[key] === 'function' ? target[key].bind(target) : target[key];
+ },
+ });
+ const warnings = [];
+ await s.build(specFor(), { sdk, warnings });
+ const unconfirmed = warnings.filter((w) => /could not be CONFIRMED/.test(w));
+ assert.equal(unconfirmed.length, 2, warnings.join('\n'));
+ assert.match(unconfirmed.find((w) => /Open Tickets/.test(w)), /^publish view Open Tickets, form Ticket could not be CONFIRMED \(the published projection could not be read\) — /);
+ assert.ok(unconfirmed.some((w) => /My Tasks/.test(w) && /form Task Card/.test(w)));
+});
+
+test('rebuild writes: when settling the publish a halted build owes fails, the warning names the saved views', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ s.fake.failWritesWhen((req) => (req.method === 'PATCH' && /^\/systemforms\(/.test(req.path) && req.body && req.body.formxml ? 500 : undefined));
+ const sdk = await s.sdkOver();
+ const halted = await runSdkBuild(changedTicketSpec(), { sdk, apply: true, publish: true, phases: PHASES }).then(() => null, (e) => e);
+ assert.ok(halted, 'the build halts in the forms phase');
+ const ticket = halted.owedPublishes.find(([, , names]) => (names || []).includes('view Open Tickets'));
+ assert.ok(ticket, `the owed target carries the names of what it covers: ${JSON.stringify(halted.owedPublishes)}`);
+
+ s.fake.failWritesWhen(PUBLISH_XML_DOWN);
+ const warnings = [];
+ await settleOwedPublishes(sdk, halted.owedPublishes, (w) => warnings.push(w));
+ s.fake.failWritesWhen(null);
+ assert.ok(warnings.some((w) => /^the build stopped before its publish phase; publish view Open Tickets FAILED: /.test(w)), warnings.join('\n'));
+});
+
+// The default views the enrichment saved are owed the same publish. A table whose authored view changed AND whose generated
+// Active/Inactive pair was enriched has three views saved but not live, and a line that named only the authored one would
+// leave the pair looking published.
+const enriched = (spec) => {
+ for (const e of spec.entities) { delete e.existing; e.enrichDefaultViews = true; }
+ return spec;
+};
+function enrichedScenario() {
+ const s = scenario();
+ s.fake.seedDefaultViews('new_ticket', 'Tickets');
+ s.fake.seedDefaultViews('new_task', 'Tasks');
+ return s;
+}
+
+test('rebuild writes: a failed phase-8 publish also names the default views the enrichment saved, whether it made the table\'s record or found it', async () => {
+ const s = enrichedScenario();
+ // The task table has no authored view, so its enrichment is what makes its record; the ticket table's authored view does.
+ const spec = (viewColumns) => { const sp = enriched(specFor({ viewColumns })); sp.views = sp.views.filter((v) => v.entity === 'new_ticket'); return sp; };
+ await s.build(spec(['new_name', 'new_code']));
+ s.fake.failWritesWhen(PUBLISH_XML_DOWN);
+ const warnings = [];
+ await s.build(spec(['new_name', 'new_code', 'new_area']), { warnings });
+ s.fake.failWritesWhen(null);
+ const notLive = s.fake.unpublished().map((r) => r.name);
+ for (const name of ['Open Tickets', 'Active Tickets', 'Inactive Tickets', 'Active Tasks', 'Inactive Tasks']) assert.ok(notLive.includes(name), `${name} is saved but not live: ${notLive}`);
+
+ const failed = warnings.filter((w) => /FAILED/.test(w));
+ assert.equal(failed.length, 2, `one line per table: ${warnings.join('\n')}`);
+ assert.match(failed.find((w) => /Open Tickets/.test(w)), /^publish view Open Tickets, default views of new_ticket, form Ticket FAILED: /, 'the authored view made the record; the enrichment joined it');
+ const task = failed.find((w) => /new_task/.test(w));
+ assert.match(task, /^publish default views of new_task, form Task/, `the enrichment made the record, and the forms joined it: ${failed.join('\n')}`);
+ assert.match(task, /form Task Card/);
+});
+
+test('rebuild writes: when settling the publish a halted build owes fails, the warning also names the default views the enrichment saved', async () => {
+ const s = enrichedScenario();
+ await s.build(enriched(specFor()));
+ s.fake.failWritesWhen((req) => (req.method === 'PATCH' && /^\/systemforms\(/.test(req.path) && req.body && req.body.formxml ? 500 : undefined));
+ const sdk = await s.sdkOver();
+ const halted = await runSdkBuild(enriched(changedTicketSpec()), { sdk, apply: true, publish: true, phases: PHASES }).then(() => null, (e) => e);
+ assert.ok(halted, 'the build halts in the forms phase');
+ const ticket = halted.owedPublishes.find(([, , names]) => (names || []).includes('view Open Tickets'));
+ assert.deepEqual(ticket && ticket[2], ['view Open Tickets', 'default views of new_ticket'], `the owed target names both: ${JSON.stringify(halted.owedPublishes)}`);
+
+ s.fake.failWritesWhen(PUBLISH_XML_DOWN);
+ const warnings = [];
+ await settleOwedPublishes(sdk, halted.owedPublishes, (w) => warnings.push(w));
+ s.fake.failWritesWhen(null);
+ assert.ok(warnings.some((w) => /^the build stopped before its publish phase; publish view Open Tickets, default views of new_ticket FAILED: /.test(w)), warnings.join('\n'));
+});
+
+// The names one failed-publish line carries: `publish form Ticket, view Open Tickets FAILED: …` -> ['form Ticket', 'view Open Tickets'].
+const carried = (line) => line.replace(/^publish /, '').replace(/ FAILED: .*$/, '').split(', ');
+
+// What the build REQUESTS from the SDK, to prove the names only label the lines: a request is still a type and an id.
+function recordPublishRequests(real) {
+ const calls = [];
+ const sdk = new Proxy(real, {
+ get: (target, key) => {
+ if (key === 'publishArtifacts' || key === 'publishArtifact') return (...args) => { calls.push({ via: key, args }); return target[key](...args); };
+ return typeof target[key] === 'function' ? target[key].bind(target) : target[key];
+ },
+ });
+ return { sdk, calls };
+}
+
+// A FIRST build creates its views, forms and charts, so no reconcile deferred a publish for any of them and the only name a
+// table's record held was its generated default views'. When that table's publish fails, everything the build saved on it is
+// not live, and a line that named only the generated Active/Inactive pair read as if only those had failed.
+test('rebuild writes: a failed phase-8 publish on a first build names the view, form and chart it created, not only the default views', async () => {
+ const s = enrichedScenario();
+ const { sdk, calls } = recordPublishRequests(await s.sdkOver());
+ s.fake.failWritesWhen(PUBLISH_XML_DOWN);
+ const warnings = [];
+ const first = await s.build(enriched(specFor()), { sdk, warnings });
+ s.fake.failWritesWhen(null);
+ assert.equal(first.result.ok, true, 'a refused publish is reported and left to the next build');
+ const notLive = s.fake.unpublished().map((r) => r.name);
+ for (const name of ['Open Tickets', 'By Area', 'Ticket', 'Active Tickets', 'Inactive Tickets', 'My Tasks', 'Task', 'Task Card', 'Active Tasks', 'Inactive Tasks']) assert.ok(notLive.includes(name), `${name} is saved but not live: ${notLive}`);
+
+ const failed = warnings.filter((w) => /FAILED/.test(w));
+ assert.equal(failed.length, 2, `one line per table: ${warnings.join('\n')}`);
+ // One line per table, in spec order. What was deferred onto the table comes first (the enrichment, then the quick-view
+ // placement), then what the build created, in name order because the artifacts are created concurrently — each name once.
+ assert.deepEqual(failed.map((w) => carried(w)), [
+ ['default views of new_ticket', 'form Ticket quick-views', 'chart By Area', 'form Ticket', 'view Open Tickets'],
+ ['default views of new_task', 'form Task', 'form Task Card', 'view My Tasks'],
+ ], failed.join('\n'));
+ assert.ok(failed.every((w) => !/\b[0-9a-f]{8}-[0-9a-f]{4}-/.test(w)), `no bare artifact id stands in for a name: ${failed.join('\n')}`);
+
+ // Only the label changed: the publish is asked for exactly as before — one envelope with one artifact per table, each a
+ // type and an id, then each table that failed on its own — and nothing more is sent for it.
+ const envelope = calls.filter((c) => c.via === 'publishArtifacts');
+ const single = calls.filter((c) => c.via === 'publishArtifact');
+ assert.equal(envelope.length, 1, 'one envelope');
+ assert.deepEqual(envelope[0].args[0].map((item) => [Object.keys(item).sort().join(), item.type]), [['id,type', 'form'], ['id,type', 'form']], 'the Main form of each table carries its publish, named by type and id only');
+ assert.equal(single.length, 2, 'then each failed table on its own');
+ for (const { args } of single) assert.equal(args.length, 2, 'a single publish is a type and an id');
+ assert.equal(first.writes['POST PublishXml'], 3, `one envelope and one publish per failed table, nothing more: ${JSON.stringify(first.writes)}`);
+});
+
+test('rebuild writes: a failed phase-8 publish on a first build of tables it does not enrich names what it created, not a bare form id', async () => {
+ const s = scenario();
+ s.fake.failWritesWhen(PUBLISH_XML_DOWN);
+ const warnings = [];
+ await s.build(specFor(), { warnings });
+ s.fake.failWritesWhen(null);
+ const failed = warnings.filter((w) => /FAILED/.test(w));
+ assert.equal(failed.length, 2, `one line per table: ${warnings.join('\n')}`);
+ // One line per table, in spec order. The ticket table's only deferred publish is its quick-view placement; the task
+ // table has none, so its Main form used to stand for it as a bare id.
+ assert.deepEqual(failed.map((w) => carried(w)), [
+ ['form Ticket quick-views', 'chart By Area', 'form Ticket', 'view Open Tickets'],
+ ['form Task', 'form Task Card', 'view My Tasks'],
+ ], failed.join('\n'));
+ assert.ok(failed.every((w) => !/\b[0-9a-f]{8}-[0-9a-f]{4}-/.test(w)), `no bare artifact id stands in for a name: ${failed.join('\n')}`);
+});
+
+test('rebuild writes: a failed phase-8 publish on a first build names the view or chart that stands for a table with no form', async () => {
+ const s = scenario();
+ s.fake.failWritesWhen(PUBLISH_XML_DOWN);
+ const warnings = [];
+ await s.build(formlessSpec(['new_name']), { warnings });
+ s.fake.failWritesWhen(null);
+ const failed = warnings.filter((w) => /FAILED/.test(w));
+ assert.equal(failed.length, 2, `one line per table: ${warnings.join('\n')}`);
+ assert.deepEqual(failed.map((w) => carried(w)).sort(), [['chart By Area'], ['view My Tasks']], `the artifact that carries each table is named: ${failed.join('\n')}`);
+});
+
+test('rebuild writes: a failed phase-8 publish names a view a rebuild added and a chart description it wrote, beside what it reconciled', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ const grown = specFor();
+ grown.views.push({ entity: 'new_ticket', name: 'Closed Tickets', columns: ['new_name'] });
+ grown.charts[0].description = 'Tickets by area.';
+ s.fake.failWritesWhen(PUBLISH_XML_DOWN);
+ const warnings = [];
+ const again = await s.build(grown, { warnings });
+ s.fake.failWritesWhen(null);
+ assert.equal(again.writes['POST savedqueries'], 1, 'the new view is created');
+ assert.equal(again.writes['PATCH savedqueryvisualizations'], 1, 'the chart description is written');
+ // The two reconciled artifacts first (deferred in phase order), then what the rebuild created or wrote, in name order.
+ const failed = warnings.filter((w) => /FAILED/.test(w));
+ const ticketLine = failed.find((w) => /Open Tickets/.test(w));
+ assert.ok(ticketLine, `the ticket table's line names its reconciled view: ${failed.join('\n')}`);
+ assert.deepEqual(carried(ticketLine), ['view Open Tickets', 'form Ticket', 'chart By Area', 'view Closed Tickets']);
+});
+
+// A name is said once, and only for something the build saved: a chart whose description the spec sets but that was already there was not written, so it is not named; and a form the
+// reconcile deferred and a form of the same name the build created are one `form Ticket`, not two.
+test('rebuild writes: an unchanged chart whose description the spec sets is not named', async () => {
+ const s = scenario();
+ const spec = () => { const sp = specFor(); sp.charts[0].description = 'Tickets by area.'; return sp; };
+ await s.build(spec());
+ s.fake.failWritesWhen(PUBLISH_XML_DOWN);
+ const warnings = [];
+ await s.build(spec(), { warnings });
+ s.fake.failWritesWhen(null);
+ const ticket = warnings.filter((w) => /FAILED/.test(w)).find((w) => /Open Tickets/.test(w));
+ assert.ok(ticket, warnings.join('\n'));
+ assert.ok(!carried(ticket).includes('chart By Area'), ticket);
+});
+
+test('rebuild writes: a reconciled form and a created form of the same name are named once', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ const grown = specFor();
+ grown.forms.push({ entity: 'new_ticket', name: 'Ticket', formType: 'QuickCreate', layout: 'auto' });
+ s.fake.failWritesWhen(PUBLISH_XML_DOWN);
+ const warnings = [];
+ await s.build(grown, { warnings });
+ s.fake.failWritesWhen(null);
+ const ticket = warnings.filter((w) => /FAILED/.test(w)).find((w) => /Open Tickets/.test(w));
+ assert.equal(carried(ticket).filter((n) => n === 'form Ticket').length, 1, ticket);
+});
+
+// The SDK saves both generated views of every table it enriches on EVERY build, so the enrichment's name is in the record on an
+// unchanged rebuild too, not only when something changed. (Should the SDK ever skip an identical save, this and the comment at
+// the enrichment step go stale together.)
+test('rebuild writes: an unchanged rebuild still names the default views when its publish fails, because the SDK saves them on every build', async () => {
+ const s = enrichedScenario();
+ const first = await s.build(enriched(specFor()));
+ // `since(mark)` runs to the end of the log, so the first build's saves are read before the second build starts.
+ const savesSince = (mark) => Object.fromEntries(s.fake.since(mark).filter((e) => e.method === 'PATCH' && /^\/savedqueries\(/.test(e.path)).map((e) => [e.path, JSON.stringify(e.body)]));
+ const savedFirst = savesSince(first.mark);
+ assert.equal(Object.keys(savedFirst).length, 4, 'the first build enriches both generated views of each table');
+ s.fake.failWritesWhen(PUBLISH_XML_DOWN);
+ const warnings = [];
+ const again = await s.build(enriched(specFor()), { warnings });
+ s.fake.failWritesWhen(null);
+ assert.equal(again.writes['PATCH savedqueries'], 4, `both generated views of each table are saved again: ${JSON.stringify(again.writes)}`);
+ assert.deepEqual(savesSince(again.mark), savedFirst, 'with the content they already had');
+ const failed = warnings.filter((w) => /FAILED/.test(w));
+ assert.equal(failed.length, 2, `one line per table: ${warnings.join('\n')}`);
+ assert.ok(carried(failed.find((w) => /new_ticket/.test(w))).includes('default views of new_ticket'), failed.join('\n'));
+ assert.ok(carried(failed.find((w) => /new_task/.test(w))).includes('default views of new_task'), failed.join('\n'));
+});
+
+// The names of what a build CREATED only label a failed publish; they are not a debt. What a halted build settles is what
+// it DEFERRED, so a table whose artifacts it merely created is left exactly as it always was — nothing published for it.
+test('rebuild writes: a first build that halts owes no publish for the views, forms and charts it merely created', async () => {
+ const s = scenario();
+ s.fake.failWritesWhen((req) => (req.method === 'PATCH' && /^\/systemforms\(/.test(req.path) && req.body && req.body.formxml ? 500 : undefined));
+ const sdk = await s.sdkOver();
+ const mark = s.fake.mark();
+ const halted = await runSdkBuild(specFor(), { sdk, apply: true, publish: true, phases: PHASES }).then(() => null, (e) => e);
+ s.fake.failWritesWhen(null);
+ assert.ok(halted, 'the build halts in the forms phase, when the quick view is placed');
+ assert.ok(s.fake.unpublished().some((r) => r.name === 'Open Tickets') && s.fake.unpublished().some((r) => r.name === 'By Area'), 'the created view and chart are saved and not live');
+ assert.equal(halted.owedPublishes, undefined, 'nothing was deferred, so nothing is owed');
+ assert.equal(s.fake.since(mark).filter((e) => e.path === '/PublishXml').length, 0, 'and no publish was sent');
+});
+
+test('rebuild writes: wiring a form event handler defers its publish too, and a rebuild that adds nothing wires and publishes nothing', async () => {
+ const s = scenario();
+ const spec = specFor();
+ spec.forms[1].events = [{ event: 'onload', library: 'new_tasklib.js', function: 'taskLoad' }];
+ const first = await s.build(spec);
+ // 3 creates + the quick view's host push + the handler's push; the quick-view and handler publishes are phase 8's.
+ assert.equal(first.writes['PATCH systemforms'], 2, JSON.stringify(first.writes));
+ assert.equal(first.writes['POST PublishXml'], 1, `one publish for the whole build: ${JSON.stringify(first.writes)}`);
+ assert.deepEqual(s.fake.unpublished(), []);
+
+ const again = await s.build(spec);
+ assert.deepEqual(again.writes, { 'POST PublishXml': 1 });
+
+ spec.forms[1].events.push({ event: 'onsave', library: 'new_tasklib.js', function: 'taskSave' });
+ const added = await s.build(spec);
+ assert.equal(added.writes['PATCH systemforms'], 1, 'only the form that gained a handler is pushed');
+ assert.equal(added.writes['POST PublishXml'], 1);
+ assert.deepEqual(s.fake.unpublished(), []);
+});
+
+// ------------------------------------------------------------------------------------ forms: pushed only when changed
+
+test('rebuild writes: an existing form the reconcile changes is still pushed once, with its new field', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ const spec = specFor();
+ spec.entities[1].columns.push({ schemaName: 'new_extra', displayName: 'Extra', type: 'Text' });
+ const changed = await s.build(spec);
+ assert.equal(changed.writes['PATCH systemforms'], 2, `the task Main form and its quick view both gain the field: ${JSON.stringify(changed.writes)}`);
+ assert.ok(s.fake.saves(changed.mark).every((e) => /new_extra/.test(e.body.formxml)));
+ assert.equal(changed.writes['POST AddSolutionComponent'], undefined);
+ assert.deepEqual(s.fake.unpublished(), []);
+});
+
+test('rebuild writes: an unchanged rebuild reads no form version token and writes no form', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ const again = await s.build(specFor());
+ assert.deepEqual(s.fake.saves(again.mark), []);
+ // A form push reads the row's version token first (`GET /systemforms(<id>)`), then the content token and the record
+ // back — three reads a form on top of the fetch. None of them happen when there is nothing to send.
+ assert.equal(s.fake.reads(/^\/systemforms\([^)]*\)$/, again.mark).length, 0, 'no row-token read: nothing was pushed');
+});
+
+test('rebuild writes: a form edit an interrupted run left in the workspace is still pushed', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ const spec = specFor();
+ spec.entities[1].columns.push({ schemaName: 'new_extra', displayName: 'Extra', type: 'Text' });
+ s.fake.failWritesWhen((req) => (req.method === 'PATCH' && /^\/systemforms\(/.test(req.path) && req.body && req.body.formxml ? 500 : undefined));
+ await assert.rejects(s.build(spec), /push|500|simulated/i);
+ s.fake.failWritesWhen(null);
+ assert.ok(s.fake.rows('systemforms').every((r) => !/new_extra/.test(r.data.formxml)), 'the server never saw the field');
+ const retry = await s.build(spec);
+ assert.ok(retry.writes['PATCH systemforms'] >= 1, JSON.stringify(retry.writes));
+ assert.ok(s.fake.rows('systemforms').filter((r) => r.data.objecttypecode === 'new_task' && r.data.type === 2).every((r) => /new_extra/.test(r.data.formxml)), 'the field lands');
+});
+
+// --------------------------------------------------------------- an edit made in Dataverse since the last build
+//
+// The workspace copy of a view or form is the SDK's last-synced snapshot, so a CLEAN copy says the workspace holds
+// no edit the server has not seen — nothing about the server having MOVED since. The reconcile fetches first: a clean
+// copy is refreshed from the server (the maker's edit becomes the new snapshot), the reconcile applies what the spec
+// asks for on top of it, and THAT difference is what gets pushed. A dirty check that read "clean" regardless would
+// leave the maker's edit standing and report a green build, so each of these moves the server before the rebuild.
+
+test('rebuild writes: a spec column a maker removed from a view in Dataverse is pushed back', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ const view = () => s.fake.rows('savedqueries').find((r) => r.data.name === 'Open Tickets');
+ assert.match(view().data.layoutxml, /new_code/);
+ // The maker drops the column in the designer: the layout loses its cell, the query its attribute, the row moves on.
+ view().data.layoutxml = view().data.layoutxml.replace(/<cell name="new_code"[^>]*\/>/, '');
+ view().data.fetchxml = view().data.fetchxml.replace(/<attribute name="new_code"\s*\/>/, '');
+ view().version += 1;
+ assert.doesNotMatch(view().data.layoutxml, /new_code/, 'the edit was made');
+
+ const again = await s.build(specFor());
+ assert.equal(again.writes['PATCH savedqueries'], 1, JSON.stringify(again.writes));
+ assert.match(view().data.layoutxml, /<cell name="new_code"/, 'the spec\'s column is back');
+ assert.deepEqual(s.fake.unpublished(), [], 'and it is published');
+});
+
+test('rebuild writes: a description the spec sets, changed by a maker in Dataverse, is pushed back', async () => {
+ const s = scenario();
+ const spec = () => specFor({ viewDescription: 'Spec text.' });
+ await s.build(spec());
+ const view = () => s.fake.rows('savedqueries').find((r) => r.data.name === 'Open Tickets');
+ assert.equal(view().data.description, 'Spec text.');
+ view().data.description = 'Maker text.';
+ view().version += 1;
+
+ const again = await s.build(spec());
+ assert.equal(again.writes['PATCH savedqueries'], 1, JSON.stringify(again.writes));
+ assert.equal(view().data.description, 'Spec text.', 'the spec\'s description is back');
+ assert.deepEqual(s.fake.unpublished(), []);
+});
+
+test('rebuild writes: a spec field a maker removed from a form in Dataverse is pushed back', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ const form = () => s.fake.rows('systemforms').find((r) => r.data.objecttypecode === 'new_ticket' && r.data.type === 2);
+ const before = form().data.formxml;
+ assert.match(before, /datafieldname="new_area"/);
+ // Drop the whole <cell> that holds the field, as removing it in the designer does.
+ form().data.formxml = before.replace(/<cell\b(?:(?!<cell\b)[\s\S])*?datafieldname="new_area"[\s\S]*?<\/cell>/, '');
+ form().version += 1;
+ assert.doesNotMatch(form().data.formxml, /datafieldname="new_area"/, 'the edit was made');
+
+ const again = await s.build(specFor());
+ assert.equal(again.writes['PATCH systemforms'], 1, `only the form that moved is pushed: ${JSON.stringify(again.writes)}`);
+ assert.match(form().data.formxml, /datafieldname="new_area"/, 'the spec\'s field is back');
+ assert.deepEqual(s.fake.unpublished(), []);
+});
+
+// Both at once is the one combination the SDK refuses to reconcile on its own: the workspace holds an edit the server
+// has not seen AND the server has moved, so a refresh would lose one of them. The reconcile's fetch throws before any
+// dirty check is asked, and the build must stop there — not skip the push as "unchanged", and not overwrite either side.
+test('rebuild writes: an edit left in the workspace by an interrupted run, with the server moved since, halts without writing', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ const grown = () => specFor({ viewColumns: ['new_name', 'new_code', 'new_area'] });
+ s.fake.failWritesWhen((req) => (req.method === 'PATCH' && /^\/savedqueries\(/.test(req.path) ? 500 : undefined));
+ await assert.rejects(s.build(grown()), /push|500|simulated/i);
+ s.fake.failWritesWhen(null);
+ const view = () => s.fake.rows('savedqueries').find((r) => r.data.name === 'Open Tickets');
+ view().data.description = 'Maker text.';
+ view().version += 1;
+
+ const mark = s.fake.mark();
+ await assert.rejects(s.build(grown()), (e) => e && e.code === 'LOCAL_EDITS_WOULD_BE_LOST' && e.phase === 'views');
+ assert.equal(s.fake.writeCounts(mark)['PATCH savedqueries'], undefined, 'nothing is written over the maker\'s edit');
+ assert.equal(view().data.description, 'Maker text.', 'and the maker\'s edit is still there');
+ assert.doesNotMatch(view().data.layoutxml, /new_area/, 'the interrupted run\'s column never reached the server');
+});
+
+// ----------------------------------------------------------- solution membership: one read, only what is missing added
+
+test('rebuild writes: the membership read is made once and every component it proves present is not added', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ const again = await s.build(specFor());
+ assert.equal(again.writes['POST AddSolutionComponent'], undefined);
+ assert.equal(s.fake.reads(/^\/solutioncomponents$/, again.mark).length, 1, 'one query, not one per component');
+ assert.equal(s.fake.reads(/^\/solutions$/, again.mark).length, 1);
+ const query = s.fake.reads(/^\/solutioncomponents$/, again.mark)[0].query;
+ assert.match(query.$filter, new RegExp(`_solutionid_value eq ${s.fake.solutionId}`));
+ assert.match(query.$filter, /componenttype eq 26/);
+ assert.equal(query.$top, undefined, 'a paginated read carries no $top');
+});
+
+test('rebuild writes: a component the solution lacks is added again, and only that one', async () => {
+ const s = scenario();
+ await s.build(specFor());
+ const chart = s.fake.rows('savedqueryvisualizations')[0];
+ const view = s.fake.rows('savedqueries').find((r) => r.data.name === 'My Tasks');
+ s.fake.removeMember(COMPONENT.chart, chart.data.savedqueryvisualizationid);
+ s.fake.removeMember(COMPONENT.view, view.data.savedqueryid);
+ const again = await s.build(specFor());
+ assert.equal(again.writes['POST AddSolutionComponent'], 2, JSON.stringify(again.writes));
+ const adds = s.fake.since(again.mark).filter((e) => e.path === '/AddSolutionComponent').map((e) => `${e.body.ComponentType}:${e.body.ComponentId}`).sort();
+ assert.deepEqual(adds, [`${COMPONENT.chart}:${chart.data.savedqueryvisualizationid}`, `${COMPONENT.view}:${view.data.savedqueryid}`].sort());
+ assert.equal(s.fake.members.size, 6, 'membership is whole again');
+});
+
+test('rebuild writes: a membership read that pages is read in full, and still adds nothing', async () => {
+ const s = scenario({ pageSize: 2 });
+ await s.build(specFor());
+ const again = await s.build(specFor());
+ assert.equal(again.writes['POST AddSolutionComponent'], undefined, 'a short first page must not look like a short list');
+ assert.equal(s.fake.reads(/^\/solutioncomponents$/, again.mark).length, 3, 'six members in pages of two');
+});
+
+test('rebuild writes: when the membership cannot be read, every component is added as before', async () => {
+ const s = scenario({ failSolutionComponentReads: true });
+ await s.build(specFor());
+ const again = await s.build(specFor());
+ assert.equal(again.result.ok, true, 'an unreadable membership never fails the build');
+ assert.equal(again.writes['POST AddSolutionComponent'], 6, `2 views + 1 chart + 3 forms: ${JSON.stringify(again.writes)}`);
+});
+
+test('rebuild writes: a built-in solution proves nothing, is never read, and still gets its adds', async () => {
+ const s = scenario({ solution: { uniqueName: 'Default' } });
+ const spec = (name) => { const sp = specFor(); sp.solution.uniqueName = name; return sp; };
+ await s.build(spec('Default'));
+ const again = await s.build(spec('Default'));
+ assert.equal(s.fake.reads(/^\/solutioncomponents$/, again.mark).length, 0);
+ assert.equal(again.writes['POST AddSolutionComponent'], 6);
+});
+
+// A first build that deploys pages is the exception: the page manifest is persisted through the membership check even
+// when it was just created, so that build makes the read (pinned in sdk-build.test.js, where pages can be staged).
+test('rebuild writes: a first build with no pages, where every component is new, never reads the membership', async () => {
+ const s = scenario();
+ const first = await s.build(specFor());
+ assert.equal(s.fake.reads(/^\/solutioncomponents$/, first.mark).length, 0);
+ assert.equal(first.writes['POST AddSolutionComponent'], 6);
+});
+
+// A table created inside a solution is held by it with ALL its subcomponents ("Include all objects"), and the platform
+// does not list that table's views, forms and charts one by one: an explicit AddSolutionComponent for one succeeds and
+// leaves no row. Measured live — a rebuild of an app whose tables the build had created sent the adds for every view,
+// form and chart again, 10 of the 19 a rebuild used to send, because a membership that looked only for rows never found
+// them; the SDK's own solution reader documents the same ("members the solution does not list one by one").
+// The fake answers the way the platform does (helpers/fake-dataverse.js). A table held in part is the control: it lists
+// what was added on its own, so only that can be skipped, and a missing one is added.
+const tableIdReads = (s, mark) => s.fake.reads(/^\/EntityDefinitions\(LogicalName='[^']+'\)$/, mark).filter((e) => /MetadataId/.test(e.query.$select || ''));
+
+test('rebuild writes: a table held with all its subcomponents has no rows for its views, forms and charts, and a rebuild adds none of them', async () => {
+ const s = scenario({ heldTables: { new_ticket: 0, new_task: 0 } });
+ const first = await s.build(specFor());
+ assert.equal(first.writes['POST AddSolutionComponent'], 6, 'the first build adds each component it creates');
+ assert.equal(s.fake.members.size, 0, 'and the platform lists none of them: their tables carry them');
+
+ const again = await s.build(specFor());
+ assert.deepEqual(again.writes, { 'POST PublishXml': 1 }, JSON.stringify(again.writes));
+ const read = s.fake.reads(/^\/solutioncomponents$/, again.mark);
+ assert.equal(read.length, 1, 'one membership read');
+ assert.match(read[0].query.$filter, /componenttype eq 1\b/, 'it asks for the tables');
+ assert.match(read[0].query.$select, /rootcomponentbehavior/, 'and for how much of each the solution holds');
+ assert.deepEqual(tableIdReads(s, again.mark).map((e) => e.path).sort(), ["/EntityDefinitions(LogicalName='new_task')", "/EntityDefinitions(LogicalName='new_ticket')"], 'one lookup per table, not one per component');
+});
+
+test('rebuild writes: a table held in part lists what was added on its own, and a rebuild adds only what is missing', async () => {
+ for (const behavior of [1, 2]) {
+ const s = scenario({ heldTables: { new_ticket: behavior, new_task: behavior } });
+ const first = await s.build(specFor());
+ assert.equal(first.writes['POST AddSolutionComponent'], 6);
+ assert.equal(s.fake.members.size, 6, `held at ${behavior}, each component is listed on its own`);
+
+ const again = await s.build(specFor());
+ assert.equal(again.writes['POST AddSolutionComponent'], undefined, `held at ${behavior}: ${JSON.stringify(again.writes)}`);
+ assert.deepEqual(tableIdReads(s, again.mark), [], 'no table carries its subcomponents, so none is looked up');
+
+ // A view the solution lost is added again: the table does not carry it.
+ const view = s.fake.rows('savedqueries').find((r) => r.data.name === 'My Tasks');
+ s.fake.removeMember(COMPONENT.view, view.data.savedqueryid);
+ const repaired = await s.build(specFor());
+ assert.equal(repaired.writes['POST AddSolutionComponent'], 1, `held at ${behavior}: ${JSON.stringify(repaired.writes)}`);
+ }
+});
+
+test('rebuild writes: a table held with all its subcomponents vouches for its own components only, not for another table\'s', async () => {
+ const s = scenario({ heldTables: { new_ticket: 0, new_task: 2 } });
+ const first = await s.build(specFor());
+ assert.equal(first.writes['POST AddSolutionComponent'], 6);
+ assert.equal(s.fake.members.size, 3, 'the task\'s view and two forms are listed; the ticket\'s view, chart and form are carried by their table');
+
+ const again = await s.build(specFor());
+ assert.equal(again.writes['POST AddSolutionComponent'], undefined, JSON.stringify(again.writes));
+ assert.deepEqual(tableIdReads(s, again.mark).map((e) => e.path), ["/EntityDefinitions(LogicalName='new_ticket')"], 'only the table that has to vouch for something is looked up');
+
+ const view = s.fake.rows('savedqueries').find((r) => r.data.name === 'My Tasks');
+ s.fake.removeMember(COMPONENT.view, view.data.savedqueryid);
+ const repaired = await s.build(specFor());
+ assert.equal(repaired.writes['POST AddSolutionComponent'], 1, 'the ticket table does not carry the task view: it is added again');
+});
+
+test('rebuild writes: a table a maker switched from "all subcomponents" to "shell only" stops vouching, and its components are added once', async () => {
+ const s = scenario({ heldTables: { new_ticket: 0, new_task: 0 } });
+ await s.build(specFor());
+ s.fake.holdTable('new_ticket', 2);
+ const switched = await s.build(specFor());
+ assert.equal(switched.writes['POST AddSolutionComponent'], 3, `the ticket's view, chart and form no longer ride on the table: ${JSON.stringify(switched.writes)}`);
+ const settled = await s.build(specFor());
+ assert.equal(settled.writes['POST AddSolutionComponent'], undefined, 'and now they are listed on their own');
+});
+
+test('rebuild writes: when a table\'s MetadataId cannot be read, nothing is vouched for and every component is added as before', async () => {
+ const s = scenario({ heldTables: { new_ticket: 0, new_task: 0 } });
+ await s.build(specFor());
+ s.fake.failTableIdReads(true);
+ const again = await s.build(specFor());
+ s.fake.failTableIdReads(false);
+ assert.equal(again.result.ok, true, 'a failed lookup never fails the build');
+ assert.equal(again.writes['POST AddSolutionComponent'], 6, JSON.stringify(again.writes));
+});
+
+// --------------------------------------------------------------------------------- what is deliberately left
+
+test('rebuild writes: the default-view enrichment is the SDK\'s own write and is still sent for each table\'s generated pair', async () => {
+ const s = scenario();
+ s.fake.seedDefaultViews('new_ticket', 'Tickets');
+ s.fake.seedDefaultViews('new_task', 'Tasks');
+ const spec = specFor();
+ for (const e of spec.entities) { delete e.existing; e.enrichDefaultViews = true; }
+ await s.build(spec);
+ const again = await s.build(spec);
+ // The engine's own reconcile writes are gone; what remains is the SDK's enrichDefaultViews, which pushes both views
+ // of each pair, and the default-form promotion of the two owned tables (isdefault) — neither is a reconcile push.
+ assert.equal(again.writes['PATCH savedqueries'], 4, JSON.stringify(again.writes));
+ assert.equal(again.writes['POST AddSolutionComponent'], undefined);
+ assert.equal(again.writes['POST PublishXml'], 1);
+ assert.deepEqual(s.fake.saves(again.mark).filter((e) => e.body.formxml), [], 'no form document is written');
+});
diff --git a/plugins/model-apps/scripts/tests/rebuild-writes-reuse-sites.test.js b/plugins/model-apps/scripts/tests/rebuild-writes-reuse-sites.test.js
new file mode 100644
index 000000000..afa0ca985
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/rebuild-writes-reuse-sites.test.js
@@ -0,0 +1,105 @@
+'use strict';
+// Rebuild writes, continued — the reuse sites of the business-rules and business-process-flows phases. A reused rule or
+// flow joins the solution again only when the solution is not PROVEN to hold it (solution-membership.js); the views,
+// charts, forms, app, sitemap, page manifest and persona roles are pinned in sdk-build.test.js, and the wire-level
+// behaviour in rebuild-writes-real-bundle.test.js.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { runSdkBuild } = require('../lib/sdk-build.js');
+const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');
+
+const SOLUTION_ID = '5011c0de-0000-4000-8000-000000000002';
+const WORKFLOW = 29; // a business rule and a process flow are both `workflow` rows
+
+function baseSpec() {
+ return {
+ solution: { uniqueName: 'ContosoReuse', displayName: 'Contoso Reuse', publisherPrefix: 'new' },
+ app: { name: 'Reuse App', description: '' },
+ entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', pluralName: 'Tickets', primaryAttribute: { schemaName: 'new_subject', displayName: 'Subject' }, columns: [{ schemaName: 'new_notes', displayName: 'Notes', type: 'Memo' }] }],
+ };
+}
+const ruleSpec = () => ({ ...baseSpec(), businessRules: [{ entity: 'new_ticket', name: 'Hide notes', conditions: [{ field: 'new_notes', operator: 'Equals', value: 'x', dataType: 'String' }], actions: [{ type: 'SetVisibility', field: 'new_notes', visible: false }] }] });
+const flowSpec = () => ({ ...baseSpec(), businessProcessFlows: [{ name: 'Ticket Handling', entity: 'new_ticket', stages: [{ name: 'Triage', steps: [{ name: 'Subject', field: 'new_subject' }] }] }] });
+
+// Just the surface those two phases touch: the workflow lookup, the membership read, and the add.
+function provisionOver({ rows, members, readFails = false }) {
+ const adds = [];
+ const reads = [];
+ return {
+ adds,
+ reads,
+ provision: {
+ queryRecords: async (entity, options) => {
+ reads.push(entity);
+ if (entity === 'workflow') return typeof rows === 'function' ? rows(options) : rows;
+ if (entity === 'solution') return [{ solutionid: SOLUTION_ID }];
+ if (entity === 'solutioncomponent') {
+ if (readFails) throw new Error('membership unreadable');
+ return members.map(([componenttype, objectid]) => ({ componenttype, objectid }));
+ }
+ return [{ publisherid: 'pub-1' }];
+ },
+ updateRecord: async () => undefined,
+ createArtifact: () => { throw new Error('a reused artifact must not be created'); },
+ addSolutionComponent: async (o) => { adds.push(o); },
+ },
+ };
+}
+
+const existingRule = { workflowid: 'rule-1', statecode: 1, createdon: '2026-01-01T00:00:00Z' };
+const existingFlow = { workflowid: 'flow-1', statecode: 1, createdon: '2026-01-01T00:00:00Z', uniquename: 'new_tickethandling' };
+
+async function build(spec, phase, over) {
+ const { sdk } = makeSimpleMockSdk();
+ const warnings = [];
+ const res = await runSdkBuild(spec, { sdk, provisionSdk: over.provision, apply: true, phases: [phase], warn: (w) => warnings.push(w) });
+ assert.equal(res.ok, true);
+ return warnings;
+}
+
+test('rebuild writes: a reused business rule the solution already holds is not added again', async () => {
+ const over = provisionOver({ rows: [existingRule], members: [[WORKFLOW, 'rule-1']] });
+ await build(ruleSpec(), 'business-rules', over);
+ assert.deepEqual(over.adds, []);
+});
+
+test('rebuild writes: a reused business rule the solution lacks is added again — the repair this re-assert exists for', async () => {
+ const over = provisionOver({ rows: [existingRule], members: [[WORKFLOW, 'some-other-rule'], [26, 'rule-1']] });
+ await build(ruleSpec(), 'business-rules', over);
+ assert.deepEqual(over.adds, [{ componentId: 'rule-1', componentType: WORKFLOW, solutionUniqueName: 'ContosoReuse' }]);
+});
+
+test('rebuild writes: a reused business rule is re-added when the membership cannot be read', async () => {
+ const over = provisionOver({ rows: [existingRule], members: [], readFails: true });
+ await build(ruleSpec(), 'business-rules', over);
+ assert.equal(over.adds.length, 1);
+});
+
+test('rebuild writes: a reused process flow the solution already holds is not added again', async () => {
+ const over = provisionOver({ rows: [existingFlow], members: [[WORKFLOW, 'flow-1']] });
+ await build(flowSpec(), 'business-process-flows', over);
+ assert.deepEqual(over.adds, []);
+});
+
+test('rebuild writes: a reused process flow the solution lacks is added again, and a failed add still only warns', async () => {
+ const over = provisionOver({ rows: [existingFlow], members: [] });
+ await build(flowSpec(), 'business-process-flows', over);
+ assert.deepEqual(over.adds, [{ componentId: 'flow-1', componentType: WORKFLOW, solutionUniqueName: 'ContosoReuse' }]);
+
+ const failing = provisionOver({ rows: [existingFlow], members: [] });
+ failing.provision.addSolutionComponent = async () => { throw new Error('component add refused'); };
+ const warnings = await build(flowSpec(), 'business-process-flows', failing);
+ assert.ok(warnings.some((w) => /could not be added to solution/.test(w)), warnings.join('\n'));
+});
+
+test('rebuild writes: the rule and the flow of one build share a single membership read', async () => {
+ // One `workflow` lookup serves both phases in this double: a flow is the category-4 row, a rule the other.
+ const over = provisionOver({
+ rows: (options) => (/category eq 4/.test((options && options.filter) || '') ? [existingFlow] : [existingRule]),
+ members: [[WORKFLOW, 'rule-1'], [WORKFLOW, 'flow-1']],
+ });
+ const { sdk } = makeSimpleMockSdk();
+ await runSdkBuild({ ...ruleSpec(), ...flowSpec() }, { sdk, provisionSdk: over.provision, apply: true, phases: ['business-rules', 'business-process-flows'], warn: () => undefined });
+ assert.deepEqual(over.adds, []);
+ assert.equal(over.reads.filter((e) => e === 'solutioncomponent').length, 1);
+});
diff --git a/plugins/model-apps/scripts/tests/run-tests.test.js b/plugins/model-apps/scripts/tests/run-tests.test.js
index 1fd1f223f..ae7eda130 100644
--- a/plugins/model-apps/scripts/tests/run-tests.test.js
+++ b/plugins/model-apps/scripts/tests/run-tests.test.js
@@ -4,6 +4,7 @@ const assert = require('node:assert');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
+const { execFileSync } = require('node:child_process');
const { pluginTestFiles, sdkTestSpec, summarize } = require('../run-tests.js');
test('pluginTestFiles discovers every *.test.js as a scripts/tests path, sorted', () => {
@@ -142,6 +143,46 @@ test('the model-apps CI workflow has a read-only token, cancels superseded runs,
assert.strictEqual(timeouts, jobCount, `every job must set timeout-minutes (${timeouts} set / ${jobCount} jobs)`);
});
+// The lexer's oracle tests (every sweep that asks TypeScript or Babel which tokens are data, and the differential
+// against the released lexer) skip themselves where the parsers are not installed, so the suite alone proves
+// nothing about them: one job must install the parsers and run the same suite with them. A text assertion again,
+// for the same reason: what matters is that the versions are exact, that nothing is installed into the plugin,
+// and that the three paths the tests read are set.
+test('the model-apps CI workflow runs the suite once with pinned TypeScript and Babel parsers and the released lexer', () => {
+ const wf = fs.readFileSync(WORKFLOW, 'utf8');
+ const start = wf.search(/^ {4}test-model-apps-lexer-oracles:\s*$/m);
+ assert.ok(start >= 0, 'a job must run the suite with the parsers');
+ const rest = wf.slice(start).split(/\r?\n/).slice(1);
+ const end = rest.findIndex((line) => /^ {4}[a-z0-9-]+:\s*$/i.test(line));
+ const job = (end === -1 ? rest : rest.slice(0, end)).join('\n');
+ // Exact versions: a range would let a new release change what the sweeps judge without a commit.
+ assert.match(job, /typescript@\d+\.\d+\.\d+(?![\w.-])/, 'TypeScript must be pinned to one version');
+ assert.match(job, /@babel\/parser@\d+\.\d+\.\d+(?![\w.-])/, 'Babel must be pinned to one version');
+ assert.doesNotMatch(job, /(?:typescript|@babel\/parser)@(?:latest|next|[\^~<>*])/, 'no range, no tag');
+ // Installed outside the plugin, without install scripts: the plugin ships no dependencies.
+ assert.match(job, /npm install --prefix "\$RUNNER_TEMP\/[^"]+"[^\n]*--ignore-scripts/, 'the parsers are installed under RUNNER_TEMP with --ignore-scripts');
+ assert.doesNotMatch(job, /npm (?:install|ci)(?![^\n]*--prefix)/, 'no install may run in the plugin or the repository');
+ // The three paths the tests read.
+ for (const name of ['TYPESCRIPT_ORACLE_PATH', 'BABEL_ORACLE_PATH', 'BASE_LIB_PATH']) {
+ assert.match(job, new RegExp(`echo "${name}=[^"]+" >> "\\$GITHUB_ENV"`), `${name} must be exported to the later steps`);
+ }
+ // The released lexer comes from the commit that released it, by its hash (a branch or a tag moves), and the suite
+ // is the plugin's own command.
+ const commit = /git fetch --no-tags --depth=1 origin ([0-9a-f]{40})\b/.exec(job);
+ assert.ok(commit, 'the released lexer is fetched by a full commit hash');
+ assert.match(job, /^ {14}run: node scripts\/run-tests\.js[ \t]*$/m, 'the plugin\'s own test command runs');
+ assert.match(job, /^ {14}working-directory: plugins\/model-apps[ \t]*$/m, 'from the plugin\'s directory');
+ // Where the history has that commit, it must be the release: a hash that names another commit would compare
+ // the lexer with the wrong one. (A shallow clone, which is what CI has, does not have it; the job fetches it.)
+ let release = null;
+ try {
+ release = execFileSync('git', ['show', `${commit[1]}:plugins/model-apps/.plugin/plugin.json`], { cwd: path.dirname(WORKFLOW), encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
+ } catch {
+ release = null;
+ }
+ if (release !== null) assert.strictEqual(JSON.parse(release).version, '2.13.0', 'the fetched commit is the 2.13.0 release');
+});
+
// --- committed lock files must not carry a registry URL ---------------------------------------
// `resolved` records the exact feed a package came from. Public npm is blocked on some Microsoft
// networks, so a contributor installing through an internal Azure Artifacts feed would rewrite
diff --git a/plugins/model-apps/scripts/tests/sdk-async-surface.test.js b/plugins/model-apps/scripts/tests/sdk-async-surface.test.js
index 66b6286a0..d71b66e88 100644
--- a/plugins/model-apps/scripts/tests/sdk-async-surface.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-async-surface.test.js
@@ -858,30 +858,254 @@ test('an unparseable file is REPORTED, never silently skipped', () => {
//
// Checked by SOURCE SCAN because the factories are CLI-internal — none is exported, so there is no
// seam to drive a construction failure through. The property checked is the one that matters
-// (construction happens inside a guarded region that cleans up), not a brittle line-order heuristic:
+// (the construction sits inside the block of a `try` whose catch or finally cleans up), not a brittle line-order heuristic:
// an earlier attempt compared `const cleanup` and `initWorkspace` offsets and wrongly flagged
// teardown-model-app.js, which declares cleanup after the init but inside a try whose catch removes
// the directory.
+//
+// Where a helper builds the SDK (verify-model-app.js, below its factory) the construction is not written in the factory's own tree,
+// so what is checked for it is its place in the text: after the directory is made, and behind the guarding `try`.
+//
+// The guard is the `catch` or `finally` of the first `try` after the directory is made that sits in the same function as
+// the `mkdtempSync` call — the one the SDK construction is behind — and no other clause in the file. Not simply the first
+// `try` in the text: verify-model-app.js's `dispose` helper has a `try` of its own between the `mkdtempSync` and the guard.
+// And not a cleanup elsewhere, such as a later `finally` that removes a download's folder: that says nothing about a
+// workspace whose construction failed, so it must neither satisfy this check nor, when it changes shape, break it. Both
+// happened while the check accepted any cleanup call within 200 characters of any later `catch` or `finally`:
+// verify-model-app.js passed through an unrelated `finally { fs.rmSync(...) }` further down (the cleanup its own guard
+// calls, `dispose()`, was not one the pattern knew), and went red when that `finally` called a helper instead.
+//
+// The syntax tree is read, not the text: a cleanup named in a comment or a string is not one, and the end of the `try`
+// is where the parser says it is.
+//
+// What the guard may remove the directory with: `cleanup()` (build, download and provision-entities hand one to their
+// caller), `dispose()` (verify's) and `fs.rmSync()` itself (ai-preflight, provision-solution, teardown).
+const WORKSPACE_CLEANUP_CALLS = new Set(['cleanup', 'dispose', 'rmSync']);
+const FUNCTION_NODES = new Set(['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression']);
+
+/** The name a call goes by: `cleanup()` is 'cleanup', `fs.rmSync()` and `require('fs').rmSync()` are 'rmSync'; null when it has none. */
+function calledName(call) {
+ return call.callee.type === 'Identifier' ? call.callee.name : calleeMethodName(call.callee);
+}
+
+/**
+ * How `src` guards the throwaway workspace it makes. null when it makes none — no `mkdtempSync`, or no `createMakerSdk` call
+ * to guard — else `{ problem }`: null when the guard is sound, otherwise what is wrong with it. The construction is found by
+ * position, as the first one after the directory is made (verify-model-app.js builds its SDK in a helper below the factory).
+ */
+function throwawayWorkspaceGuard(src) {
+ const parsed = parseForGuard(src);
+ if (!parsed) return { problem: 'the source did not parse, so the guard could not be inspected' };
+ const made = [];
+ const constructions = [];
+ const tries = [];
+ walk(parsed.ast, (node, ancestors) => {
+ // `ancestors` is closest first: the first function in it is the one this node is written in (null at the top level).
+ const scope = ancestors.find((a) => FUNCTION_NODES.has(a.type)) || null;
+ if (node.type === 'Identifier' && node.name === 'mkdtempSync') made.push({ node, scope });
+ else if (node.type === 'CallExpression' && calledName(node) === 'createMakerSdk') constructions.push({ node, scope });
+ else if (node.type === 'TryStatement') tries.push({ node, scope });
+ });
+ const firstAfter = (found, offset, accept = () => true) => found
+ .filter((f) => f.node.start > offset && accept(f))
+ .sort((a, b) => a.node.start - b.node.start)[0];
+ const dirMade = firstAfter(made, -1);
+ if (!dirMade || constructions.length === 0) return null;
+ const construction = firstAfter(constructions, dirMade.node.start);
+ if (!construction) {
+ return { problem: 'no createMakerSdk call follows mkdtempSync, so there is no construction to see inside the guard — it must come after the directory is made' };
+ }
+ const guarded = firstAfter(tries, dirMade.node.start, (f) => f.scope === dirMade.scope);
+ // A construction written in the function that made the directory must lie in the BLOCK of that try — one before the try, or in its
+ // catch or finally, or after it, is outside the guard. One written in another function (verify's makeProvision, which the guarded
+ // block calls) has no place in this tree to compare with the block, so only its order against the try is checked.
+ const insideGuard = (found) => (found.scope === dirMade.scope
+ ? guarded.node.block.start <= found.node.start && found.node.end <= guarded.node.block.end
+ : guarded.node.start <= found.node.start);
+ if (!guarded || !insideGuard(construction)) {
+ return {
+ problem: 'the createMakerSdk construction after mkdtempSync must be inside a try — the constructor builds the '
+ + 'filesystem adapter and can throw, and the caller\'s finally is unreachable until this function returns',
+ };
+ }
+ // …and the guard must actually reclaim the directory, not merely swallow the error.
+ let removes = false;
+ for (const clause of [guarded.node.handler && guarded.node.handler.body, guarded.node.finalizer]) {
+ walk(clause, (node) => {
+ if (node.type === 'CallExpression' && WORKSPACE_CLEANUP_CALLS.has(calledName(node))) removes = true;
+ });
+ }
+ return {
+ problem: removes ? null : 'the guard around SDK construction — the catch or finally of the first try after mkdtempSync, in the '
+ + 'function that made it — must remove the throwaway directory (cleanup(), dispose() or rmSync) before the error leaves',
+ };
+}
+
+// The check on sources small enough to read. `factory` is the plain layout: the guard is a clause of the one `try`. `verifyShaped`
+// is verify-model-app.js's: a `dispose()` helper defined before the guard, with a `try` of its own — the first `try` after the
+// `mkdtempSync` in the text — the guard calling it, the construction behind a helper, and a later, unrelated function that removes
+// another folder in a `finally`: the one thing the old check mistook for the guard.
+const factory = (guard) => `
+ const fs = require('node:fs');
+ async function make(env) {
+ const dir = fs.mkdtempSync('model-app-');
+ const cleanup = () => fs.rmSync(dir, { recursive: true, force: true });
+ try {
+ const sdk = createMakerSdk({ instanceUrl: env });
+ await sdk.initWorkspace();
+ return { sdk, cleanup };
+ } ${guard}
+ }`;
+const verifyShaped = ({ guard, elsewhere }) => `
+ const fs = require('node:fs');
+ async function throwawaySdk(env) {
+ const dir = fs.mkdtempSync('verify-dashboard-');
+ const dispose = () => { try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* best-effort */ } };
+ try {
+ return { sdk: await makeProvision(env, dir), dispose };
+ } ${guard}
+ }
+ async function makeProvision(env, dir) {
+ const sdk = createMakerSdk({ instanceUrl: env });
+ await sdk.initWorkspace();
+ return sdk;
+ }
+ async function downloadPage(id) {
+ const outDir = fs.mkdtempSync('verify-page-');
+ try { return await download(id, outDir); } finally { ${elsewhere} }
+ }`;
+const VERIFY_GUARD = 'catch (e) { dispose(); throw e; }';
+const FOLDER_CLEANUP = 'try { fs.rmSync(outDir, { recursive: true, force: true }); } catch { /* leave the temp dir */ }';
+const GUARD_PROBLEM = /must remove the throwaway directory/;
+
+test('the guard check accepts the cleanups the entry points use, in a catch or in a finally', () => {
+ for (const guard of [
+ 'catch (err) { cleanup(); throw err; }',
+ 'catch (err) { dispose(); throw err; }',
+ 'catch (err) { try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* best-effort */ } throw err; }',
+ 'finally { fs.rmSync(dir, { recursive: true, force: true }); }',
+ 'catch (err) { error = err; } finally { require(\'fs\').rmSync(dir, { force: true }); }',
+ ]) {
+ assert.deepStrictEqual(throwawayWorkspaceGuard(factory(guard)), { problem: null }, guard);
+ }
+});
+
+test('the guard check does not take for a cleanup what is not one: no clause, a comment, a string, a helper it does not know', () => {
+ for (const guard of [
+ 'catch (err) { throw err; }',
+ 'catch (err) { /* cleanup(); */ throw err; }',
+ 'catch (err) { console.error("cleanup()"); throw err; }',
+ 'catch (err) { removeWorkspace(dir); throw err; }',
+ 'catch (err) { error = err; } finally { done(); }',
+ ]) {
+ // `cleanup` is defined, with its `fs.rmSync`, before the `try` in every one of these: that is not the guard either.
+ assert.match(throwawayWorkspaceGuard(factory(guard)).problem, GUARD_PROBLEM, guard);
+ }
+});
+
+test('MUTATION: a guard whose cleanup is gone is caught, although another cleanup follows later in the file', () => {
+ assert.deepStrictEqual(throwawayWorkspaceGuard(verifyShaped({ guard: VERIFY_GUARD, elsewhere: FOLDER_CLEANUP })), { problem: null }, 'the unmutated layout is sound');
+ const mutated = verifyShaped({ guard: 'catch (e) { throw e; }', elsewhere: FOLDER_CLEANUP });
+ // The later `finally` still removes a folder, and that is the cleanup the old check took for the guard's.
+ assert.ok(/finally \{ try \{ fs\.rmSync\(outDir/.test(mutated));
+ assert.match(throwawayWorkspaceGuard(mutated).problem, GUARD_PROBLEM);
+});
+
+test('a cleanup elsewhere in the file may change shape without touching the verdict on the guard', () => {
+ for (const elsewhere of [FOLDER_CLEANUP, 'removeDownloadDir(outDir);', '']) {
+ assert.deepStrictEqual(throwawayWorkspaceGuard(verifyShaped({ guard: VERIFY_GUARD, elsewhere })), { problem: null }, elsewhere);
+ }
+});
+
+test('the guard check flags a construction that comes before any try, and one that is not after the directory is made', () => {
+ const src = `
+ async function make(env) {
+ const dir = fs.mkdtempSync('model-app-');
+ const sdk = createMakerSdk({ instanceUrl: env });
+ try { await sdk.initWorkspace(); } catch (err) { cleanup(); throw err; }
+ return sdk;
+ }`;
+ assert.match(throwawayWorkspaceGuard(src).problem, /must be inside a try/);
+ const before = `
+ function build(env) { return createMakerSdk({ instanceUrl: env }); }
+ async function make(env) {
+ const dir = fs.mkdtempSync('model-app-');
+ try { return { sdk: build(env), dir }; } catch (err) { cleanup(); throw err; }
+ }`;
+ assert.match(throwawayWorkspaceGuard(before).problem, /no createMakerSdk call follows mkdtempSync/);
+});
+
+test('the guard check refuses a construction that is not in the block of the try that guards it — before the try, in its catch, or after it — and keeps its order-only rule for a helper', () => {
+ const inFunction = (beforeTry, inTry, afterTry) => `
+ const fs = require('node:fs');
+ async function make(env) {
+ const dir = fs.mkdtempSync('model-app-');
+ ${beforeTry}
+ try {
+ ${inTry}
+ } catch (err) { fs.rmSync(dir, { recursive: true, force: true }); throw err; }
+ ${afterTry}
+ }`;
+ const build = 'createMakerSdk({ instanceUrl: env })';
+ // The sound layout, and then the same try with the construction moved out of its block.
+ assert.deepStrictEqual(throwawayWorkspaceGuard(inFunction('', `const sdk = ${build}; await sdk.initWorkspace();`, '')), { problem: null });
+ // A try of its own comes first and the real guard follows: the construction sits between them, after the first try and before the guarding one.
+ assert.match(throwawayWorkspaceGuard(inFunction(`try { fs.accessSync(dir); } catch (err) { fs.rmSync(dir, { recursive: true, force: true }); throw err; } const early = ${build};`, 'await later();', '')).problem, /must be inside a try/);
+ assert.match(throwawayWorkspaceGuard(inFunction('', 'await later();', `const late = ${build};`)).problem, /must be inside a try/);
+ // In the catch of the guarding try: a construction that fails there is not behind the cleanup the catch runs.
+ const inCatch = `
+ const fs = require('node:fs');
+ async function make(env) {
+ const dir = fs.mkdtempSync('model-app-');
+ try { await ready(); } catch (err) { const sdk = ${build}; fs.rmSync(dir, { recursive: true, force: true }); throw err; }
+ }`;
+ assert.match(throwawayWorkspaceGuard(inCatch).problem, /must be inside a try/);
+});
+
+test('the guard check counts only the catch and the finally of the guarding try: a cleanup defined or called in its block is not the guard', () => {
+ // teardown-model-app.js defines `cleanup` inside the guarded block, so a scan that walked the whole `try` would take that for the guard.
+ for (const inTry of [
+ 'const cleanup = () => fs.rmSync(dir, { recursive: true, force: true });',
+ 'cleanup();',
+ 'fs.rmSync(dir, { recursive: true, force: true });',
+ 'dispose();',
+ ]) {
+ const src = `
+ const fs = require('node:fs');
+ async function make(env) {
+ const dir = fs.mkdtempSync('model-app-');
+ try {
+ ${inTry}
+ const sdk = createMakerSdk({ instanceUrl: env });
+ await sdk.initWorkspace();
+ return { sdk };
+ } catch (err) { throw err; }
+ }`;
+ assert.match(throwawayWorkspaceGuard(src).problem, GUARD_PROBLEM, inTry);
+ }
+});
+
+test('the guard check has nothing to say about a file that makes no workspace or builds no SDK, and reports one it cannot parse', () => {
+ assert.strictEqual(throwawayWorkspaceGuard('const sdk = createMakerSdk({});'), null);
+ assert.strictEqual(throwawayWorkspaceGuard('const dir = fs.mkdtempSync("x-"); try { run(dir); } finally { fs.rmSync(dir); }'), null);
+ assert.match(throwawayWorkspaceGuard('const dir = fs.mkdtempSync("x-"); createMakerSdk(;;;(').problem, /did not parse/);
+});
+
test('every CLI that mints a throwaway workspace constructs the SDK INSIDE its cleanup guard', () => {
const dir = path.join(__dirname, '..');
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.js'));
const checked = [];
for (const file of files) {
const src = fs.readFileSync(path.join(dir, file), 'utf8');
- const mk = src.indexOf('mkdtempSync');
- if (mk < 0 || !/createMakerSdk\(/.test(src)) continue;
- const tryAt = src.indexOf('try {', mk);
- const ctorAt = src.indexOf('createMakerSdk(', mk);
- assert.ok(tryAt >= 0 && tryAt < ctorAt,
- `${file}: the createMakerSdk construction after mkdtempSync must be inside a try — the constructor builds the `
- + 'filesystem adapter and can throw, and the caller\'s finally is unreachable until this function returns');
- // …and the guard must actually reclaim the directory, not merely swallow the error.
- const after = src.slice(tryAt);
- assert.ok(/catch[\s\S]{0,200}?(cleanup\(\)|rmSync)/.test(after) || /finally[\s\S]{0,200}?(cleanup\(\)|rmSync)/.test(after),
- `${file}: the guard around SDK construction must remove the throwaway directory (cleanup()/rmSync) before rethrowing`);
+ if (!src.includes('mkdtempSync') || !/createMakerSdk\(/.test(src)) continue;
+ const guard = throwawayWorkspaceGuard(src);
+ if (!guard) continue;
+ assert.ok(guard.problem === null, `${file}: ${guard.problem}`);
checked.push(file);
}
- // A scan that matches nothing "passes" forever. These are the five entry points that own a
- // throwaway workspace today; if one is renamed the count changes and this fails loudly.
- assert.ok(checked.length >= 5, `expected to scan at least 5 entry points, scanned ${checked.length}: ${checked.join(', ')}`);
+ // A scan that matches nothing "passes" forever. These are the seven entry points that own a
+ // throwaway workspace today, named below as well as counted, so that none can drop out of the scan while the count still holds.
+ const entryPoints = ['ai-preflight.js', 'build-model-app.js', 'download-model-app.js', 'provision-entities.js', 'provision-solution.js', 'teardown-model-app.js', 'verify-model-app.js'];
+ for (const entry of entryPoints) assert.ok(checked.includes(entry), `${entry} was not scanned; scanned ${checked.join(', ')}`);
+ assert.ok(checked.length >= entryPoints.length, `expected to scan at least ${entryPoints.length} entry points, scanned ${checked.length}: ${checked.join(', ')}`);
});
\ No newline at end of file
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.js
index 245039de1..5456f16ff 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
@@ -12,7 +12,9 @@ const assert = require('node:assert');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
-const { runSdkBuild } = require('../lib/sdk-build.js');
+const { runSdkBuild, appUniqueName } = require('../lib/sdk-build.js');
+const { writeBaseline, readBaseline } = require('../lib/deployed-baseline.js');
+const { sha256 } = require('../lib/hash.js');
const { currentReadSdk } = require('./helpers/app-membership-sdk.js');
const { OBJECT_DIVISION_PAGE, MISREAD_PAGES, HIDDEN_CALL_PAGE, PREFIX_INCREMENT_PAGE, 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');
@@ -87,6 +89,19 @@ function mockSdk(opts = {}) {
pushArtifact: async (t, id) => ({ type: t, id, saved: true, shipped: false, publish: { kind: 'notRequested' } }),
addSolutionComponent: async (o) => { calls.push({ name: 'addSolutionComponent', args: [o] }); },
publishArtifact: async (type, id) => ({ type, id, shipped: true, publish: { kind: 'verified' } }),
+ // The shared-page scan's reads through the client: the list of apps (the published ones are all there are here, none was never published) and the other apps'
+ // saved layer, which is each app's published sitemap while nothing is pending.
+ dataverse: {
+ get: async (url) => {
+ if (url.startsWith('/appmodules/')) {
+ const value = [{ appmoduleid: APP_ID, appmoduleidunique: SELF_UNIQUE_VALUE, uniquename: opts.selfAppUnique, componentstate: 0 }];
+ (opts.otherApps || []).forEach((a, i) => value.push({ appmoduleid: `app-${i + 2}`, appmoduleidunique: `uv-${i + 2}`, uniquename: a.uniquename, componentstate: 0 }));
+ return { status: 200, body: { value } };
+ }
+ if (url.startsWith('/sitemaps/')) return { status: 200, body: { value: (opts.otherApps || []).map((a, i) => ({ sitemapid: `sm-${i + 2}`, sitemapxml: a.sitemapxml || '<SiteMap/>', componentstate: 0 })) } };
+ return { status: 404, body: null };
+ },
+ },
};
return { sdk, calls };
}
@@ -866,6 +881,553 @@ test('deploy: a page with a present-but-blank agent message HALTS before any upl
} finally { fs.rmSync(appDir, { recursive: true, force: true }); }
});
+// ── The Griffel check in the build's pre-write scan (AB#6691124) ────────────────────────────────────────────────────────────────────
+// Griffel drops ten CSS shorthands from a `makeStyles` object at runtime and nothing between the author and the browser notices, so a page that writes one deploys without its
+// border, colour or reset. /app-builder pages come from workers that have no shell, from hand edits after a download, and from specs written by hand: every one of them reaches this
+// scan before a page is created or updated, so this is where the defect is stopped whatever instructions were or were not followed.
+const GRIFFEL_IMPORT = "import { makeStyles, tokens } from '@fluentui/react-components';\n";
+const GRIFFEL_BAD = `${GRIFFEL_IMPORT}const useStyles = makeStyles({\n root: {\n borderWidth: '1px',\n padding: '4px',\n },\n hover: { ':hover': { borderColor: 'red' } },\n});\nexport default function Detail() { return null; }\n`;
+const GRIFFEL_CLEAN = `${GRIFFEL_IMPORT}// borderWidth: 1\nconst useStyles = makeStyles({ root: { borderTopWidth: '1px', padding: '4px' } });\nexport default function Detail() { return <div style={{ borderColor: 'red' }}>{'borderStyle'}</div>; }\n`;
+// Valid TSX that the lexer cannot read for certain: after `if (s) { }` a `/` could start a regex or divide, so the makeStyles call below it is not one the checker can vouch for.
+const GRIFFEL_UNREADABLE = `${GRIFFEL_IMPORT}export function skip(s: string) { if (s) { } /x/.test(s); }\nconst useStyles = makeStyles({ root: { padding: '4px' } });\nexport default function Detail() { return null; }\n`;
+// A style object written elsewhere: its keys — here one Griffel drops — are not in the call, so the checker cannot see them.
+const GRIFFEL_INDIRECT = `${GRIFFEL_IMPORT}const styles = { root: { borderWidth: '1px' } };\nconst useStyles = makeStyles(styles);\nexport default function Detail() { return null; }\n`;
+const BOTH_WAYS_OUT = 'Deleting a key changes nothing on screen, because Griffel never applied it; writing the longhands (for `all`, the properties you want) makes the style start to render, which changes how the page looks.';
+
+// What an earlier APPLY left in last-applied.json, read back as build-model-app.js reads it for the next build (`opts.baselineSpec`): the real writer and the real reader, so each page's
+// `__contentSha` is the hash the changed-only flow records, of the source as it is on disk NOW — call it before editing a page to record "the source as last applied". The reader returns
+// the snapshot only for the app and environment it describes, as it does for a build.
+const BASELINE_ENV = 'https://contoso.crm.dynamics.com';
+function recordApply(spec, appDir) {
+ const workspace = path.join(appDir, '.maker-workspace');
+ const identity = { environment: BASELINE_ENV, appUniqueName: appUniqueName(spec) };
+ writeBaseline(workspace, spec, { appDir, ...identity, created: { pages: { overview: OVERVIEW_ID, detail: DETAIL_ID } } });
+ return readBaseline(workspace, identity);
+}
+// A rebuild of the two-page app with `detail` as given: both pages are live and bound by the manifest, and neither links to the other (so no source is rewritten on its way out).
+// `rebuild({ baselineSpec })` runs the pages phase; its `warnings` are what the build said through `warn` about Griffel (it also warns about other things — an organization language it could not read, say).
+function deployedApp(detail) {
+ const { appDir, spec } = makeTwoPageApp();
+ fs.writeFileSync(path.join(appDir, 'overview.tsx'), 'export default function Overview(){ return null; }', 'utf8');
+ fs.writeFileSync(path.join(appDir, 'detail.tsx'), detail, 'utf8');
+ spec.pages[0].navigatesTo = undefined;
+ const live = [{ pageId: OVERVIEW_ID, name: 'Overview' }, { pageId: DETAIL_ID, name: 'Detail' }];
+ const manifest = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: OVERVIEW_ID }, { key: 'detail', name: 'Detail', pageId: DETAIL_ID }] }), 'utf8').toString('base64');
+ const rebuild = (extra = {}) => {
+ const { sdk } = mockSdk({ pageManifest: manifest, liveSitemapXml: pageSitemap([OVERVIEW_ID, DETAIL_ID]), pageRows: live.map((p) => ({ uxagentprojectid: p.pageId, name: p.name })) });
+ const genpageCli = mockGenpageCli(live);
+ const warnings = [];
+ return { genpageCli, warnings, run: () => runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: PHASES, warn: (m) => { if (/Griffel/.test(m)) warnings.push(m); }, ...extra }) };
+ };
+ return { appDir, spec, rebuild, edit: (text) => fs.writeFileSync(path.join(appDir, 'detail.tsx'), text, 'utf8'), cleanup: () => fs.rmSync(appDir, { recursive: true, force: true }) };
+}
+
+test('deploy: a NEW page whose makeStyles drops a Griffel shorthand HALTS before any upload, naming the page, each key\'s line and column, the longhands and both ways out', async () => {
+ const { appDir, spec } = makeTwoPageApp();
+ try {
+ fs.writeFileSync(path.join(appDir, 'detail.tsx'), GRIFFEL_BAD, 'utf8');
+ const { sdk } = mockSdk();
+ const genpageCli = mockGenpageCli();
+ await assert.rejects(
+ runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: PHASES }),
+ (e) => {
+ assert.strictEqual(e.phase, 'pages');
+ assert.strictEqual(e.code, 'pages-griffel-shorthand');
+ assert.strictEqual(e.recoverable, false);
+ assert.ok(e.message.startsWith('page "Detail" writes CSS that Griffel drops at runtime, so the page would deploy without it — '), e.message);
+ assert.ok(e.message.includes('detail.tsx:4:5: `borderWidth` is not supported by Griffel'), 'where the first key is');
+ assert.ok(e.message.includes('detail.tsx:7:24: `borderColor` is not supported by Griffel'), 'and the second');
+ assert.ok(e.message.includes('Write the longhands instead: borderTopWidth, borderRightWidth, borderBottomWidth, borderLeftWidth.'));
+ assert.ok(e.message.includes(BOTH_WAYS_OUT), 'and what each way out does: deleting the key keeps the look, the longhands start to render');
+ assert.match(e.message, /Fix them in the page's source \(`node scripts\/check-griffel-styles\.js --file <page\.tsx>` lists every one\), then re-run\.$/);
+ assert.doesNotMatch(e.message, /Its source changed since/, 'a page that does not exist yet has no earlier source to have changed from');
+ return true;
+ }
+ );
+ assert.strictEqual(genpageCli.uploads.length, 0, 'the scan rejects before any page is created — not even the page that is clean');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// The halt's text opens with the page's name, and buildModelApp decides from the text whether a halt is a transient error to run the build again for (isTransientHalt). A page called
+// "SQL Timeout Report" must not make this refusal read as one: it is raised before anything in the pages phase is written, so a run again can only repeat it — three more times, after every
+// earlier phase, with a log that blames the service. The words alone DO read as transient (the control), so it is the marker that is tested; the receipt halt carries the same one.
+test('deploy: the Griffel halt of a page whose name reads as a transient error is not retried by the build', async () => {
+ const { buildModelApp, isTransientHalt } = require('../build-model-app.js');
+ const { appDir, spec } = onePageApp('SQL Timeout Report');
+ try {
+ fs.writeFileSync(path.join(appDir, 'p.tsx'), GRIFFEL_BAD, 'utf8');
+ const genpageCli = mockGenpageCli();
+ const { sdk } = mockSdk();
+ const lines = [];
+ let halt = null;
+ try {
+ await buildModelApp(spec, { apply: true, env: 'https://contoso.crm.dynamics.com', appDir, retryDelayMs: 0 }, {
+ sdk, provisionSdk: sdk, genpageCli, sleep: async () => {}, log: (m) => lines.push(m),
+ discoverOpDiffState: async () => ({ collision: { appExists: false, solutionExists: false }, forms: [], sitemap: null }),
+ });
+ } catch (e) { halt = e; }
+ assert.ok(halt, 'the build halts');
+ assert.strictEqual(halt.code, 'pages-griffel-shorthand');
+ assert.match(halt.message, /^page "SQL Timeout Report" writes CSS that Griffel drops at runtime/);
+ assert.strictEqual(genpageCli.uploads.length, 0, 'before any page is created');
+ assert.deepStrictEqual(lines.filter((l) => /transient error|retrying/.test(l)), [], 'and no retry');
+ assert.strictEqual(isTransientHalt(halt, { spec }), false, 'the halt reads as final');
+ assert.strictEqual(halt.transient, false, 'because it says so');
+ assert.strictEqual(isTransientHalt(new Error(halt.message), { spec }), true, 'its words alone would have read as a transient error');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+test('deploy: the Griffel check holds for a NEW navigation page, whose canonical source is checked ahead of the resolved copy', async () => {
+ const nav = makeTwoPageApp();
+ try {
+ fs.writeFileSync(path.join(nav.appDir, 'overview.tsx'), `${GRIFFEL_IMPORT}const s = makeStyles({ root: { borderStyle: 'solid' } });\nexport default function Overview(){ ${NAV('detail')} return null; }\n`, 'utf8');
+ const genpageCli = mockGenpageCli();
+ await assert.rejects(
+ runSdkBuild(nav.spec, { sdk: mockSdk().sdk, apply: true, env: 'https://x', appDir: nav.appDir, genpageCli, phases: PHASES }),
+ (e) => e && e.code === 'pages-griffel-shorthand' && /page "Overview" writes CSS[\s\S]*overview\.tsx:2:[0-9]+: `borderStyle`/.test(e.message)
+ );
+ assert.strictEqual(genpageCli.uploads.length, 0, 'no target was minted for the navigation either');
+ } finally { fs.rmSync(nav.appDir, { recursive: true, force: true }); }
+});
+
+// A page deployed by an earlier release can carry a key Griffel drops (its only guard was a grep for `borderWidth`): `borderColor` under `:hover` passed. Sending the same bytes again ships
+// nothing new, and stopping a rebuild over a page nobody touched — after the earlier phases have written — leaves one way through, editing it, whose longhands CHANGE how the page renders.
+test('deploy: a page already deployed with a dropped key and sent again UNCHANGED is warned about, not refused — each key named, with both ways out', async () => {
+ const app = deployedApp(GRIFFEL_BAD);
+ try {
+ // The last apply sent this very source: last-applied.json records its hash.
+ const baselineSpec = recordApply(app.spec, app.appDir);
+ const r = app.rebuild({ baselineSpec });
+ await r.run();
+ assert.deepStrictEqual(r.genpageCli.uploads.map((u) => u.name).sort(), ['Detail', 'Overview'], 'both pages are updated, as any rebuild does');
+ assert.strictEqual(r.genpageCli.uploads.find((u) => u.name === 'Detail').content, GRIFFEL_BAD, 'and what is sent is the source, untouched');
+ assert.strictEqual(r.warnings.length, 1, 'one warning, for the page that has the keys — the clean page says nothing');
+ const [warning] = r.warnings;
+ assert.ok(warning.startsWith('page "Detail" is already deployed, and its source is the one the last build recorded for it, so this build sends it again as it is and goes on. '), warning);
+ assert.ok(warning.includes('detail.tsx:4:5: `borderWidth` is not supported by Griffel'), 'the first key, where it is');
+ assert.ok(warning.includes('detail.tsx:7:24: `borderColor` is not supported by Griffel'), 'and the second');
+ assert.ok(warning.includes(BOTH_WAYS_OUT), 'both ways out');
+ assert.match(warning, /lists every one\); once the page's source changes, the build holds it to the check and stops on anything the check still reports\.$/);
+ // A caller that does not listen (no `warn`) goes on all the same: the warning is advice, never a condition.
+ await app.rebuild({ baselineSpec, warn: undefined }).run();
+ } finally { app.cleanup(); }
+});
+
+// A page that links to another is uploaded as a RESOLVED copy (the target's id where its source has a PAGEREF_ name), and what an apply records is the hash of the SOURCE in the app folder.
+// The comparison is with that source, so such a page is told "unchanged" like any other — and an edit to the source is what changes it.
+test('deploy: a deployed NAVIGATION page with a dropped key, sent again unchanged, is warned about — its source is compared, not the resolved copy that is uploaded', async () => {
+ const { appDir, spec } = makeTwoPageApp(); // overview links to detail
+ try {
+ const overview = (padding) => `${GRIFFEL_IMPORT}const s = makeStyles({ root: { borderColor: 'red', padding: '${padding}' } });\nexport default function Overview(){ ${NAV('detail')} return null; }\n`;
+ fs.writeFileSync(path.join(appDir, 'overview.tsx'), overview('4px'), 'utf8');
+ const baselineSpec = recordApply(spec, appDir);
+ const live = [{ pageId: OVERVIEW_ID, name: 'Overview' }, { pageId: DETAIL_ID, name: 'Detail' }];
+ const manifest = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: OVERVIEW_ID }, { key: 'detail', name: 'Detail', pageId: DETAIL_ID }] }), 'utf8').toString('base64');
+ const rebuild = (extra) => {
+ const { sdk } = mockSdk({ pageManifest: manifest, liveSitemapXml: pageSitemap([OVERVIEW_ID, DETAIL_ID]), pageRows: live.map((p) => ({ uxagentprojectid: p.pageId, name: p.name })) });
+ const genpageCli = mockGenpageCli(live);
+ const warnings = [];
+ return { genpageCli, warnings, run: () => runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: PHASES, baselineSpec, warn: (m) => { if (/Griffel/.test(m)) warnings.push(m); }, ...extra }) };
+ };
+ const same = rebuild();
+ await same.run();
+ const sent = same.genpageCli.uploads.find((u) => u.name === 'Overview');
+ assert.ok(sent.content.includes(DETAIL_ID) && !sent.content.includes('PAGEREF_'), 'what is uploaded is the resolved copy, which is not the source whose hash was recorded');
+ assert.strictEqual(same.warnings.length, 1);
+ assert.match(same.warnings[0], /^page "Overview" is already deployed, and its source is the one the last build recorded for it/);
+ assert.ok(same.warnings[0].includes('overview.tsx:2:'), 'the key is named where it is in the source');
+ // An edit to the source is a change, resolved copy or not.
+ fs.writeFileSync(path.join(appDir, 'overview.tsx'), overview('8px'), 'utf8');
+ const edited = rebuild();
+ await assert.rejects(edited.run(), (e) => e.code === 'pages-griffel-shorthand' && /^page "Overview" writes CSS/.test(e.message) && /Its source changed since the last build recorded for it/.test(e.message));
+ assert.deepStrictEqual(edited.genpageCli.uploads, [], 'nothing was written');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+test('deploy: a page that is UPDATED with a changed source is held to the check even when the key was already there — nothing is written', async () => {
+ const app = deployedApp(GRIFFEL_BAD);
+ try {
+ const baselineSpec = recordApply(app.spec, app.appDir);
+ // The maker edits the page's text and keeps the shorthand: its hash no longer matches the last apply's, so this build would ship a CHANGED page that still drops the key.
+ app.edit(GRIFFEL_BAD.replace("padding: '4px'", "padding: '8px'"));
+ const r = app.rebuild({ baselineSpec });
+ await assert.rejects(r.run(), (e) => {
+ assert.strictEqual(e.phase, 'pages');
+ assert.strictEqual(e.code, 'pages-griffel-shorthand');
+ assert.strictEqual(e.recoverable, false);
+ assert.ok(e.message.startsWith('page "Detail" writes CSS that Griffel drops at runtime, so the page would deploy without it — '), e.message);
+ assert.ok(e.message.includes('detail.tsx:4:5: `borderWidth`') && e.message.includes('detail.tsx:7:24: `borderColor`'), 'each key, where it is');
+ assert.ok(e.message.includes(BOTH_WAYS_OUT), 'both ways out');
+ assert.ok(e.message.includes('Its source changed since the last build recorded for it, so it is held to the check as a new page is; left as it was, it would only be warned about. Fix them in the page\'s source'), 'and why this page is held to it');
+ return true;
+ });
+ assert.deepStrictEqual(r.genpageCli.uploads, [], 'neither page was written');
+ assert.deepStrictEqual(r.warnings, [], 'a halt says why it halted, not what it would have let through');
+ // Adding a key to a page that was clean is the same: it changed, and now drops one.
+ const clean = deployedApp(GRIFFEL_CLEAN);
+ try {
+ const recorded = recordApply(clean.spec, clean.appDir);
+ clean.edit(GRIFFEL_BAD);
+ const again = clean.rebuild({ baselineSpec: recorded });
+ await assert.rejects(again.run(), (e) => e.code === 'pages-griffel-shorthand' && /Its source changed since the last build recorded for it/.test(e.message));
+ assert.deepStrictEqual(again.genpageCli.uploads, []);
+ } finally { clean.cleanup(); }
+ // Control: the maker deletes the keys (no change on screen): the page is changed and clean, and goes up with no warning.
+ app.edit(GRIFFEL_CLEAN);
+ const fixed = app.rebuild({ baselineSpec });
+ await fixed.run();
+ assert.deepStrictEqual(fixed.genpageCli.uploads.map((u) => u.name).sort(), ['Detail', 'Overview']);
+ assert.deepStrictEqual(fixed.warnings, []);
+ } finally { app.cleanup(); }
+});
+
+// "No record" is the case the build cannot tell: a workspace that is new, moved or cleared, or an apply that predates the record. The page exists in the environment, so an earlier release
+// deployed it as it is — the key silently dropped — and refusing it now would stop a rebuild that release completed. It fails open, with a warning that says so. A page that does NOT exist
+// is created, and no record can change that: what would be deployed is new.
+test('deploy: a page that exists but has no record in this workspace is warned about, not refused — and a page that does not exist yet is still held to the check', async () => {
+ const app = deployedApp(GRIFFEL_BAD);
+ try {
+ const recorded = recordApply(app.spec, app.appDir);
+ const unreadableThen = { ...recorded, pages: recorded.pages.map((p) => (p.key === 'detail' ? { ...p, __contentSha: null } : p)) };
+ for (const [what, baselineSpec] of [
+ ['no baseline at all (a new or cleared workspace, or another app or environment)', undefined],
+ ['a baseline with no record of this page', { ...recorded, pages: recorded.pages.filter((p) => p.key !== 'detail') }],
+ ['a record with no hash — the source could not be read then', unreadableThen],
+ ]) {
+ const r = app.rebuild({ baselineSpec });
+ await r.run();
+ assert.deepStrictEqual(r.genpageCli.uploads.map((u) => u.name).sort(), ['Detail', 'Overview'], `${what}: the rebuild completes`);
+ assert.strictEqual(r.warnings.length, 1, what);
+ assert.ok(r.warnings[0].startsWith('page "Detail" is already deployed, and this workspace holds no record of what the last build sent for it, so the build cannot tell whether this send changes it; it goes on, as builds did before this check. '), `${what}: ${r.warnings[0]}`);
+ assert.ok(r.warnings[0].includes('detail.tsx:4:5: `borderWidth`') && r.warnings[0].includes(BOTH_WAYS_OUT), what);
+ assert.ok(r.warnings[0].endsWith('once a build has recorded this page, a change to its source is held to the check, and the build stops on anything the check still reports.'), `${what}: what happens from then on`);
+ }
+ } finally { app.cleanup(); }
+ // Not deployed: the page is created, and the record of an apply that once sent the same bytes does not matter — the earlier page was deleted.
+ const fresh = makeTwoPageApp();
+ try {
+ fs.writeFileSync(path.join(fresh.appDir, 'detail.tsx'), GRIFFEL_BAD, 'utf8');
+ const baselineSpec = recordApply(fresh.spec, fresh.appDir);
+ const genpageCli = mockGenpageCli();
+ await assert.rejects(
+ runSdkBuild(fresh.spec, { sdk: mockSdk().sdk, apply: true, env: 'https://x', appDir: fresh.appDir, genpageCli, phases: PHASES, baselineSpec }),
+ (e) => e.code === 'pages-griffel-shorthand' && /page "Detail" writes CSS/.test(e.message) && !/Its source changed/.test(e.message)
+ );
+ assert.deepStrictEqual(genpageCli.uploads, []);
+ } finally { fs.rmSync(fresh.appDir, { recursive: true, force: true }); }
+});
+
+// A style object written elsewhere hides its keys from the check, so the page is held as one the check could not read — as an unreadable call is — and an unchanged page
+// that is already deployed only warns.
+test('deploy: a page whose style object is written elsewhere is held as one the check could not read; sent unchanged it only warns', async () => {
+ const app = deployedApp(GRIFFEL_INDIRECT);
+ try {
+ const baselineSpec = recordApply(app.spec, app.appDir);
+ const ok = app.rebuild({ baselineSpec });
+ await ok.run();
+ assert.strictEqual(ok.warnings.length, 1);
+ assert.match(ok.warnings[0], /^page "Detail" is already deployed, and its source is the one the last build recorded for it, so this build sends it again as it is and goes on\. It has makeStyles calls the Griffel check could not read/);
+ app.edit(`${GRIFFEL_INDIRECT}// edited\n`);
+ const held = app.rebuild({ baselineSpec });
+ await assert.rejects(held.run(), (e) => {
+ assert.strictEqual(e.code, 'pages-griffel-shorthand');
+ assert.match(e.message, /^page "Detail" has makeStyles calls the Griffel check could not read, so it cannot tell whether the page writes CSS that Griffel drops at runtime — detail\.tsx:3:\d+: this makeStyles call is given a style object written elsewhere/);
+ return true;
+ });
+ assert.deepStrictEqual(held.genpageCli.uploads, []);
+ } finally { app.cleanup(); }
+});
+
+// A call the checker cannot read is not a key Griffel drops, and a refusal that says so sends the author looking for CSS that is not there: nothing gets past it but rewriting the code, which
+// the message has to say. A page that is already deployed and sent as it is only warns, as for a key.
+test('deploy: a makeStyles call the checker cannot read is reported as that — not as CSS Griffel drops — with what to change; an unchanged page with one only warns', async () => {
+ const app = deployedApp(GRIFFEL_UNREADABLE);
+ try {
+ const baselineSpec = recordApply(app.spec, app.appDir);
+ const ok = app.rebuild({ baselineSpec });
+ await ok.run();
+ assert.strictEqual(ok.warnings.length, 1);
+ assert.ok(ok.warnings[0].startsWith('page "Detail" is already deployed, and its source is the one the last build recorded for it, so this build sends it again as it is and goes on. It has makeStyles calls the Griffel check could not read, so it cannot tell whether the page writes CSS that Griffel drops at runtime: detail.tsx:3:19: the makeStyles call here cannot be checked for certain'), ok.warnings[0]);
+ assert.doesNotMatch(ok.warnings[0], /Deleting a key/, 'there is no key to delete or rewrite');
+ // Changed, or new: held, and told what to change.
+ app.edit(`${GRIFFEL_UNREADABLE}// edited\n`);
+ const held = app.rebuild({ baselineSpec });
+ await assert.rejects(held.run(), (e) => {
+ assert.strictEqual(e.code, 'pages-griffel-shorthand');
+ assert.ok(e.message.startsWith('page "Detail" has makeStyles calls the Griffel check could not read, so it cannot tell whether the page writes CSS that Griffel drops at runtime — detail.tsx:3:19: the makeStyles call here cannot be checked for certain'), e.message);
+ assert.doesNotMatch(e.message, /writes CSS that Griffel drops at runtime, so the page would deploy without it/, 'it is not said to write any');
+ assert.match(e.message, /put an operand in parentheses, \(\{ … \}\) \/ 2 or \(\/re\/\)\.test\(text\), or end the statement with a ";" — or move the makeStyles call above it\./);
+ assert.match(e.message, /Its source changed since the last build recorded for it, so it is held to the check as a new page is; left as it was, it would only be warned about\. Change the page's source as that says \(`node scripts\/check-griffel-styles\.js --file <page\.tsx>` shows what it cannot read\), then re-run\.$/);
+ return true;
+ });
+ assert.deepStrictEqual(held.genpageCli.uploads, []);
+ } finally { app.cleanup(); }
+ const fresh = makeTwoPageApp();
+ try {
+ fs.writeFileSync(path.join(fresh.appDir, 'detail.tsx'), GRIFFEL_UNREADABLE, 'utf8');
+ await assert.rejects(
+ runSdkBuild(fresh.spec, { sdk: mockSdk().sdk, apply: true, env: 'https://x', appDir: fresh.appDir, genpageCli: mockGenpageCli(), phases: PHASES }),
+ (e) => e.code === 'pages-griffel-shorthand' && /^page "Detail" has makeStyles calls the Griffel check could not read/.test(e.message) && /then re-run\.$/.test(e.message)
+ );
+ } finally { fs.rmSync(fresh.appDir, { recursive: true, force: true }); }
+});
+
+// The build wraps a pac upload that timed out with the caller's own advice: it keeps no base marker, and a navigation page's code file is a staging copy it deletes at the end, so the standalone
+// script's `genpage-base.js check --file <staging copy>` would fail on a missing file. The update is reported as one that may have landed, it is NOT sent again, and the next build
+// converges with one page per name.
+test('deploy: a pac timeout during an UPDATE stops the build with the build\'s advice, sends nothing again, and the next build converges with one page per name', async () => {
+ const { makeGenpageCli } = require('../lib/genpage-cli.js');
+ const { isTransientHalt } = require('../build-model-app.js');
+ const { appDir, spec } = makeTwoPageApp(); // overview links to detail: its upload goes through a staging copy
+ try {
+ const live = [{ pageId: OVERVIEW_ID, name: 'Overview' }, { pageId: DETAIL_ID, name: 'Detail' }];
+ const manifest = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: OVERVIEW_ID }, { key: 'detail', name: 'Detail', pageId: DETAIL_ID }] }), 'utf8').toString('base64');
+ const listing = `Connected as [email protected]\nRetrieving generated pages...\nFound ${live.length} generated page(s):\n\n${'Page ID'.padEnd(37)}${'Name'.padEnd(9)}Published\n${live.map((p) => `${p.pageId} ${p.name.padEnd(8)} -`).join('\n')}\n`;
+ const pacCalls = [];
+ let stall = true;
+ const run = async (args) => {
+ pacCalls.push(args);
+ if (args[2] === 'list') return { status: 0, stdout: listing, stderr: '' };
+ if (stall) return { status: null, timedOut: true, timeoutMs: 600000, command: 'pac model genpage upload', stdout: '', stderr: '' };
+ return { status: 0, stdout: `Page ID: ${args[args.indexOf('--page-id') + 1]}`, stderr: '' };
+ };
+ const genpageCli = makeGenpageCli('https://x', { run, sleep: async () => {} });
+ const make = () => mockSdk({ pageManifest: manifest, liveSitemapXml: pageSitemap([OVERVIEW_ID, DETAIL_ID]), pageRows: live.map((p) => ({ uxagentprojectid: p.pageId, name: p.name })) }).sdk;
+ await assert.rejects(runSdkBuild(spec, { sdk: make(), apply: true, env: 'https://x', appDir, genpageCli, phases: PHASES }), (e) => {
+ assert.strictEqual(e.phase, 'pages');
+ assert.match(e.message, /timed out after 600 s and was stopped — the UPDATE of page 11111111-0000-4000-8000-000000000001 MAY HAVE LANDED/);
+ assert.match(e.message, /First see what is deployed: pac model genpage download --environment https:\/\/x --app-id [^ ]+ --page-id 11111111-0000-4000-8000-000000000001 --output-directory <folder>/);
+ assert.match(e.message, /Then run the build again: it sends this page once more, to the same page id/);
+ assert.doesNotMatch(e.message, /genpage-base\.js|\.pageref-deploy|re-run the upload/, 'no advice the build cannot follow: no check on a staging copy it deletes');
+ assert.strictEqual(isTransientHalt(e), false, 'the build does not retry it by itself');
+ return true;
+ });
+ const uploads = pacCalls.filter((a) => a[2] === 'upload');
+ assert.strictEqual(uploads.length, 1, 'one send: the update that stalled is not sent again, and the next page was never started');
+ assert.ok(!fs.existsSync(path.join(appDir, '.maker-workspace', '.pageref-deploy')) || fs.readdirSync(path.join(appDir, '.maker-workspace', '.pageref-deploy')).length === 0, 'the staging copy is gone, as the message says it would be');
+ // The next normal build: the same pages, the same ids — one page per name, nothing created.
+ stall = false;
+ pacCalls.length = 0;
+ await runSdkBuild(spec, { sdk: make(), apply: true, env: 'https://x', appDir, genpageCli, phases: PHASES });
+ const sent = pacCalls.filter((a) => a[2] === 'upload');
+ assert.strictEqual(sent.length, 2, 'both pages are sent');
+ assert.deepStrictEqual(sent.map((a) => a[a.indexOf('--page-id') + 1]).sort(), [OVERVIEW_ID, DETAIL_ID].sort(), 'each to the id it already has: updates, and no create');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// The same for an UPDATE that FAILS rather than stalls: pac can fail in the publish after it wrote the page and recorded its prompt, so the build sends it once — not again in the
+// upload's own loop, and not by its re-run of a halt it takes for transient (the pac words here, "try again later", would read as one without the marker) — and gives its own advice.
+test('deploy: a pac failure during an UPDATE stops the build with the build\'s advice, sends nothing again, and the next build converges with one page per name', async () => {
+ const { makeGenpageCli } = require('../lib/genpage-cli.js');
+ const { isTransientHalt } = require('../build-model-app.js');
+ const { appDir, spec } = makeTwoPageApp();
+ try {
+ const live = [{ pageId: OVERVIEW_ID, name: 'Overview' }, { pageId: DETAIL_ID, name: 'Detail' }];
+ const manifest = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: OVERVIEW_ID }, { key: 'detail', name: 'Detail', pageId: DETAIL_ID }] }), 'utf8').toString('base64');
+ const listing = `Connected as [email protected]\nRetrieving generated pages...\nFound ${live.length} generated page(s):\n\n${'Page ID'.padEnd(37)}${'Name'.padEnd(9)}Published\n${live.map((p) => `${p.pageId} ${p.name.padEnd(8)} -`).join('\n')}\n`;
+ const pacCalls = [];
+ let fail = true;
+ const run = async (args) => {
+ pacCalls.push(args);
+ if (args[2] === 'list') return { status: 0, stdout: listing, stderr: '' };
+ const id = args[args.indexOf('--page-id') + 1];
+ if (fail) return { status: 1, stdout: `Page ID: ${id}\r\nPublishing...\r\n`, stderr: 'Error: The service is busy, try again later.' };
+ return { status: 0, stdout: `Page ID: ${id}`, stderr: '' };
+ };
+ const genpageCli = makeGenpageCli('https://x', { run, sleep: async () => {} });
+ const make = () => mockSdk({ pageManifest: manifest, liveSitemapXml: pageSitemap([OVERVIEW_ID, DETAIL_ID]), pageRows: live.map((p) => ({ uxagentprojectid: p.pageId, name: p.name })) }).sdk;
+ await assert.rejects(runSdkBuild(spec, { sdk: make(), apply: true, env: 'https://x', appDir, genpageCli, phases: PHASES }), (e) => {
+ assert.strictEqual(e.phase, 'pages');
+ assert.match(e.message, /failed \(Error: The service is busy, try again later\.\) — the UPDATE of page 11111111-0000-4000-8000-000000000001 MAY HAVE LANDED: pac had printed the Page ID/);
+ assert.match(e.message, /First see what is deployed: pac model genpage download --environment https:\/\/x --app-id [^ ]+ --page-id 11111111-0000-4000-8000-000000000001 --output-directory <folder>/);
+ assert.match(e.message, /Then run the build again: it sends this page once more, to the same page id, so nothing new is created — but if the failed send did land/);
+ assert.doesNotMatch(e.message, /genpage-base\.js|\.pageref-deploy|re-run the upload/, 'no advice the build cannot follow: no check on a staging copy it deletes');
+ assert.strictEqual(isTransientHalt(e), false, 'the build does not retry it by itself');
+ return true;
+ });
+ const uploads = pacCalls.filter((a) => a[2] === 'upload');
+ assert.strictEqual(uploads.length, 1, 'one send: the update that failed is not sent again, and the next page was never started');
+ // The next normal build: the same pages, the same ids — one page per name, nothing created.
+ fail = false;
+ pacCalls.length = 0;
+ await runSdkBuild(spec, { sdk: make(), apply: true, env: 'https://x', appDir, genpageCli, phases: PHASES });
+ const sent = pacCalls.filter((a) => a[2] === 'upload');
+ assert.strictEqual(sent.length, 2, 'both pages are sent');
+ assert.deepStrictEqual(sent.map((a) => a[a.indexOf('--page-id') + 1]).sort(), [OVERVIEW_ID, DETAIL_ID].sort(), 'each to the id it already has: updates, and no create');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+test('deploy: a page with the same names only in a comment, a string or an inline style is not refused, and a spec of clean pages builds as it did', async () => {
+ const { appDir, spec } = makeTwoPageApp();
+ try {
+ fs.writeFileSync(path.join(appDir, 'detail.tsx'), GRIFFEL_CLEAN, 'utf8');
+ const genpageCli = mockGenpageCli();
+ await runSdkBuild(spec, { sdk: mockSdk().sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: PHASES });
+ assert.deepStrictEqual(genpageCli.uploads.map((u) => u.name).sort(), ['Detail', 'Overview']);
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+test('changed-only: the Griffel check is held against the pages the run uploads, not against a page it leaves alone — and a selected page is judged like any other', async () => {
+ const appDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sel-griffel-'));
+ try {
+ fs.writeFileSync(path.join(appDir, 'overview.tsx'), 'export default function O(){ return null; }', 'utf8');
+ fs.writeFileSync(path.join(appDir, 'detail.tsx'), GRIFFEL_CLEAN, 'utf8');
+ const spec = {
+ schemaVersion: 2,
+ solution: { uniqueName: 'SelGriffel', displayName: 'S', publisherPrefix: 'contoso' },
+ app: { name: 'Sel Griffel App' },
+ entities: [{ schemaName: 'contoso_item', displayName: 'Item', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] }],
+ pages: [
+ { key: 'overview', name: 'Overview', source: { kind: 'tsx', codeFile: 'overview.tsx' } },
+ { key: 'detail', name: 'Detail', source: { kind: 'tsx', codeFile: 'detail.tsx' } },
+ ],
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'G', subAreas: [{ page: 'overview', title: 'Overview' }, { page: 'detail', title: 'Detail' }] }] }] },
+ };
+ // The last apply sent `detail` clean; since then its source was edited, and now drops keys. (The record is made before the edit.)
+ const cleanBaseline = recordApply(spec, appDir);
+ fs.writeFileSync(path.join(appDir, 'detail.tsx'), GRIFFEL_BAD, 'utf8');
+ const live = [{ pageId: OVERVIEW_ID, name: 'Overview' }, { pageId: DETAIL_ID, name: 'Detail' }];
+ const manifest = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: OVERVIEW_ID }, { key: 'detail', name: 'Detail', pageId: DETAIL_ID }] }), 'utf8').toString('base64');
+ const make = () => mockSdk({ pageManifest: manifest, liveSitemapXml: pageSitemap([OVERVIEW_ID, DETAIL_ID]), pageRows: live.map((p) => ({ uxagentprojectid: p.pageId, name: p.name })) }).sdk;
+ const changedOnly = (selectedKeys) => ({ fastApply: true, resolvedAppId: APP_ID, skipSitemapFinalize: true, selectedKeys });
+ // The selected page is clean: the run goes ahead, and the page it did not select — which would be refused if it were uploaded — is left alone.
+ const genpageCli = mockGenpageCli(live);
+ const r = await runSdkBuild(spec, { sdk: make(), apply: true, env: 'https://x', appDir, genpageCli, phases: PAGES_ONLY, changedOnly: changedOnly(['overview']), baselineSpec: cleanBaseline });
+ assert.ok(r.ok);
+ assert.deepStrictEqual(genpageCli.uploads.map((u) => u.name), ['Overview']);
+ // Selecting the page that changed to drop a key is refused, before anything is uploaded.
+ const refused = mockGenpageCli(live);
+ await assert.rejects(
+ runSdkBuild(spec, { sdk: make(), apply: true, env: 'https://x', appDir, genpageCli: refused, phases: PAGES_ONLY, changedOnly: changedOnly(['overview', 'detail']), baselineSpec: cleanBaseline }),
+ (e) => e && e.code === 'pages-griffel-shorthand' && /page "Detail"/.test(e.message)
+ );
+ assert.deepStrictEqual(refused.uploads, []);
+ // No selection at all is a full build: every page is uploaded, so every page is checked.
+ const full = mockGenpageCli(live);
+ await assert.rejects(
+ runSdkBuild(spec, { sdk: make(), apply: true, env: 'https://x', appDir, genpageCli: full, phases: PAGES_ONLY, changedOnly: { resolvedAppId: APP_ID, skipSitemapFinalize: true }, baselineSpec: cleanBaseline }),
+ (e) => e && e.code === 'pages-griffel-shorthand'
+ );
+ // A selected page whose source is the one recorded — the record was made with the keys in it — is sent as it is and warned about: the decision is the build's, whoever selected the page.
+ const badBaseline = recordApply(spec, appDir);
+ const sameAsRecorded = mockGenpageCli(live);
+ const warnings = [];
+ await runSdkBuild(spec, { sdk: make(), apply: true, env: 'https://x', appDir, genpageCli: sameAsRecorded, phases: PAGES_ONLY, changedOnly: changedOnly(['detail']), baselineSpec: badBaseline, warn: (m) => warnings.push(m) });
+ assert.deepStrictEqual(sameAsRecorded.uploads.map((u) => u.name), ['Detail']);
+ assert.strictEqual(warnings.length, 1);
+ assert.match(warnings[0], /^page "Detail" is already deployed, and its source is the one the last build recorded for it/);
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// ── What the build records as the source it sent ────────────────────────────────────────────────────────────────────────────────────────────
+// The baseline is written when the build ENDS, and it is what the next build's Griffel check judges a page against: "the source the last apply sent". The pages phase measures the source it
+// read and checked for each page it sends (`created.pageSourceShas`), and that is what is recorded — not the file as it is when the baseline is written, which a maker can have saved over
+// while the build ran. Such a page then reads as changed next time, and is held to the check, instead of as "unchanged", with a key nothing ever checked let through on a warning.
+test('deploy: the pages phase records the hash of the source it read for each page it sends — a navigation page by its own source, not by the resolved copy it uploads', async () => {
+ const { appDir, spec } = makeTwoPageApp(); // overview links to detail
+ try {
+ const genpageCli = mockGenpageCli();
+ const r = await runSdkBuild(spec, { sdk: mockSdk().sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: PHASES });
+ const source = (file) => sha256(fs.readFileSync(path.join(appDir, file)));
+ assert.deepStrictEqual(r.created.pageSourceShas, { overview: source('overview.tsx'), detail: source('detail.tsx') });
+ assert.notStrictEqual(r.created.pageDeployedShas.overview, r.created.pageSourceShas.overview, 'the copy that is uploaded has the target\'s id where the source has PAGEREF_: it is another hash');
+ // Only a page that is sent is recorded: a changed-only run that selects one page records that page.
+ const selected = await runSdkBuild(spec, { sdk: mockSdk({ pageManifest: Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: OVERVIEW_ID }, { key: 'detail', name: 'Detail', pageId: DETAIL_ID }] }), 'utf8').toString('base64'), liveSitemapXml: pageSitemap([OVERVIEW_ID, DETAIL_ID]), pageRows: [{ uxagentprojectid: OVERVIEW_ID, name: 'Overview' }, { uxagentprojectid: DETAIL_ID, name: 'Detail' }] }).sdk,
+ apply: true, env: 'https://x', appDir, genpageCli: mockGenpageCli([{ pageId: OVERVIEW_ID, name: 'Overview' }, { pageId: DETAIL_ID, name: 'Detail' }]), phases: PAGES_ONLY,
+ changedOnly: { fastApply: true, resolvedAppId: APP_ID, skipSitemapFinalize: true, selectedKeys: ['detail'] } });
+ assert.deepStrictEqual(selected.created.pageSourceShas, { detail: source('detail.tsx') });
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+test('deploy: a page saved while a build runs is not recorded as applied — the next build holds it to the check, instead of finding it "unchanged" and letting its new key through on a warning', async () => {
+ const { persistAppliedBaseline } = require('../build-model-app.js');
+ const app = deployedApp(GRIFFEL_CLEAN);
+ try {
+ const workspace = path.join(app.appDir, '.maker-workspace');
+ const identity = { environment: BASELINE_ENV, appUniqueName: appUniqueName(app.spec) };
+ const earlier = recordApply(app.spec, app.appDir); // an earlier apply sent the clean page
+ // Build 1: the pre-write scan has read both pages when, during the upload, the maker saves a `borderColor` into detail.tsx.
+ const first = app.rebuild({ baselineSpec: earlier });
+ const upload = first.genpageCli.upload;
+ first.genpageCli.upload = async (o) => { const up = await upload(o); if (o.name === 'Detail') app.edit(GRIFFEL_BAD); return up; };
+ const result = await first.run();
+ assert.strictEqual(first.genpageCli.uploads.find((u) => u.name === 'Detail').content, GRIFFEL_CLEAN, 'build 1 sent the clean page, and succeeded');
+ assert.ok(persistAppliedBaseline(result, { spec: app.spec, opts: { apply: true, baselineSpec: earlier }, workspaceDir: workspace, appDirAbs: app.appDir, baselineIdentity: identity }), 'its baseline is written, as main() does');
+ // Build 2 meets the saved page. It is not what build 1 sent, so it is changed, and its key is refused.
+ const recorded = readBaseline(workspace, identity);
+ const second = app.rebuild({ baselineSpec: recorded });
+ await assert.rejects(second.run(), (e) => e.code === 'pages-griffel-shorthand' && /^page "Detail" writes CSS/.test(e.message) && /Its source changed since the last build recorded for it/.test(e.message));
+ assert.deepStrictEqual(second.genpageCli.uploads, [], 'nothing was written');
+ assert.deepStrictEqual(second.warnings, []);
+ } finally { app.cleanup(); }
+});
+
+test('deploy: a page that no edit touched is recorded as sent, so the build after it still only warns about the key it already has', async () => {
+ const { persistAppliedBaseline } = require('../build-model-app.js');
+ const app = deployedApp(GRIFFEL_BAD);
+ try {
+ const workspace = path.join(app.appDir, '.maker-workspace');
+ const identity = { environment: BASELINE_ENV, appUniqueName: appUniqueName(app.spec) };
+ const earlier = recordApply(app.spec, app.appDir);
+ const first = app.rebuild({ baselineSpec: earlier });
+ const result = await first.run();
+ assert.ok(persistAppliedBaseline(result, { spec: app.spec, opts: { apply: true, baselineSpec: earlier }, workspaceDir: workspace, appDirAbs: app.appDir, baselineIdentity: identity }));
+ const second = app.rebuild({ baselineSpec: readBaseline(workspace, identity) });
+ await second.run();
+ assert.strictEqual(second.genpageCli.uploads.length, 2, 'both pages are sent again');
+ assert.strictEqual(second.warnings.length, 1);
+ assert.match(second.warnings[0], /^page "Detail" is already deployed, and its source is the one the last build recorded for it/);
+ } finally { app.cleanup(); }
+});
+
+test('changed-only: a page the run did not select keeps the record it had, whatever its file says by the time the baseline is written', async () => {
+ const { persistAppliedBaseline } = require('../build-model-app.js');
+ const app = deployedApp(GRIFFEL_CLEAN);
+ try {
+ const workspace = path.join(app.appDir, '.maker-workspace');
+ const identity = { environment: BASELINE_ENV, appUniqueName: appUniqueName(app.spec) };
+ const earlier = recordApply(app.spec, app.appDir); // detail was sent clean
+ // A fast apply that selects only overview; detail is saved with a key while it runs, and is never sent.
+ const live = [{ pageId: OVERVIEW_ID, name: 'Overview' }, { pageId: DETAIL_ID, name: 'Detail' }];
+ const manifest = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: OVERVIEW_ID }, { key: 'detail', name: 'Detail', pageId: DETAIL_ID }] }), 'utf8').toString('base64');
+ const sdk = mockSdk({ pageManifest: manifest, liveSitemapXml: pageSitemap([OVERVIEW_ID, DETAIL_ID]), pageRows: live.map((p) => ({ uxagentprojectid: p.pageId, name: p.name })) }).sdk;
+ const cli = mockGenpageCli(live);
+ const upload = cli.upload;
+ cli.upload = async (o) => { const up = await upload(o); app.edit(GRIFFEL_BAD); return up; };
+ const result = await runSdkBuild(app.spec, { sdk, apply: true, env: 'https://x', appDir: app.appDir, genpageCli: cli, phases: PAGES_ONLY, baselineSpec: earlier,
+ changedOnly: { fastApply: true, resolvedAppId: APP_ID, skipSitemapFinalize: true, selectedKeys: ['overview'] } });
+ assert.deepStrictEqual(cli.uploads.map((u) => u.name), ['Overview']);
+ assert.ok(persistAppliedBaseline({ ...result, changedOnly: { decision: 'fast' } }, { spec: app.spec, opts: { apply: true, phases: PAGES_ONLY, baselineSpec: earlier }, workspaceDir: workspace, appDirAbs: app.appDir, baselineIdentity: identity }));
+ const recorded = readBaseline(workspace, identity);
+ assert.strictEqual(recorded.pages.find((p) => p.key === 'detail').__contentSha, earlier.pages.find((p) => p.key === 'detail').__contentSha, 'detail: the record it had, not the hash of a file nothing sent');
+ // So the next build — a full one — finds detail changed, and holds it.
+ await assert.rejects(app.rebuild({ baselineSpec: recorded }).run(), (e) => e.code === 'pages-griffel-shorthand' && /^page "Detail" writes CSS/.test(e.message));
+ } finally { app.cleanup(); }
+});
+
+// A halting build says only why it halted: the pages it would have let through are warned about once the whole scan has passed. The warning for a page that comes first must not be said
+// when a later page stops the build — a message about a page the build then never sent would read as if it had.
+test('deploy: a build that halts on a later page says nothing about an earlier page it would have let through', async () => {
+ const app = deployedApp(GRIFFEL_CLEAN);
+ try {
+ const earlier = recordApply(app.spec, app.appDir);
+ // overview carries a key with no record of what was last sent for it (a warning); detail changed and carries one (a halt) — detail comes second in the scan.
+ fs.writeFileSync(path.join(app.appDir, 'overview.tsx'), `${GRIFFEL_IMPORT}const s = makeStyles({ root: { borderColor: 'red' } });\nexport default function Overview(){ return null; }\n`, 'utf8');
+ const baselineSpec = { ...earlier, pages: earlier.pages.map((p) => (p.key === 'overview' ? { ...p, __contentSha: null } : p)) };
+ app.edit(GRIFFEL_BAD);
+ const held = app.rebuild({ baselineSpec });
+ await assert.rejects(held.run(), (e) => e.code === 'pages-griffel-shorthand' && /^page "Detail" writes CSS/.test(e.message));
+ assert.deepStrictEqual(held.warnings, [], 'the page that would have been warned about is not mentioned');
+ assert.deepStrictEqual(held.genpageCli.uploads, []);
+ // Control: with detail clean, the same overview is warned about, once, and the build goes on — so the silence above is about the halt.
+ app.edit(GRIFFEL_CLEAN);
+ const goes = app.rebuild({ baselineSpec });
+ await goes.run();
+ assert.strictEqual(goes.warnings.length, 1);
+ assert.match(goes.warnings[0], /^page "Overview" is already deployed, and this workspace holds no record/);
+ } finally { app.cleanup(); }
+});
+
test('deploy: a page with a present-but-blank prompt HALTS before any upload', async () => {
const { appDir, spec } = makeTwoPageApp();
try {
@@ -1011,3 +1573,253 @@ test('lexical navigation overrides halt before any upload', async () => {
} finally { fs.rmSync(appDir, { recursive: true, force: true }); }
}
});
+
+// ── An upload whose outcome is not known is never sent again — not by the build's own retry either ─────────────────────────────────────────────
+// buildModelApp re-runs the whole build when a halt reads as transient (isTransientHalt), and it decides that from the halt's TEXT. The text of an uncertain create quotes the page's name — user
+// text, so "SQL Timeouts" or "Concurrent Deletes" read as a SQL timeout or a concurrent delete — and pac's own words ("… try again later"). A re-run is a second create: the page the first one made,
+// if it landed, is left beside the new one, outside the app's navigation, and the run reports success. These tests drive the REAL retry loop, the real wrapper and a pac that ends the create each
+// way, and count the creates that reach pac.
+function onePageApp(pageName) {
+ const appDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pages-uncertain-'));
+ fs.writeFileSync(path.join(appDir, 'p.tsx'), 'export default function P(){ return null; }', 'utf8');
+ const spec = {
+ schemaVersion: 2,
+ solution: { uniqueName: 'UncertainSol', displayName: 'Uncertain', publisherPrefix: 'contoso' },
+ app: { name: 'Uncertain App' },
+ entities: [{ schemaName: 'contoso_item', displayName: 'Item', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] }],
+ pages: [{ key: 'p', name: pageName, source: { kind: 'tsx', codeFile: 'p.tsx' } }],
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Pages', subAreas: [{ page: 'p', title: pageName }] }] }] },
+ };
+ return { appDir, spec };
+}
+const PAC_LISTING_EMPTY = 'Connected as [email protected]\nRetrieving generated pages...\nFound 0 generated page(s):\n';
+function pacListing(rows) {
+ const width = Math.max(4, ...rows.map((r) => r.name.length));
+ return `Connected as [email protected]\nRetrieving generated pages...\nFound ${rows.length} generated page(s):\n\n${'Page ID'.padEnd(37)}${'Name'.padEnd(width + 1)}Published\n${rows.map((r) => `${r.pageId} ${r.name.padEnd(width)} -`).join('\n')}\n`;
+}
+const PAC_STALLED = { status: null, timedOut: true, timeoutMs: 600000, command: 'pac model genpage upload', stdout: '', stderr: '' };
+// A pac whose create ends as `create` says, and whose listings, once a create was sent, answer as `afterListing` says. Every call is recorded.
+function sendingPac({ create, afterListing = () => ({ status: 0, stdout: PAC_LISTING_EMPTY, stderr: '' }) }) {
+ const calls = [];
+ let sent = 0;
+ let listedSinceSend = 0;
+ const run = async (args) => {
+ calls.push(args);
+ if (args[2] === 'list') {
+ if (sent === 0) return { status: 0, stdout: PAC_LISTING_EMPTY, stderr: '' };
+ listedSinceSend += 1;
+ return afterListing(listedSinceSend);
+ }
+ if (args[2] === 'upload') { sent += 1; return create(sent, args); }
+ return { status: 1, stdout: '', stderr: 'unexpected pac call' };
+ };
+ return { run, calls, creates: () => calls.filter((a) => a[2] === 'upload' && !a.includes('--page-id')).length };
+}
+const TRY_AGAIN_LATER = 'Error: The service is unavailable. Please try again later.';
+const UNCERTAIN_PAGE_ID = '3a1f9c52-0000-4000-8000-00000000a0a0';
+// `says` is what the halt says; each scenario ends the create a different way.
+const UNCERTAIN_CREATES = [
+ { what: 'a create that stalls with nothing visible yet, for a page named "SQL Timeouts"', name: 'SQL Timeouts', create: () => PAC_STALLED, says: /an UNCERTAIN create: no new page is visible/ },
+ { what: 'a create that stalls with nothing visible yet, for a page named "Concurrent Deletes"', name: 'Concurrent Deletes', create: () => PAC_STALLED, says: /an UNCERTAIN create: no new page is visible/ },
+ { what: 'a create that stalls and whose environment listing then fails with "try again later"', name: 'Overview', create: () => PAC_STALLED, afterListing: () => ({ status: 1, stdout: '', stderr: TRY_AGAIN_LATER }), says: /env enumeration failed — refusing to retry/ },
+ { what: 'a create that fails and whose environment listing then fails with "try again later"', name: 'Overview', create: () => ({ status: 1, stdout: '', stderr: 'Error: the upload failed' }), afterListing: () => ({ status: 1, stdout: '', stderr: TRY_AGAIN_LATER }), says: /env enumeration failed — refusing to retry/ },
+ { what: 'a create that stalls and whose page then shows up in the environment, for a page named "SQL Timeout Report"', name: 'SQL Timeout Report', create: () => PAC_STALLED, afterListing: () => ({ status: 0, stdout: pacListing([{ pageId: UNCERTAIN_PAGE_ID, name: 'SQL Timeout Report' }]), stderr: '' }), says: /ambiguous ownership/ },
+ { what: 'a create that fails and leaves a page in the environment, for a page named "SQL Timeout Report"', name: 'SQL Timeout Report', create: () => ({ status: 1, stdout: '', stderr: 'Error: could not publish' }), afterListing: () => ({ status: 0, stdout: pacListing([{ pageId: UNCERTAIN_PAGE_ID, name: 'SQL Timeout Report' }]), stderr: '' }), says: /ambiguous ownership/ },
+ { what: 'a create that stalls after pac printed the Page ID, for a page named "SQL Timeouts"', name: 'SQL Timeouts', create: () => ({ ...PAC_STALLED, stdout: `Page ID: ${UNCERTAIN_PAGE_ID}\n` }), says: /after it had CREATED the page as/ },
+ { what: 'a create that fails after pac printed the Page ID, with "try again later"', name: 'Overview', create: () => ({ status: 1, stdout: `Page ID: ${UNCERTAIN_PAGE_ID}\n`, stderr: TRY_AGAIN_LATER }), says: /failed after it had CREATED the page as/ },
+];
+async function runUncertainBuild(scenario) {
+ const { buildModelApp } = require('../build-model-app.js');
+ const { makeGenpageCli } = require('../lib/genpage-cli.js');
+ const { appDir, spec } = onePageApp(scenario.name);
+ try {
+ const pac = sendingPac(scenario);
+ const genpageCli = makeGenpageCli('https://contoso.crm.dynamics.com', { run: pac.run, sleep: async () => {}, request: async () => ({ status: 200, data: { name: scenario.name, createdon: '2026-01-01T00:00:00Z' } }) });
+ const { sdk } = mockSdk();
+ const lines = [];
+ let halt = null;
+ try {
+ await buildModelApp(spec, { apply: true, env: 'https://contoso.crm.dynamics.com', appDir, retryDelayMs: 0 }, {
+ sdk, provisionSdk: sdk, genpageCli, sleep: async () => {}, log: (m) => lines.push(m),
+ discoverOpDiffState: async () => ({ collision: { appExists: false, solutionExists: false }, forms: [], sitemap: null }),
+ });
+ } catch (e) { halt = e; }
+ return { halt, lines, pac, spec };
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+}
+for (const scenario of UNCERTAIN_CREATES) {
+ test(`deploy: ${scenario.what} halts the build — its create reaches pac once, and the build's own retry does not send it again`, async () => {
+ const { isTransientHalt } = require('../build-model-app.js');
+ const { halt, lines, pac, spec } = await runUncertainBuild(scenario);
+ assert.ok(halt, 'the build halts');
+ assert.strictEqual(halt.phase, 'pages');
+ assert.match(halt.message, scenario.says);
+ assert.strictEqual(pac.creates(), 1, 'one create: a second would make a duplicate page');
+ assert.deepStrictEqual(lines.filter((l) => /transient error|retrying/.test(l)), [], 'and the build never says it is retrying');
+ assert.strictEqual(isTransientHalt(halt, { spec }), false, 'the halt reads as final');
+ assert.strictEqual(halt.cause && halt.cause.transient, false, 'because the error it wraps says so, whatever its text quotes');
+ });
+}
+
+// The marker is not a blanket: what the build rides out is still ridden out. A listing that fails BEFORE any create was sent — the snapshot the create is checked against — leaves nothing
+// to duplicate, so a transient failure there is retried, and the create is sent once, when it can be.
+test('deploy: a transient failure BEFORE the create was sent is still retried by the build, and the create is sent once', async () => {
+ const scenario = { name: 'Overview', create: () => ({ status: 0, stdout: `Page ID: ${UNCERTAIN_PAGE_ID}\n`, stderr: '' }) };
+ const { buildModelApp } = require('../build-model-app.js');
+ const { makeGenpageCli } = require('../lib/genpage-cli.js');
+ const { appDir, spec } = onePageApp(scenario.name);
+ try {
+ const pac = sendingPac(scenario);
+ let snapshots = 0;
+ const run = async (args) => {
+ if (args[2] === 'list' && pac.creates() === 0 && (snapshots += 1) <= 3) return { status: 1, stdout: '', stderr: TRY_AGAIN_LATER };
+ return pac.run(args);
+ };
+ const genpageCli = makeGenpageCli('https://contoso.crm.dynamics.com', { run, sleep: async () => {} });
+ const { sdk } = mockSdk();
+ const lines = [];
+ const result = await buildModelApp(spec, { apply: true, env: 'https://contoso.crm.dynamics.com', appDir, retryDelayMs: 0 }, {
+ sdk, provisionSdk: sdk, genpageCli, sleep: async () => {}, log: (m) => lines.push(m),
+ discoverOpDiffState: async () => ({ collision: { appExists: false, solutionExists: false }, forms: [], sitemap: null }),
+ });
+ assert.strictEqual(result.ok, true);
+ assert.ok(lines.some((l) => /transient error in pages — retrying/.test(l)), 'the build retried');
+ assert.strictEqual(pac.creates(), 1, 'and the create went out once');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// The one other place a create is left unrecorded: pac made the page, and the receipt that lets a later build find it could not be written. The halt quotes the page's name too.
+test('deploy: a page that was created but whose local receipt cannot be saved halts, and the build does not retry it into a second page — whatever the page is called', async () => {
+ const { buildModelApp, isTransientHalt } = require('../build-model-app.js');
+ const { recordPageCreation } = require('../lib/page-ownership-records.js');
+ const { appDir, spec } = onePageApp('SQL Timeouts');
+ try {
+ const workspaceDir = path.join(appDir, '.maker-workspace');
+ // A receipt for this very page id under another name: saving this one is refused, as a receipt that disagrees about the page is.
+ recordPageCreation(workspaceDir, appUniqueName(spec), 'p', OVERVIEW_ID, 'Another name', 'https://contoso.crm.dynamics.com');
+ const genpageCli = mockGenpageCli();
+ const { sdk } = mockSdk();
+ const lines = [];
+ let halt = null;
+ try {
+ await buildModelApp(spec, { apply: true, env: 'https://contoso.crm.dynamics.com', appDir, workspaceDir, retryDelayMs: 0 }, {
+ sdk, provisionSdk: sdk, genpageCli, sleep: async () => {}, log: (m) => lines.push(m),
+ discoverOpDiffState: async () => ({ collision: { appExists: false, solutionExists: false }, forms: [], sitemap: null }),
+ });
+ } catch (e) { halt = e; }
+ assert.ok(halt, 'the build halts');
+ assert.match(halt.message, /page "SQL Timeouts" was created as 11111111-0000-4000-8000-000000000001, but its local receipt could not be saved/);
+ assert.strictEqual(genpageCli.uploads.length, 1, 'one create');
+ assert.deepStrictEqual(lines.filter((l) => /transient error|retrying/.test(l)), [], 'and no retry');
+ assert.strictEqual(isTransientHalt(halt, { spec }), false);
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// The pages scan reads each page ONCE, and checks and hashes those bytes; every upload then sends a staging copy of them, never the canonical file.
+// A page saved again while the build runs — after the scan, before its own upload — must not ship unchecked, nor be recorded as what was sent.
+// Overview links to Detail and Notes, so both are minted first (the create-absent-first step); Help links nowhere and goes up last. While the
+// first page goes up, Notes and Help are saved with a key Griffel drops.
+test('deploy: every page is uploaded from a staging copy of the bytes the scan read — a save to a page during the build does not ship', async () => {
+ const appDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pages-deploy-'));
+ try {
+ const original = {
+ notes: 'export default function Notes(){ return null; }',
+ help: 'export default function Help(){ return null; }',
+ };
+ fs.writeFileSync(path.join(appDir, 'overview.tsx'), `export default function Overview(){ ${NAV('detail')} ${NAV('notes')} return null; }`, 'utf8');
+ fs.writeFileSync(path.join(appDir, 'detail.tsx'), 'export default function Detail(){ return null; }', 'utf8');
+ fs.writeFileSync(path.join(appDir, 'notes.tsx'), original.notes, 'utf8');
+ fs.writeFileSync(path.join(appDir, 'help.tsx'), original.help, 'utf8');
+ const spec = {
+ schemaVersion: 2,
+ solution: { uniqueName: 'PgDeploy', displayName: 'Pg', publisherPrefix: 'contoso' },
+ app: { name: 'Deploy App' },
+ entities: [{ schemaName: 'contoso_item', displayName: 'Item', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] }],
+ pages: [
+ { key: 'overview', name: 'Overview', navigatesTo: [{ targetKey: 'detail' }, { targetKey: 'notes' }], source: { kind: 'tsx', codeFile: 'overview.tsx' } },
+ { key: 'detail', name: 'Detail', source: { kind: 'tsx', codeFile: 'detail.tsx' } },
+ { key: 'notes', name: 'Notes', source: { kind: 'tsx', codeFile: 'notes.tsx' } },
+ { key: 'help', name: 'Help', source: { kind: 'tsx', codeFile: 'help.tsx' } },
+ ],
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Pages', subAreas: ['overview', 'detail', 'notes', 'help'].map((page) => ({ page, title: page })) }] }] },
+ };
+ const saved = "import { makeStyles } from '@fluentui/react-components';\nconst useStyles = makeStyles({ root: { borderWidth: '1px' } });\nexport default function Saved(){ return null; }";
+ const ids = { Overview: OVERVIEW_ID, Detail: DETAIL_ID, Notes: '33333333-0000-4000-8000-000000000003', Help: '44444444-0000-4000-8000-000000000004' };
+ const uploads = [];
+ const genpageCli = {
+ enumerateEnv: async () => ({ ok: true, ids: [], pages: [] }),
+ upload: async (o) => {
+ uploads.push({ name: o.name, codeFile: o.codeFile, content: fs.readFileSync(o.codeFile, 'utf8') });
+ if (uploads.length === 1) {
+ fs.writeFileSync(path.join(appDir, 'notes.tsx'), saved, 'utf8');
+ fs.writeFileSync(path.join(appDir, 'help.tsx'), saved, 'utf8');
+ }
+ return { pageId: o.pageId || ids[o.name] };
+ },
+ };
+ const { sdk } = mockSdk();
+ const r = await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: PHASES });
+ assert.deepStrictEqual(uploads.map((u) => u.name), ['Detail', 'Notes', 'Overview', 'Help'], 'the link targets are minted first, then the rest go up, each once');
+ const by = Object.fromEntries(uploads.map((u) => [u.name, u]));
+ assert.strictEqual(by.Notes.content, original.notes, 'a minted target sends what the scan read, not the later save');
+ assert.strictEqual(by.Help.content, original.help, 'a page that links nowhere sends what the scan read, not the later save');
+ const stagingRoot = path.join(appDir, '.maker-workspace', '.pageref-deploy');
+ for (const u of uploads) assert.ok(u.codeFile.startsWith(stagingRoot), `${u.name}: a staging copy, not the canonical file (${u.codeFile})`);
+ assert.ok(!fs.existsSync(stagingRoot) || fs.readdirSync(stagingRoot).length === 0, 'and the copies are removed when the build ends');
+ // What the build records as sent is what it sent: the source hash the next build compares with, and (for a page sent in the upload step) the deployed hash.
+ for (const key of ['notes', 'help']) assert.strictEqual(r.created.pageSourceShas[key], sha256(original[key]), `${key}: source hash`);
+ assert.strictEqual(r.created.pageDeployedShas.help, sha256(original.help), 'help: deployed hash');
+ assert.strictEqual(fs.readFileSync(path.join(appDir, 'help.tsx'), 'utf8'), saved, 'the canonical file keeps the save, for the next build to check');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// Windows reserves the device names, with or without an extension (`NUL.txt` is NUL —
+// https://learn.microsoft.com/windows/win32/fileio/naming-a-file), and a page key is a slug that can be one. The
+// staging copy pac uploads must never be named like one: where a release reads `con.tsx` as the console, the build
+// would hand pac a device instead of the page. Checked on the name rather than by writing one, because Windows 11
+// writes `con.tsx` as an ordinary file, so a write would pass here and fail elsewhere.
+test('deploy: a page keyed like a Windows device name is staged under a name that is not one', async () => {
+ const DEVICE = /^(?:con|prn|aux|nul|com[0-9\u00b9\u00b2\u00b3]|lpt[0-9\u00b9\u00b2\u00b3])(?:\..*)?$/i;
+ const appDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pages-deploy-'));
+ try {
+ const keys = ['con', 'nul', 'aux', 'prn', 'com1', 'lpt1'];
+ const source = {};
+ // `con` links to `nul` and `aux`, so both are minted first and `con` goes up with its tokens resolved; the rest link nowhere.
+ for (const key of keys) {
+ source[key] = key === 'con'
+ ? `export default function Con(){ ${NAV('nul')} ${NAV('aux')} return null; }`
+ : `export default function Page_${key}(){ return null; }`;
+ fs.writeFileSync(path.join(appDir, `src-${key}.tsx`), source[key], 'utf8');
+ }
+ const spec = {
+ schemaVersion: 2,
+ solution: { uniqueName: 'PgDeploy', displayName: 'Pg', publisherPrefix: 'contoso' },
+ app: { name: 'Deploy App' },
+ entities: [{ schemaName: 'contoso_item', displayName: 'Item', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] }],
+ pages: keys.map((key) => ({ key, name: `Page ${key}`, ...(key === 'con' ? { navigatesTo: [{ targetKey: 'nul' }, { targetKey: 'aux' }] } : {}), source: { kind: 'tsx', codeFile: `src-${key}.tsx` } })),
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Pages', subAreas: keys.map((page) => ({ page, title: page })) }] }] },
+ };
+ const uploads = [];
+ let minted = 0;
+ const genpageCli = {
+ enumerateEnv: async () => ({ ok: true, ids: [], pages: [] }),
+ upload: async (o) => {
+ uploads.push({ name: o.name, codeFile: o.codeFile, content: fs.readFileSync(o.codeFile, 'utf8') });
+ return { pageId: o.pageId || `5${String(++minted).padStart(7, '0')}-0000-4000-8000-000000000000` };
+ },
+ };
+ const { sdk } = mockSdk();
+ await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: PHASES });
+ assert.deepStrictEqual(uploads.map((u) => u.name).sort(), keys.map((k) => `Page ${k}`).sort(), 'every page goes up once');
+ for (const u of uploads) {
+ const base = path.basename(u.codeFile);
+ assert.doesNotMatch(base, DEVICE, `${u.name}: staged as "${base}", which Windows reserves for a device`);
+ assert.match(base, /\.tsx$/, `${u.name}: still a .tsx file, for pac to transpile`);
+ }
+ assert.strictEqual(new Set(uploads.map((u) => path.basename(u.codeFile))).size, uploads.length, 'one staging file per page');
+ for (const key of keys.filter((k) => k !== 'con')) assert.strictEqual(uploads.find((u) => u.name === `Page ${key}`).content, source[key], `${key}: the bytes the scan read`);
+ assert.doesNotMatch(uploads.find((u) => u.name === 'Page con').content, /PAGEREF_/, 'and the navigation page goes up with its tokens resolved');
+ const stagingRoot = path.join(appDir, '.maker-workspace', '.pageref-deploy');
+ assert.ok(!fs.existsSync(stagingRoot) || fs.readdirSync(stagingRoot).length === 0, 'the copies are removed when the build ends');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
diff --git a/plugins/model-apps/scripts/tests/sdk-build-pages-order.test.js b/plugins/model-apps/scripts/tests/sdk-build-pages-order.test.js
index 01792abbf..5e1c944a8 100644
--- a/plugins/model-apps/scripts/tests/sdk-build-pages-order.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-build-pages-order.test.js
@@ -62,6 +62,8 @@ function harness() {
removeElement: async () => { await Promise.resolve(); return {}; },
pushArtifact: async (t, id) => ({ type: t, id, saved: true, shipped: false, publish: { kind: 'notRequested' } }),
addSolutionComponent: async () => {}, publishArtifact: async (type, id) => ({ type, id, shipped: true, publish: { kind: 'verified' } }),
+ // The shared-page scan's one read of the apps that were never published: the app is the only one, and it is published.
+ dataverse: { get: async (url) => (url.startsWith('/appmodules/') ? { status: 200, body: { value: [{ appmoduleid: APP_ID, appmoduleidunique: SELF_UNIQUE_VALUE, componentstate: 0 }] } } : { status: 404, body: null }) },
};
const genpageCli = {
uploads: [],
diff --git a/plugins/model-apps/scripts/tests/sdk-build-publish-batch.test.js b/plugins/model-apps/scripts/tests/sdk-build-publish-batch.test.js
index 7901cb173..1eb9dd495 100644
--- a/plugins/model-apps/scripts/tests/sdk-build-publish-batch.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-build-publish-batch.test.js
@@ -11,7 +11,7 @@
// retry follows (settleOwedPublishes; the CLI side is pinned in build-model-app.test.js).
const { test } = require('node:test');
const assert = require('node:assert/strict');
-const { runSdkBuild, publishTargets, partialEnrichment, settleOwedPublishes, BuildHalt } = require('../lib/sdk-build.js');
+const { runSdkBuild, publishTargets, partialEnrichment, settleOwedPublishes, collectOwedPublishes, BuildHalt } = require('../lib/sdk-build.js');
const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');
// Two tables: Project (with a form, so phase 8 already names it) and Task (no form, view or chart,
@@ -112,7 +112,11 @@ test('a refused envelope falls back to the per-target path unchanged', async ()
});
const failure = (promise) => promise.then(() => assert.fail('the build was expected to halt'), (e) => e);
+// A target as a caller hands it to settleOwedPublishes: just the artifact that stands for its table.
const owedView = (logical) => ['view', `defview-${logical}`];
+// The same target as a halted build carries it: the artifact the SDK reported as saved but not published, and the name
+// of what it covers, which a failed publish then says (publishTargets).
+const savedDefaults = (logical, id = `defview-${logical}`) => ['view', id, [`default views of ${logical}`]];
test('a deferred enrichment that fails part-way halts, and the halt carries every publish still owed', async () => {
const PARTIAL = Symbol.for('cds-maker-sdk.partialDefaultViewEnrichment');
@@ -136,7 +140,7 @@ test('a deferred enrichment that fails part-way halts, and the halt carries ever
assert.ok(steps.some((e) => e.status === 'error' && /enrich default views for cnt_task/.test(e.label || '')), 'the failed step is reported');
// The build itself publishes nothing on a halt: only its caller knows whether a retry follows.
assert.equal(named(calls, 'publishArtifacts').length + named(calls, 'publishArtifact').length, 0);
- assert.deepEqual(halt.owedPublishes, [owedView('cnt_project'), owedView('cnt_task')], 'the table enriched before the failure, and what the failed call had saved');
+ assert.deepEqual(halt.owedPublishes, [savedDefaults('cnt_project'), savedDefaults('cnt_task')], 'the table enriched before the failure, and what the failed call had saved');
assert.equal(Object.keys(halt).includes('owedPublishes'), false, 'it rides along, never into a serialized error');
assert.equal(halt.owedPaid, false, 'no publish phase ran');
assert.equal(Object.keys(halt).includes('owedPaid'), false);
@@ -168,7 +172,7 @@ test('a default-view push refused by value (a concurrent edit) fails the enrichm
const halt = await failure(runSdkBuild(spec(), { sdk, apply: true, publish: true }));
assert.ok(halt instanceof BuildHalt && halt.phase === 'views' && halt.code === 'version-conflict', `${halt.code}: ${halt.message}`);
assert.match(halt.message, /default view defview-cnt_task-inactive of cnt_task/);
- assert.deepEqual(halt.owedPublishes, [owedView('cnt_project'), ['view', 'defview-cnt_task-active']], 'the saved view still owes its publish');
+ assert.deepEqual(halt.owedPublishes, [savedDefaults('cnt_project'), savedDefaults('cnt_task', 'defview-cnt_task-active')], 'the saved view still owes its publish');
assert.equal(halt.owedPaid, false);
assert.equal(named(calls, 'publishArtifacts').length + named(calls, 'publishArtifact').length, 0);
});
@@ -182,7 +186,7 @@ test('a later phase that halts hands every enriched table to the caller: nothing
const halt = await failure(runSdkBuild(spec(), { sdk, apply: true, publish: true }));
assert.ok(halt instanceof BuildHalt && halt.phase === 'app-shell', String(halt));
assert.equal(named(calls, 'publishArtifacts').length + named(calls, 'publishArtifact').length, 0);
- assert.deepEqual(halt.owedPublishes, [owedView('cnt_project'), owedView('cnt_task')]);
+ assert.deepEqual(halt.owedPublishes, [savedDefaults('cnt_project'), savedDefaults('cnt_task')]);
assert.equal(halt.owedPaid, false);
await settleOwedPublishes(sdk, halt.owedPublishes, () => {});
assert.deepEqual(named(calls, 'publishArtifacts').map((c) => c[1].map((t) => t.id)), [['defview-cnt_project', 'defview-cnt_task']]);
@@ -194,7 +198,7 @@ test('a halt inside the publish phase still owes; once that phase has run, a lat
inside.sdk.publishArtifact = async () => { throw new Error('publish down'); };
const halted = await failure(runSdkBuild(spec(), { sdk: inside.sdk, apply: true, publish: true }));
assert.ok(halted instanceof BuildHalt && halted.phase === 'publish', String(halted));
- assert.deepEqual(halted.owedPublishes, [owedView('cnt_project'), owedView('cnt_task')]);
+ assert.deepEqual(halted.owedPublishes, [savedDefaults('cnt_project'), savedDefaults('cnt_task')]);
assert.equal(halted.owedPaid, false, 'a publish phase that halts has paid nothing');
// After: the AI re-confirmation runs after the publish phase; an event it emits fails the build.
@@ -271,3 +275,172 @@ test('publishTargets: a single target and an empty list never use the envelope',
await publishTargets(provision, runner, 2, [['form', 'f1'], ['view', 'v1']], ['app', 'a1', 'app One'], () => {});
assert.deepEqual(calls.map((c) => c[0]), ['publishArtifacts', 'publishArtifact', 'publishArtifact', 'publishArtifact']);
});
+
+// `publishTargets` tells the publish phase whether the app's OWN publish went through, because an AI override saved in
+// the app's unpublished layer is in force once the app is published (and only then). The batched branch is the one a
+// build takes whenever tables and the app publish together, so it answers for itself.
+test('publishTargets reports whether the app\u2019s own publish went through, in the envelope or on its own', async () => {
+ const runner = { mapLimit: async (items, n, fn) => Promise.all(items.map(fn)) };
+ const publishOf = (kind) => (kind === 'failed' ? { kind, error: new Error('publish refused') } : kind === 'unverifiable' ? { kind, reason: 'the published copy was not read back' } : { kind });
+ const outcome = (type, id, kind) => ({ type, id, shipped: kind === 'verified', publish: publishOf(kind) });
+ // `envelope`: what the one envelope answers for [form, app]; `single`: what a publish on its own answers, by type.
+ const run = async ({ envelope, single = {}, entities = [['form', 'f1']], app = ['app', 'a1', 'app One'] }) => {
+ const provision = {
+ publishArtifacts: async (targets) => targets.map(({ type, id }, i) => outcome(type, id, envelope[i])),
+ publishArtifact: async (type, id) => outcome(type, id, single[type] || 'verified'),
+ };
+ return (await publishTargets(provision, runner, 2, entities, app, () => {})).appPublished;
+ };
+ assert.equal(await run({ envelope: ['verified', 'verified'] }), true);
+ assert.equal(await run({ envelope: ['verified', 'unverifiable'] }), true, 'PublishXml answered; only the read-back was not possible');
+ assert.equal(await run({ envelope: ['verified', 'failed'] }), true, 'failed in the envelope, published on its own');
+ assert.equal(await run({ envelope: ['verified', 'failed'], single: { app: 'unverifiable' } }), true);
+ assert.equal(await run({ envelope: ['verified', 'failed'], single: { app: 'failed' } }), false, 'failed in the envelope and again on its own');
+ assert.equal(await run({ envelope: ['failed', 'verified'], single: { form: 'failed' } }), true, 'another target\u2019s failure says nothing about the app');
+ assert.equal(await run({ envelope: ['verified', 'notRequested'] }), false, 'an outcome that says nothing about publishing proves nothing');
+ assert.equal(await run({ envelope: ['verified', 'verified'], app: null }), false, 'no app target, no app publish');
+ assert.equal(await run({ envelope: ['verified', 'verified', 'verified'], entities: [['form', 'f1'], ['view', 'v1']] }), true, 'the app\u2019s own entry is the one that counts, wherever it sits in the envelope');
+});
+
+test('publishTargets: a refused envelope falls back to per-target publishes, and the app\u2019s own decides', async () => {
+ const runner = { mapLimit: async (items, n, fn) => Promise.all(items.map(fn)) };
+ const run = async (appKind) => (await publishTargets({
+ publishArtifacts: async () => { throw new Error('ARTIFACT_NOT_FOUND: view/x not in workspace'); },
+ publishArtifact: async (type, id) => ({ type, id, publish: type === 'app' && appKind === 'failed' ? { kind: 'failed', error: new Error('refused') } : { kind: appKind === 'unverifiable' && type === 'app' ? 'unverifiable' : 'verified' } }),
+ }, runner, 2, [['form', 'f1']], ['app', 'a1', 'app One'], () => {})).appPublished;
+ assert.equal(await run('verified'), true);
+ assert.equal(await run('unverifiable'), true);
+ assert.equal(await run('failed'), false);
+});
+
+// `failed` names the TABLE targets whose last publish the SDK refused by value — the ones whose saved changes are not live.
+// The build halts on one before it writes the app (publishReconciledTables), so a table the envelope refused but its own
+// publish then took must not be in it, nor the app's own failure, nor an outcome that is not a refusal.
+test('publishTargets names each table whose publish stayed refused, in the envelope and on its own, and nothing else', async () => {
+ const runner = { mapLimit: async (items, n, fn) => Promise.all(items.map(fn)) };
+ const refused = new Error('PublishXml refused');
+ const outcome = (type, id, kind) => ({ type, id, publish: kind === 'failed' ? { kind, error: refused } : { kind } });
+ const failedOf = async ({ envelope, single = {}, batch = true }) => (await publishTargets({
+ ...(batch ? { publishArtifacts: async (targets) => targets.map(({ type, id }, i) => outcome(type, id, envelope[i])) } : {}),
+ publishArtifact: async (type, id) => outcome(type, id, single[type] || 'submitted'),
+ }, runner, 2, [['form', 'f1', ['form Ticket']], ['view', 'v1']], ['app', 'a1', 'app One'], () => {})).failed;
+ assert.deepEqual(await failedOf({ envelope: ['submitted', 'submitted', 'submitted'] }), []);
+ assert.deepEqual(await failedOf({ envelope: ['failed', 'submitted', 'submitted'] }), [], 'refused in the envelope, taken on its own');
+ assert.deepEqual(await failedOf({ envelope: ['failed', 'submitted', 'submitted'], single: { form: 'failed' } }), [{ target: ['form', 'f1', ['form Ticket']], error: refused }]);
+ assert.deepEqual(await failedOf({ envelope: ['submitted', 'submitted', 'failed'], single: { app: 'failed' } }), [], 'the app is no table');
+ assert.deepEqual(await failedOf({ envelope: ['submitted', 'unverifiable', 'submitted'] }), [], 'unconfirmed is not refused');
+ assert.deepEqual(await failedOf({ batch: false, single: { view: 'failed' } }), [{ target: ['view', 'v1'], error: refused }], 'one table at a time');
+});
+
+// The same fixture with an AI override that the SDK saved but could not yet publish — the case the report is for. The
+// override row reads as present only once an app publish has really gone through, as on a live environment.
+function aiBatchSdk({ envelope, single } = {}) {
+ const state = { inForce: false };
+ const { sdk, calls } = batchSdk({
+ envelope: (targets) => {
+ const out = envelope ? envelope(targets) : targets.map(({ type, id }) => ({ type, id, shipped: true, publish: { kind: 'verified' } }));
+ out.forEach((o, i) => { if (targets[i].type === 'app' && o.publish.kind !== 'failed') state.inForce = true; });
+ return out;
+ },
+ });
+ sdk.publishArtifact = async (type, id) => {
+ calls.push(['publishArtifact', type, id]);
+ const publish = single ? single(type) : { kind: 'verified' };
+ if (type === 'app' && publish.kind !== 'failed') state.inForce = true;
+ return { type, id, shipped: publish.kind === 'verified', publish };
+ };
+ const fetched = sdk.fetchArtifact;
+ sdk.fetchArtifact = async (type, id, ...rest) => { calls.push(['fetchArtifact', type, id]); return fetched(type, id, ...rest); };
+ const query = sdk.queryRecords;
+ sdk.queryRecords = async (entity, ...rest) => {
+ if (entity === 'appmodule') return [{ appmoduleid: 'APPID' }];
+ if (entity === 'settingdefinition') return [{ settingdefinitionid: 'DEFID' }];
+ if (entity === 'appsetting') return state.inForce ? [{ value: '2' }] : [];
+ return query(entity, ...rest);
+ };
+ sdk.setAppAiFeatures = async (appUnique, flags) => {
+ calls.push(['setAppAiFeatures', appUnique, flags]);
+ return { applied: ['formFill'], skipped: [], notPersisted: [], unverified: [], failed: [], outcomes: [{ feature: 'formFill', status: 'applied', appOverrideExists: true, pendingPublish: true }] };
+ };
+ return { sdk, calls };
+}
+const aiSpec = () => ({ ...spec(), ai: { appFeatures: { formFill: true }, summaries: { default: 'off' } } });
+const aiWarnings = (events) => events.filter((e) => e.phase === 'ai-features' && e.status === 'skip').map((e) => e.label);
+const appPublishes = (calls) => named(calls, 'publishArtifact').filter((c) => c[1] === 'app');
+
+test('with --publish, an app the envelope published is not published again for a saved AI override: it is only proved', async () => {
+ const { sdk, calls } = aiBatchSdk();
+ const events = [];
+ const r = await runSdkBuild(aiSpec(), { sdk, apply: true, publish: true, emit: (e) => events.push(e) });
+ assert.equal(named(calls, 'publishArtifacts').length, 1, 'one envelope');
+ assert.equal(appPublishes(calls).length, 0, 'the app rode in the envelope; nothing publishes it again');
+ assert.equal(named(calls, 'fetchArtifact').filter((c) => c[1] === 'app').length, 0, 'and it is not fetched for a retry');
+ assert.equal(named(calls, 'setAppAiFeatures').length, 1, 'nor is the override written again');
+ assert.deepEqual(r.created.ai.appFeatures.applied, ['formFill']);
+ assert.deepEqual(aiWarnings(events), []);
+});
+
+test('with --publish, an app the envelope could not publish is published again for a saved AI override, and the result is the proof\u2019s', async () => {
+ const failedApp = { kind: 'failed', error: new Error('publish refused') };
+ const { sdk, calls } = aiBatchSdk({
+ envelope: (targets) => targets.map(({ type, id }) => (type === 'app'
+ ? { type, id, shipped: false, publish: failedApp }
+ : { type, id, shipped: true, publish: { kind: 'verified' } })),
+ single: (type) => (type === 'app' ? failedApp : { kind: 'verified' }),
+ });
+ const events = [];
+ const r = await runSdkBuild(aiSpec(), { sdk, apply: true, publish: true, emit: (e) => events.push(e), warn: () => {}, proofDelayMs: 0 });
+ assert.equal(appPublishes(calls).length, 2, 'on its own after the envelope, and once more for the override');
+ assert.equal(named(calls, 'setAppAiFeatures').length, 1, 'publishing is what a saved override needs; it is not written again');
+ assert.ok(aiWarnings(events).some((l) => /NOT YET PUBLISHED: formFill/.test(l)), JSON.stringify(aiWarnings(events)));
+ assert.ok(!r.created.ai.appFeatures.applied.includes('formFill'));
+});
+
+test('with --publish, an app the envelope could not publish but its own publish then did is not published a third time', async () => {
+ const { sdk, calls } = aiBatchSdk({
+ envelope: (targets) => targets.map(({ type, id }) => (type === 'app'
+ ? { type, id, shipped: false, publish: { kind: 'failed', error: new Error('envelope 400') } }
+ : { type, id, shipped: true, publish: { kind: 'verified' } })),
+ });
+ const r = await runSdkBuild(aiSpec(), { sdk, apply: true, publish: true });
+ assert.equal(appPublishes(calls).length, 1, 'the retry on its own is the app\u2019s publish; the override needs no other');
+ assert.deepEqual(r.created.ai.appFeatures.applied, ['formFill']);
+});
+
+// A target is `[type, id]` plus, optionally, what it is for: the names of the saved views and forms deferred onto its
+// table, or the app's label. A line about a publish that failed or could not be confirmed says that, not `form <guid>`.
+test('publishTargets names what a target is for in every line it prints, and falls back to `type id` for one that is not named', async () => {
+ const runner = { mapLimit: async (items, n, fn) => Promise.all(items.map(fn)) };
+ const down = (type, id) => ({ type, id, shipped: false, publish: { kind: 'failed', error: new Error('PublishXml 500') } });
+ const targets = [['form', 'f1', ['view Open Tickets', 'form Ticket']], ['view', 'v2']];
+
+ // One envelope that fails, then each failed target alone (which fails again).
+ const warnings = [];
+ await publishTargets({ publishArtifacts: async (t) => t.map(({ type, id }) => down(type, id)), publishArtifact: async (type, id) => down(type, id) }, runner, 2, targets, ['app', 'a1', 'app One'], (w) => warnings.push(w));
+ assert.deepEqual(warnings.map((w) => w.replace(/ FAILED:.*/, '')), ['publish view Open Tickets, form Ticket', 'publish view v2', 'publish app One']);
+
+ // Without an envelope each target is published alone, and named the same way.
+ warnings.length = 0;
+ await publishTargets({ publishArtifact: async (type, id) => down(type, id) }, runner, 2, targets, null, (w) => warnings.push(w));
+ assert.deepEqual(warnings.map((w) => w.replace(/ FAILED:.*/, '')), ['publish view Open Tickets, form Ticket', 'publish view v2']);
+
+ // A publish that cannot be CONFIRMED is named too.
+ warnings.length = 0;
+ const unverifiable = (type, id) => ({ type, id, shipped: false, publish: { kind: 'unverifiable', reason: 'projection not readable' } });
+ await publishTargets({ publishArtifacts: async (t) => t.map(({ type, id }) => unverifiable(type, id)) }, runner, 2, targets, null, (w) => warnings.push(w));
+ assert.deepEqual(warnings, [
+ 'publish view Open Tickets, form Ticket could not be CONFIRMED (projection not readable) — the publish call succeeded but the published projection was not read back, so treat "live" as unproven',
+ 'publish view v2 could not be CONFIRMED (projection not readable) — the publish call succeeded but the published projection was not read back, so treat "live" as unproven',
+ ]);
+});
+
+test('collectOwedPublishes keeps one entry per target and unions the names every attempt recorded for it', () => {
+ const byTarget = new Map();
+ collectOwedPublishes(byTarget, [['view', 'v1', ['view A']], ['view', 'v2']]);
+ collectOwedPublishes(byTarget, [['view', 'v1', ['view A', 'form B']], ['view', 'v2']]);
+ collectOwedPublishes(byTarget, [['view', 'v1', ['form C']]]); // an attempt that stopped before the others got as far
+ assert.deepEqual([...byTarget.values()], [['view', 'v1', ['view A', 'form B', 'form C']], ['view', 'v2']]);
+ assert.equal(collectOwedPublishes(byTarget, undefined), byTarget);
+ for (const nothing of [undefined, null, 'view:v1', [], [null], [undefined]]) collectOwedPublishes(byTarget, nothing);
+ assert.equal(byTarget.size, 2, 'anything that is not a list of targets adds nothing');
+});
diff --git a/plugins/model-apps/scripts/tests/sdk-build.test.js b/plugins/model-apps/scripts/tests/sdk-build.test.js
index 6534f89f3..2bff4276a 100644
--- a/plugins/model-apps/scripts/tests/sdk-build.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-build.test.js
@@ -4,8 +4,12 @@ const assert = require('node:assert');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
-const { commandDef, chartDef, runSdkBuild, planFor, resolvePhases, compileFormIntent, formFieldLogicals, viewDef, appDef, defaultViewColumns, enrichesDefaultViews, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, dashboardTileOpts, PHASES, appUniqueName, personaRoleSpecFor } = require('../lib/sdk-build.js');
+const { commandDef, chartDef, runSdkBuild: runSdkBuildWithRealWaits, planFor, resolvePhases, compileFormIntent, formFieldLogicals, viewDef, appDef, defaultViewColumns, enrichesDefaultViews, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, dashboardTileOpts, PHASES, appUniqueName, personaRoleSpecFor } = require('../lib/sdk-build.js');
const { validateAppSpec } = require('../lib/app-spec.js');
+// The AI phase's proof after a publish waits 500 ms between reads of an override row that is not there yet, as --verify
+// does. No test below is about that wait (it is pinned through `proofBudget`), and every one that leaves a row absent
+// would otherwise sleep a second for it.
+const runSdkBuild = (spec, opts = {}) => runSdkBuildWithRealWaits(spec, { proofDelayMs: 0, ...opts });
// Real GUIDs (Imp9) for the three-authority sitemap mock. SELF_* identify THIS app's appmodule + sitemap
// so fetchSitemap(appUnique) resolves to opts.liveSitemapXml; otherApps get synthetic ids. Ids that flow
@@ -13,6 +17,9 @@ const { validateAppSpec } = require('../lib/app-spec.js');
const APP_ID = 'a1b2c3d4-0000-4000-8000-000000000001';
const SELF_UNIQUE_VALUE = 'c0ffee00-0000-4000-8000-00000000dddd';
const SELF_SITEMAP_ID = '5111e0f2-0000-4000-8000-0000000000aa';
+// A never-published app (mockSdk opts.draftApps) has a layer key and a sitemap id of its own, both real GUIDs: the layer key goes into a Dataverse filter, so the scan refuses one that is not.
+const draftLayerKey = (j) => `c0ffee00-0000-4000-8000-0000000000d${j}`;
+const draftSitemapId = (j) => `5111e0f2-0000-4000-8000-0000000000d${j}`;
// A valid, page-less sitemap (passes sitemap-pages.isMalformed) — the default membership for a build that
// does not seed opts.liveSitemapXml.
const EMPTY_SITEMAP_XML = '<SiteMap><Area><Group></Group></Area></SiteMap>';
@@ -87,6 +94,7 @@ function seedForm(id, fields) {
}
// `existingTables`: { logical: { entitySetName, columns:[logical...], relationships:[schema...] } }
+const MEMBER_SOLUTION_ID = '5011c0de-0000-4000-8000-000000000001'; // a GUID: the membership read interpolates it unquoted
function mockSdk(opts = {}) {
const calls = [];
let idc = 0;
@@ -96,7 +104,11 @@ function mockSdk(opts = {}) {
queryRecords: async (e, o) => {
calls.push({ name: 'queryRecords', args: [e, o] });
const filter = (o && o.filter) || '';
- if (e === 'solution') return opts.solutionExists ? [{ solutionid: 's' }] : [];
+ if (e === 'solution') return opts.solutionMembers ? [{ solutionid: MEMBER_SOLUTION_ID }] : opts.solutionExists ? [{ solutionid: 's' }] : [];
+ // The components the solution is proven to hold, `[componenttype, objectid]` pairs — the one
+ // read the build makes (solution-membership.js) before it re-adds anything it reuses.
+ // A row may carry a third element, the table's `rootcomponentbehavior` (0 Include Subcomponents).
+ if (e === 'solutioncomponent' && opts.solutionMembers) return opts.solutionMembers.map(([componenttype, objectid, rootcomponentbehavior]) => ({ componenttype, objectid, ...(rootcomponentbehavior === undefined ? {} : { rootcomponentbehavior }) }));
// Which dashboards the app's solution holds (componenttype 60 = systemform) — the ownership
// evidence the build uses to pick among several same-named dashboards.
if (e === 'solutioncomponent' && /componenttype eq 60/.test(filter)) {
@@ -134,6 +146,13 @@ function mockSdk(opts = {}) {
if (opts.failSitemap) return []; // membership read failure → sitemap-component-not-found
const uv = (filter.match(/_appmoduleidunique_value eq (\S+)/) || [])[1];
if (uv === SELF_UNIQUE_VALUE) return [{ objectid: SELF_SITEMAP_ID, componenttype: 62 }];
+ // A never-published app's sitemap component hangs off the layer key its draft row carries.
+ const dj = (opts.draftApps || []).findIndex((_, j) => draftLayerKey(j) === uv);
+ if (dj >= 0) {
+ // `componentReadFails`: the read itself fails (a 5xx, a timeout), which proves nothing about the app — unlike an answer with no rows.
+ if (opts.draftApps[dj].componentReadFails) throw new Error('component read failed');
+ return opts.draftApps[dj].noSitemapComponent ? [] : [{ objectid: draftSitemapId(dj), componenttype: 62 }];
+ }
const idx = (opts.otherApps || []).findIndex((_, i) => `uv-${i + 2}` === uv);
return [{ objectid: `sm-${idx + 2}`, componenttype: 62 }];
}
@@ -405,6 +424,44 @@ function mockSdk(opts = {}) {
disassociateRecords: async (e, id, rel, targetId) => { calls.push({ name: 'disassociateRecords', args: [e, id, rel, targetId] }); if (opts.dissociateGone) { const err = new Error('HTTP 404 from ...: does not exist'); err.statusCode = 404; throw err; } },
deleteSecurityRole: async (id) => { calls.push({ name: 'deleteSecurityRole', args: [id] }); },
};
+ // The other apps' navigation, read through the SDK's Dataverse client (fetchAppsForPages). Attached for a build that has an app identity to scan from (`selfAppUnique`) or other
+ // apps to find: the scan lists the apps that were never published (one RetrieveUnpublishedMultiple read on the `appmodule` collection) even when there is no other app, as the real
+ // SDK always has a client to read it with. A build without one keeps no client, so the table-reuse and relationship probes — which also look for it — read as they always did.
+ // apps list self and every other app have their published row (componentstate 0); `draftApps` ([{ uniquename, savedSitemapXml }]) were NEVER published, so they have
+ // no published row and one draft row (componentstate 1) with a layer key of its own. opts.draftAppsError makes this read fail.
+ // saved sitemaps every sitemap's current layer, in one read; every row carries its sitemap's `sitemapnameunique`, which is its app's unique name (the SDK names an app's sitemap after the
+ // app). An app with no `savedSitemapXml` has nothing pending: the one row is its published sitemap; with one, the platform
+ // answers with both layers. opts.savedNavigationError makes the read fail as a whole; an app's `savedRows` replaces its rows (e.g. to leave them out). A draft app's
+ // one row is its saved sitemap; it may set `noSitemapComponent` (its layer has no sitemap component to find), `componentReadFails` (the read of its components fails) or
+ // `sitemapName` (the unique name its sitemap carries, when it is not the app's own).
+ if (opts.selfAppUnique !== undefined || (opts.otherApps || []).length || (opts.draftApps || []).length) sdk.dataverse = {
+ get: async (url) => {
+ calls.push({ name: 'dataverse.get', args: [url] });
+ if (/^\/appmodules\/Microsoft\.Dynamics\.CRM\.RetrieveUnpublishedMultiple\(\)/.test(url)) {
+ if (opts.draftAppsError) return { status: 503, body: null };
+ const value = [{ appmoduleid: APP_ID, appmoduleidunique: SELF_UNIQUE_VALUE, uniquename: opts.selfAppUnique, componentstate: 0 }];
+ (opts.otherApps || []).forEach((a, i) => value.push({ appmoduleid: `app-${i + 2}`, appmoduleidunique: `uv-${i + 2}`, uniquename: a.uniquename, componentstate: 0 }));
+ (opts.draftApps || []).forEach((d, j) => value.push({ appmoduleid: `draft-${j}`, appmoduleidunique: draftLayerKey(j), uniquename: d.uniquename, componentstate: 1 }));
+ return { status: 200, body: { value } };
+ }
+ if (!/^\/sitemaps\/Microsoft\.Dynamics\.CRM\.RetrieveUnpublishedMultiple\(\)/.test(url)) return { status: 404, body: null };
+ if (opts.savedNavigationError) return { status: 503, body: null };
+ const value = [];
+ (opts.otherApps || []).forEach((a, i) => {
+ const sitemapid = `sm-${i + 2}`;
+ const sitemapnameunique = a.uniquename;
+ if (a.savedRows) value.push(...a.savedRows.map((r) => ({ sitemapid, sitemapnameunique, ...r })));
+ else if (a.savedSitemapXml !== undefined) value.push({ sitemapid, sitemapnameunique, sitemapxml: a.sitemapxml, componentstate: 0 }, { sitemapid, sitemapnameunique, sitemapxml: a.savedSitemapXml, componentstate: 1 });
+ else value.push({ sitemapid, sitemapnameunique, sitemapxml: a.sitemapxml, componentstate: 0 });
+ });
+ (opts.draftApps || []).forEach((d, j) => {
+ const sitemapnameunique = d.sitemapName === undefined ? d.uniquename : d.sitemapName;
+ if (d.savedRows) value.push(...d.savedRows.map((r) => ({ sitemapid: draftSitemapId(j), sitemapnameunique, ...r })));
+ else value.push({ sitemapid: draftSitemapId(j), sitemapnameunique, sitemapxml: d.savedSitemapXml, componentstate: 1 });
+ });
+ return { status: 200, body: { value } };
+ },
+ };
return { sdk, calls };
}
const find = (calls, name) => calls.filter((c) => c.name === name);
@@ -617,6 +674,14 @@ test('app icon: an explicit spec.app.icon (declared web resource) is used instea
assert.ok(appCreate.args[1].iconWebResourceId, 'app def carries the explicit icon id');
});
+test('app create: the def leaves `published` unset, so the SDK publishes the new app (a draft is invisible to the build\'s own probes)', async () => {
+ const { sdk, calls } = mockSdk();
+ await runSdkBuild(makeSpec(), { sdk, apply: true, phases: ['solution', 'data-model', 'web-resources', 'app-shell'] });
+ const appCreate = find(calls, 'createArtifact').find((c) => c.args[0] === 'app');
+ assert.ok(appCreate, 'the app is created');
+ assert.ok(!('published' in appCreate.args[1]), `published must stay unset; def keys: ${Object.keys(appCreate.args[1]).join(', ')}`);
+});
+
test('sitemap: the app sitemap is added to the solution (componenttype 62)', async () => {
const { sdk, calls } = mockSdk();
await runSdkBuild(makeSpec(), { sdk, apply: true, phases: ['solution', 'data-model', 'app-shell'] });
@@ -1254,6 +1319,162 @@ test('apply progress total covers the existing-app sitemap finalize on a page-le
assert.equal(terminal.at(-1).n, terminal.at(-1).total, 'the final step index must equal the advertised total');
});
+// Live-measured: once a table's EXISTING form is saved, a PublishXml that names only the app, sent before the table's
+// own publish, leaves the form's label changes unpublished for good (publishReconciledTables in sdk-build.js). With
+// --publish a reconcile defers its table's publish to phase 8, so every table it deferred must be published before the
+// first write that can publish the app: an existing app's sitemap finalize or app-shell publish, and a new app's create
+// push. Order is what these pin; the label loss itself is a platform behaviour no mock reproduces.
+const RECONCILE_PHASES = ['views', 'charts', 'forms', 'app-shell', 'pages', 'publish'];
+function firstAppWrite(calls) {
+ return calls.findIndex((c) => (c.name === 'createArtifact' || c.name === 'pushArtifact' || c.name === 'publishArtifact') && c.args[0] === 'app');
+}
+// The publishes in a slice of the call log, one `type id` per artifact: a per-target publish, or each target of an envelope.
+const publishesIn = (slice) => slice.flatMap((c) => (c.name === 'publishArtifact' ? [`${c.args[0]} ${c.args[1]}`]
+ : c.name === 'publishArtifacts' ? c.args[0].map((t) => `${t.type} ${t.id}`) : []));
+function assertReconciledPublishedBeforeApp(calls) {
+ const boundary = firstAppWrite(calls);
+ assert.ok(boundary > 0, 'the build writes the app');
+ const before = publishesIn(calls.slice(0, boundary));
+ assert.ok(before.includes('form form-existing'), `the reconciled Customer form's table is published before the app: ${before.join(', ') || 'nothing'}`);
+ assert.ok(before.includes('view view-existing'), `the reconciled Active Tickets view's table is published before the app: ${before.join(', ') || 'nothing'}`);
+ const after = publishesIn(calls.slice(boundary));
+ assert.ok(after.includes('form form-existing'), `phase 8 still publishes the table with everything else: ${after.join(', ')}`);
+}
+
+test('with --publish, the tables a rebuild reconciled are published before the sitemap finalize publishes the app', async () => {
+ const { sdk, calls } = mockSdk({ artifactsExist: true });
+ await runSdkBuild(makeSpec(), { sdk, apply: true, publish: true, phases: RECONCILE_PHASES, genpageCli: noPages });
+ assertReconciledPublishedBeforeApp(calls);
+});
+
+test('with --publish and no pages phase, the tables a rebuild reconciled are published before the app-shell publishes the app', async () => {
+ const { sdk, calls } = mockSdk({ artifactsExist: true });
+ await runSdkBuild(makeSpec(), { sdk, apply: true, publish: true, phases: RECONCILE_PHASES.filter((p) => p !== 'pages') });
+ assertReconciledPublishedBeforeApp(calls);
+});
+
+test('with --publish, the tables a first build reconciled are published before the new app is created, whose push publishes it', async () => {
+ const { sdk, calls } = mockSdk({ artifactsExist: true });
+ // The forms and views exist (a spec over tables another build left), the app does not.
+ const find = sdk.findArtifact;
+ sdk.findArtifact = async (kind, identity) => (kind === 'app' ? (calls.push({ name: 'findArtifact', args: [kind, identity] }), null) : find(kind, identity));
+ const list = sdk.listArtifacts;
+ sdk.listArtifacts = async (kind) => (kind === 'app' ? [] : list(kind));
+ await runSdkBuild(makeSpec(), { sdk, apply: true, publish: true, phases: RECONCILE_PHASES, genpageCli: noPages });
+ assert.ok(calls.some((c) => c.name === 'createArtifact' && c.args[0] === 'app'), 'the app is created');
+ assertReconciledPublishedBeforeApp(calls);
+});
+
+test('without --publish the reconciles publish their own tables as before, and the app step publishes nothing extra', async () => {
+ const { sdk, calls } = mockSdk({ artifactsExist: true });
+ await runSdkBuild(makeSpec(), { sdk, apply: true, publish: false, phases: RECONCILE_PHASES, genpageCli: noPages });
+ const boundary = firstAppWrite(calls);
+ const before = calls.slice(0, boundary).filter((c) => c.name === 'publishArtifact').map((c) => `${c.args[0]} ${c.args[1]}`);
+ assert.deepEqual(before.filter((p) => p === 'form form-existing').length, 1, `the form reconcile's own publish, once: ${before.join(', ')}`);
+ assert.deepEqual(before.filter((p) => p === 'view view-existing').length, 1, `the view reconcile's own publish, once: ${before.join(', ')}`);
+});
+
+// The SDK the build uses, with an envelope publish (`publishArtifacts`) when `envelope` is set: `outcome(type, id)` answers
+// both the envelope's targets and a per-target publish; it defaults to a verified publish.
+function publishingSdk({ envelope = false, outcome } = {}) {
+ const mock = mockSdk({ artifactsExist: true });
+ const { sdk, calls } = mock;
+ const single = sdk.publishArtifact;
+ const answer = (type, id) => (outcome && outcome(type, id)) || { type, id, shipped: true, publish: { kind: 'verified' } };
+ sdk.publishArtifact = async (type, id) => {
+ const own = outcome && outcome(type, id);
+ if (!own) return single(type, id);
+ calls.push({ name: 'publishArtifact', args: [type, id] });
+ return own;
+ };
+ if (envelope) sdk.publishArtifacts = async (targets) => { calls.push({ name: 'publishArtifacts', args: [targets] }); return targets.map(({ type, id }) => answer(type, id)); };
+ return mock;
+}
+const refusedPublish = (type, id) => ({ type, id, shipped: false, publish: { kind: 'failed', error: new Error('PublishXml refused (test)') } });
+
+for (const envelope of [false, true]) {
+ const how = envelope ? 'in one envelope' : 'one table at a time';
+ test(`with --publish, the app step waits until the tables a rebuild reconciled are published (${how})`, async () => {
+ const { sdk, calls } = publishingSdk({ envelope });
+ let release;
+ const gate = new Promise((resolve) => { release = resolve; });
+ let held = 0;
+ for (const name of ['publishArtifact', 'publishArtifacts']) {
+ const inner = sdk[name];
+ if (typeof inner !== 'function') continue;
+ sdk[name] = async (...args) => {
+ if (release && !(name === 'publishArtifact' && args[0] === 'app')) { held += 1; await gate; }
+ return inner(...args);
+ };
+ }
+ const run = runSdkBuild(makeSpec(), { sdk, apply: true, publish: true, phases: RECONCILE_PHASES, genpageCli: noPages });
+ for (let i = 0; i < 2000 && held === 0; i += 1) await new Promise((resolve) => setImmediate(resolve));
+ assert.ok(held > 0, 'the reconciled tables are being published');
+ for (let i = 0; i < 200; i += 1) await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(firstAppWrite(calls), -1, 'nothing creates, pushes or publishes the app while that publish is outstanding');
+ const open = release;
+ release = null;
+ open();
+ await run;
+ assertReconciledPublishedBeforeApp(calls);
+ });
+}
+
+test('with --publish, a reconciled table whose early publish is refused stops the build before anything writes the app', async () => {
+ const { sdk, calls } = publishingSdk({ outcome: (type, id) => (type === 'form' ? refusedPublish(type, id) : null) });
+ const warnings = [];
+ const halt = await runSdkBuild(makeSpec(), { sdk, apply: true, publish: true, phases: RECONCILE_PHASES, genpageCli: noPages, warn: (w) => warnings.push(String(w)) }).then(() => null, (e) => e);
+ assert.ok(halt, 'the build halts');
+ assert.equal(halt.code, 'reconciled-publish-failed', halt.message);
+ assert.equal(halt.phase, 'app-shell');
+ assert.match(halt.message, /publish form Customer FAILED before the app was written: PublishXml refused \(test\)/);
+ assert.equal(firstAppWrite(calls), -1, 'the app is neither created, pushed nor published');
+ assert.ok(warnings.some((w) => /publish form Customer FAILED/.test(w)), warnings.join(' | '));
+ assert.ok(Array.isArray(halt.owedPublishes) && halt.owedPublishes.some(([type, id]) => type === 'form' && id === 'form-existing'),
+ 'the halt carries the table it owes, for the CLI to publish without the app once no retry follows');
+});
+
+test('with --publish, a reconciled table the envelope and then its own publish both refuse stops the build before the app', async () => {
+ const { sdk, calls } = publishingSdk({ envelope: true, outcome: (type, id) => (type === 'form' ? refusedPublish(type, id) : null) });
+ const halt = await runSdkBuild(makeSpec(), { sdk, apply: true, publish: true, phases: RECONCILE_PHASES, genpageCli: noPages, warn: () => {} }).then(() => null, (e) => e);
+ assert.ok(halt, 'the build halts');
+ assert.equal(halt.code, 'reconciled-publish-failed', halt.message);
+ assert.equal(firstAppWrite(calls), -1);
+ assert.deepEqual(publishesIn(calls).filter((p) => p === 'form form-existing').length, 2, 'the envelope, then the form on its own');
+});
+
+test('with --publish, a reconciled table the envelope refuses but its own publish then takes does not stop the build', async () => {
+ let envelopeSeen = false;
+ const { sdk, calls } = publishingSdk({ envelope: true });
+ const envelope = sdk.publishArtifacts;
+ sdk.publishArtifacts = async (targets) => {
+ const results = await envelope(targets);
+ if (envelopeSeen) return results;
+ envelopeSeen = true;
+ return results.map((r) => (r.type === 'form' ? refusedPublish(r.type, r.id) : r));
+ };
+ await runSdkBuild(makeSpec(), { sdk, apply: true, publish: true, phases: RECONCILE_PHASES, genpageCli: noPages, warn: () => {} });
+ assertReconciledPublishedBeforeApp(calls);
+});
+
+// The runner wraps the halt once more, and the CLI's retry check reads a status only on the halt it is given and on that
+// halt's cause: the refusal's status must reach it, or a throttled publish is never re-run.
+test('with --publish, an early publish refused with a 429 or a 503 halts as transient; a 400, or a refusal marked never-retry, does not', async () => {
+ const { isTransientHalt } = require(path.join(__dirname, '..', 'build-model-app.js'));
+ const haltFor = async (statusCode, extra = {}) => {
+ const error = Object.assign(new Error(`HTTP ${statusCode} from PublishXml (test)`), { statusCode }, extra);
+ const { sdk } = publishingSdk({ outcome: (type, id) => (type === 'form' ? { type, id, shipped: false, publish: { kind: 'failed', error } } : null) });
+ return runSdkBuild(makeSpec(), { sdk, apply: true, publish: true, phases: RECONCILE_PHASES, genpageCli: noPages, warn: () => {} }).then(() => null, (e) => e);
+ };
+ for (const status of [429, 503]) {
+ const halt = await haltFor(status);
+ assert.equal(halt && halt.code, 'reconciled-publish-failed');
+ assert.equal(isTransientHalt(halt), true, `${status}: the build is run again at once`);
+ }
+ assert.equal(isTransientHalt(await haltFor(400)), false, 'a refusal a re-run cannot change is final');
+ assert.equal(isTransientHalt(await haltFor(429, { transient: false })), false, 'an explicit never-retry still wins');
+});
+
// --- Tier 2.x: SDK fix uptake (AutoNumber primary, N:N sub-grids) + folded build steps ----
test('AutoNumber primary column flows to createTable.primaryColumnAutoNumberFormat', async () => {
const spec = makeSpec();
@@ -1278,6 +1499,25 @@ test('formDef forces single-column sections for a field-heavy QuickCreate form',
assert.strictEqual(qc.tabs[0].columns[0].sections[0].columns, 1, 'QuickCreate form is forced to a single column');
});
+// Dataverse refuses a multi-column section on a Quick View form exactly as it does on a Quick Create one —
+// live: "HTTP 400 … systemforms: Columns in a section must be set to '1'. Found '11'." for a Quick View whose
+// auto layout went to two columns past six fields, which failed the build mid-run.
+test('formDef forces single-column sections for a field-heavy QuickView form, auto and explicit', () => {
+ const { sectionGridWidth } = require('../lib/artifact-intent.js');
+ const spec = makeSpec();
+ const cust = spec.entities.find((e) => e.schemaName === 'new_customer');
+ cust.columns = Array.from({ length: 8 }, (_, i) => ({ schemaName: `new_c${i}`, displayName: `C${i}`, type: 'Text' }));
+ const auto = compileFormIntent(spec, { entity: 'new_customer', name: 'Card', formType: 'QuickView', layout: 'auto' });
+ const autoSection = auto.tabs[0].columns[0].sections[0];
+ assert.strictEqual(autoSection.columns, 1, 'a field-heavy QuickView auto layout stays single-column');
+ assert.ok(autoSection.rows.every((r) => r.cells.length === 1), 'one cell per row in a single-column section');
+ const explicit = compileFormIntent(spec, { entity: 'new_customer', name: 'Card', formType: 'QuickView',
+ tabs: [{ label: 'G', sections: [{ label: 'S', columns: 2, fields: ['new_name', 'new_c0', 'new_c1'] }] }] });
+ assert.strictEqual(explicit.tabs[0].columns[0].sections[0].columns, 1, 'an authored two-column QuickView section is clamped to 1');
+ assert.strictEqual(sectionGridWidth({ columns: 2 }, 'QuickView'), 1, 'verify judges a QuickView section by the same width');
+ assert.strictEqual(sectionGridWidth({ columns: 2 }, 'Main'), 2, 'a Main form keeps its authored width');
+});
+
test('formDef clamps an explicitly authored multi-column section to 1 for QuickCreate', () => {
const spec = makeSpec();
const qc = compileFormIntent(spec, { entity: 'new_customer', name: 'QC', formType: 'QuickCreate',
@@ -1995,6 +2235,31 @@ test('quick-view placement halts clearly when the referenced form was not built'
await assert.rejects(runSdkBuild(spec, { sdk, apply: true }), /quick-view references form 'Nope' on 'new_customer' which wasn't built/);
});
+// Quick views went into the first section of the first form-column — which is a sub-grid's section once the grid is
+// placed in front of the form's own. It is the first FIELD section they belong in, as a field with no section of
+// its own is put.
+test('quick-view placement: the quick view goes into the first field section, not a sub-grid section placed ahead of it', async () => {
+ const spec = makeSpec();
+ spec.forms = [
+ { entity: 'new_customer', name: 'Customer', formType: 'Main', layout: 'auto',
+ subgrids: [{ childEntity: 'new_ticket', before: 'section_general' }],
+ quickViews: [{ lookup: 'new_primaryticket', targetEntity: 'new_ticket', form: 'Ticket QV', label: 'Ticket' }] },
+ { entity: 'new_ticket', name: 'Ticket QV', formType: 'QuickView', layout: 'auto' },
+ ];
+ const { sdk, calls } = mockSdk();
+ await runSdkBuild(spec, { sdk, apply: true });
+ const QUICKVIEW_CLS = '5C5600E0-1D6E-4205-A272-BE80DA87FD42';
+ const qvCall = find(calls, 'addElement').find((c) => c.args[0] === 'form' && (c.args[3] && c.args[3].cells || [])
+ .some((cell) => cell.control && String(cell.control.classId).replace(/[{}]/g, '').toUpperCase() === QUICKVIEW_CLS));
+ assert.ok(qvCall, 'one quick-view control placed');
+ const host = await sdk.getArtifact('form', qvCall.args[1]);
+ const sections = host.tabs[0].columns[0].sections;
+ assert.deepStrictEqual(sections.map((s) => s.name), ['section_grid_new_customer_new_ticket', 'section_general'], 'the premise: the grid section comes first');
+ assert.strictEqual(qvCall.args[2], '/tabs/0/columns/0/sections/1/rows', 'the quick view is added to the field section');
+ assert.strictEqual(sections[0].rows.length, 1, 'the grid section still holds only its grid');
+ assert.ok(sections[1].rows.some((r) => r.cells.some((c) => c.control && c.control.fieldName === 'new_primaryticket')), 'the quick view sits in section_general');
+});
+
test('commands: loose buttons + a flyout with children build to the right shape (one loose group)', async () => {
const spec = makeSpec();
spec.webResources = [{ name: 'new_ticket.js', type: 'js', content: 'x' }];
@@ -3999,6 +4264,115 @@ test('security phase: a REUSED role is STILL added to the solution (idempotent r
assert.strictEqual(find(calls, 'addSolutionComponent').filter((c) => c.args[0].componentType === 20).length, 2, 'both reused roles re-ensured in the solution');
});
+// --- rebuild writes: what a rebuild REUSES joins the solution only when the solution is not proven to hold it ------
+//
+// A reused component is re-added on every run so one that missed its add (or came from a build of a different
+// solution) is repaired. One read of the solution's members (solution-membership.js) lets the build skip the adds
+// that are provably unnecessary; anything the read does not prove present is added exactly as before. The wire-level
+// behaviour is pinned against the real bundle in rebuild-writes-real-bundle.test.js — these pin each reuse site.
+
+const addsOf = (calls, type) => find(calls, 'addSolutionComponent').filter((c) => c.args[0].componentType === type).map((c) => c.args[0].componentId);
+
+test('rebuild writes: a reused role the solution already holds is not added again — one it lacks still is', async () => {
+ const { sdk, calls } = mockSdk({ rolesExist: true, solutionMembers: [[20, 'role-Ticket Agent']] });
+ await runSdkBuild(personaSpec(), { sdk, apply: true });
+ assert.deepStrictEqual(addsOf(calls, 20), ['role-Dispatcher']);
+});
+
+test('rebuild writes: a role the SDK just created is always added — it cannot be a member yet', async () => {
+ const { sdk, calls } = mockSdk({ solutionMembers: [[20, 'role-Ticket Agent'], [20, 'role-Dispatcher']] });
+ await runSdkBuild(personaSpec(), { sdk, apply: true });
+ assert.deepStrictEqual(addsOf(calls, 20).sort(), ['role-Dispatcher', 'role-Ticket Agent']);
+ assert.strictEqual(find(calls, 'queryRecords').filter((c) => c.args[0] === 'solutioncomponent').length, 0, 'nothing reused, so nothing read');
+});
+
+test('rebuild writes: a reused view, chart and form the solution already holds are not added again', async () => {
+ const { sdk, calls } = mockSdk({ artifactsExist: true, solutionMembers: [[26, 'view-existing'], [59, 'chart-existing'], [60, 'form-existing']] });
+ await runSdkBuild(makeSpec(), { sdk, apply: true, phases: ['solution', 'data-model', 'views', 'charts', 'forms'] });
+ assert.deepStrictEqual(find(calls, 'addSolutionComponent'), []);
+ assert.strictEqual(find(calls, 'queryRecords').filter((c) => c.args[0] === 'solutioncomponent').length, 1, 'one membership read for all of them');
+});
+
+test('rebuild writes: a reused view, chart or form the solution lacks is added again, and only that one', async () => {
+ const { sdk, calls } = mockSdk({ artifactsExist: true, solutionMembers: [[26, 'view-existing']] });
+ await runSdkBuild(makeSpec(), { sdk, apply: true, phases: ['solution', 'data-model', 'views', 'charts', 'forms'] });
+ assert.deepStrictEqual(find(calls, 'addSolutionComponent').map((c) => `${c.args[0].componentType}:${c.args[0].componentId}`).sort(), ['59:chart-existing', '60:form-existing']);
+});
+
+// A table the solution holds with ALL its subcomponents (`rootcomponentbehavior` 0) carries its views, charts and forms,
+// which then have no row of their own. The table row's `objectid` is the table's MetadataId, so the build resolves each
+// table through the raw client (the same read the app's table pins use) before it can match one.
+const TICKET_TABLE = '7a1b1c1d-0000-4000-8000-0000000000a1';
+const CUSTOMER_TABLE = '7a1b1c1d-0000-4000-8000-0000000000a2';
+function withTableMetadata(sdk, { fails = false } = {}) {
+ const urls = [];
+ sdk.dataverse = {
+ get: async (url) => {
+ urls.push(url);
+ if (fails) throw new Error('metadata service unavailable');
+ const logical = /LogicalName='([^']+)'/.exec(url)[1];
+ return { status: 200, body: { LogicalName: logical, MetadataId: logical === 'new_ticket' ? TICKET_TABLE : CUSTOMER_TABLE, EntitySetName: `${logical}s` } };
+ },
+ };
+ return urls;
+}
+
+test('rebuild writes: a reused view, chart and form whose tables the solution holds with all their subcomponents are not added again', async () => {
+ const { sdk, calls } = mockSdk({ artifactsExist: true, solutionMembers: [[1, TICKET_TABLE, 0], [1, CUSTOMER_TABLE, 0]] });
+ const urls = withTableMetadata(sdk);
+ await runSdkBuild(makeSpec(), { sdk, apply: true, phases: ['views', 'charts', 'forms'] });
+ assert.deepStrictEqual(find(calls, 'addSolutionComponent'), []);
+ assert.deepStrictEqual(urls.filter((u) => /MetadataId/.test(u)).sort(), [
+ "/EntityDefinitions(LogicalName='new_customer')?$select=MetadataId,EntitySetName",
+ "/EntityDefinitions(LogicalName='new_ticket')?$select=MetadataId,EntitySetName",
+ ], 'each table is resolved once, not once per component');
+ assert.strictEqual(find(calls, 'queryRecords').filter((c) => c.args[0] === 'solutioncomponent').length, 1, 'still one membership read');
+});
+
+test('rebuild writes: a table held in part, another table\'s row, or a table that cannot be resolved vouches for nothing', async () => {
+ // The ticket table is held at 2 (shell only) and the customer table at 0: the view and chart (ticket) are added, the form (customer) is not.
+ const mixed = mockSdk({ artifactsExist: true, solutionMembers: [[1, TICKET_TABLE, 2], [1, CUSTOMER_TABLE, 0]] });
+ withTableMetadata(mixed.sdk);
+ await runSdkBuild(makeSpec(), { sdk: mixed.sdk, apply: true, phases: ['views', 'charts', 'forms'] });
+ assert.deepStrictEqual(find(mixed.calls, 'addSolutionComponent').map((c) => `${c.args[0].componentType}:${c.args[0].componentId}`).sort(), ['26:view-existing', '59:chart-existing']);
+
+ // Both tables whole, but their metadata cannot be read: nothing is proven, everything is added, the build still succeeds.
+ const unreadable = mockSdk({ artifactsExist: true, solutionMembers: [[1, TICKET_TABLE, 0], [1, CUSTOMER_TABLE, 0]] });
+ withTableMetadata(unreadable.sdk, { fails: true });
+ const res = await runSdkBuild(makeSpec(), { sdk: unreadable.sdk, apply: true, phases: ['views', 'charts', 'forms'] });
+ assert.strictEqual(res.ok, true);
+ assert.strictEqual(find(unreadable.calls, 'addSolutionComponent').length, 3, 'view, chart and form are added as before');
+
+ // No raw client at all (a double without one): the same.
+ const bare = mockSdk({ artifactsExist: true, solutionMembers: [[1, TICKET_TABLE, 0], [1, CUSTOMER_TABLE, 0]] });
+ await runSdkBuild(makeSpec(), { sdk: bare.sdk, apply: true, phases: ['views', 'charts', 'forms'] });
+ assert.strictEqual(find(bare.calls, 'addSolutionComponent').length, 3);
+});
+
+test('rebuild writes: an existing app and its sitemap the solution already holds are not added again', async () => {
+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingWebResource: true, solutionMembers: [[26, 'view-existing'], [59, 'chart-existing'], [60, 'form-existing'], [80, 'app-existing'], [62, 'sm-1']] });
+ await runSdkBuild(makeSpec(), { sdk, apply: true, phases: ['solution', 'data-model', 'views', 'charts', 'forms', 'app-shell'] });
+ assert.deepStrictEqual(find(calls, 'addSolutionComponent'), []);
+});
+
+test('rebuild writes: an existing app, or its sitemap, the solution lacks is added again', async () => {
+ const { sdk, calls } = mockSdk({ artifactsExist: true, existingWebResource: true, solutionMembers: [[26, 'view-existing'], [59, 'chart-existing'], [60, 'form-existing'], [62, 'sm-1']] });
+ await runSdkBuild(makeSpec(), { sdk, apply: true, phases: ['solution', 'data-model', 'views', 'charts', 'forms', 'app-shell'] });
+ assert.deepStrictEqual(find(calls, 'addSolutionComponent').map((c) => `${c.args[0].componentType}:${c.args[0].componentId}`), ['80:app-existing']);
+ const missingSitemap = mockSdk({ artifactsExist: true, existingWebResource: true, solutionMembers: [[26, 'view-existing'], [59, 'chart-existing'], [60, 'form-existing'], [80, 'app-existing']] });
+ await runSdkBuild(makeSpec(), { sdk: missingSitemap.sdk, apply: true, phases: ['solution', 'data-model', 'views', 'charts', 'forms', 'app-shell'] });
+ assert.deepStrictEqual(find(missingSitemap.calls, 'addSolutionComponent').map((c) => `${c.args[0].componentType}:${c.args[0].componentId}`), ['62:sm-1']);
+});
+
+test('rebuild writes: a membership read that fails leaves every re-assert in place, and the build still succeeds', async () => {
+ const { sdk, calls } = mockSdk({ artifactsExist: true, solutionMembers: [[26, 'view-existing'], [59, 'chart-existing'], [60, 'form-existing']] });
+ const read = sdk.queryRecords;
+ sdk.queryRecords = async (e, o) => { if (e === 'solutioncomponent') throw new Error('membership unreadable'); return read(e, o); };
+ const res = await runSdkBuild(makeSpec(), { sdk, apply: true, phases: ['solution', 'data-model', 'views', 'charts', 'forms'] });
+ assert.strictEqual(res.ok, true);
+ assert.strictEqual(find(calls, 'addSolutionComponent').length, 3, 'view, chart and form are added as before');
+});
+
test('security phase: a duplicate app<->role association (realistic 400 + 0x80060891) is swallowed', async () => {
const { sdk, calls } = mockSdk({ associateDuplicate: true });
const r = await runSdkBuild(personaSpec(), { sdk, apply: true }); // must NOT throw
@@ -4372,9 +4746,11 @@ const aiRetrySpec = () => makeSpec({ ai: { appFeatures: { nlSearch: true }, summ
const withAiResults = (results) => {
const { sdk, calls } = mockSdk();
let n = 0;
+ // A fresh copy per call, like the SDK's own: the build moves features between a result's buckets, and a result
+ // handed out twice would carry the first call's moves into the second.
sdk.setAppAiFeatures = async (appUnique, flags, opts) => {
calls.push({ name: 'setAppAiFeatures', args: [appUnique, flags, opts] });
- return results[Math.min(n++, results.length - 1)];
+ return clone(results[Math.min(n++, results.length - 1)]);
};
return { sdk, calls };
};
@@ -4698,6 +5074,368 @@ test('ai-features phase: an override holding the WRONG value is not treated as p
assert.ok(events.some((e) => e.phase === 'ai-features' && e.status === 'skip'), 'a wrong-valued override must still warn');
});
+// ── `pendingPublish`: an override the SDK now PROVES while it is still unpublished ──────────────────
+// An app-scope setting write lands in the app's unpublished layer, which the published `appsettings`
+// projection the SDK used to prove against cannot show: on a freshly created app the first write read
+// back `notPersisted`, and the build's post-publish re-issue (fetch, publish, write again) is what
+// put the rows in force. The SDK now proves the row where it is, and reports it `applied` with
+// `pendingPublish: true` — saved, taking effect when the app is published. That is NOT "applied" for the
+// build's purposes unless a publish follows: without `--publish` nothing else publishes the app after
+// this write, and `--verify` reads the published layer.
+const pendingOutcome = (feature) => ({ feature, setting: `S_${feature}`, requestedValue: '2', status: 'applied', appOverrideExists: true, pendingPublish: true });
+const pendingResult = (features) => ({ applied: [...features], skipped: [], notPersisted: [], unverified: [], failed: [], outcomes: features.map(pendingOutcome) });
+const inForceResult = (features) => ({ applied: [...features], skipped: [], notPersisted: [], unverified: [], failed: [], outcomes: features.map((feature) => ({ feature, status: 'applied', appOverrideExists: true })) });
+const withOverrideRow = (sdk, rows) => {
+ sdk.queryRecords = async (set) => {
+ if (set === 'appmodule') return [{ appmoduleid: 'APPID' }];
+ if (set === 'settingdefinition') return [{ settingdefinitionid: 'DEFID' }];
+ if (set === 'appsetting') return rows;
+ return [];
+ };
+};
+
+// What the app's publish answers, in order (the last answer repeats). The SDK reports a publish that did not succeed
+// BY VALUE — `failed` and `unverifiable` RESOLVE, they do not throw — so that is what these hand back. Only the
+// app's publish is scripted: every other target publishes cleanly.
+const failedPublish = () => ({ kind: 'failed', error: new Error('PublishXml was refused') });
+const unverifiablePublish = () => ({ kind: 'unverifiable', reason: 'the published copy could not be read back' });
+const verifiedPublish = () => ({ kind: 'verified' });
+const withAppPublishes = (sdk, calls, answers) => {
+ let n = 0;
+ sdk.publishArtifact = async (type, id) => {
+ calls.push({ name: 'publishArtifact', args: [type, id] });
+ const publish = type === 'app' ? answers[Math.min(n++, answers.length - 1)]() : verifiedPublish();
+ return { type, id, shipped: publish.kind === 'verified', publish };
+ };
+};
+const notPersistedResult = (features) => ({ applied: [], skipped: [], notPersisted: [...features], unverified: [], failed: [], outcomes: features.map((feature) => ({ feature, status: 'notPersisted', appOverrideExists: false, reason: 'no override observed' })) });
+const aiWarnings = (events) => events.filter((e) => e.phase === 'ai-features' && e.status === 'skip').map((e) => e.label);
+const appPublishCalls = (calls) => find(calls, 'publishArtifact').filter((c) => c.args[0] === 'app');
+const aiOutcome = (r, feature) => r.created.ai.appFeatures.outcomes.find((o) => o.feature === feature);
+
+test('ai-features phase: a feature saved but not yet published is published once and PROVED — not written again', async () => {
+ // Its row is already in the app's unpublished layer, so a second write would only save it again: the publish is what
+ // puts it in force, and the proof reads the row where the runtime does.
+ const { sdk, calls } = withAiResults([pendingResult(['formFill'])]);
+ withOverrideRow(sdk, [{ value: '2' }]); // in force once the app is published
+ const events = [];
+ const r = await runSdkBuild(aiProblemSpec(), { sdk, apply: true, phases: ['app-shell', 'ai-features'], emit: (e) => events.push(e) });
+
+ assert.strictEqual(find(calls, 'setAppAiFeatures').length, 1, 'no second write');
+ const firstWrite = calls.findIndex((c) => c.name === 'setAppAiFeatures');
+ const fetchIdx = calls.findIndex((c, i) => i > firstWrite && c.name === 'fetchArtifact' && c.args[0] === 'app');
+ const pubIdx = calls.findIndex((c, i) => i > firstWrite && c.name === 'publishArtifact' && c.args[0] === 'app');
+ assert.ok(fetchIdx > firstWrite && pubIdx > fetchIdx, 'without --publish nothing else publishes the app, so it is fetched and published after the write');
+ assert.strictEqual(appPublishCalls(calls).length, 1);
+
+ const af = r.created.ai.appFeatures;
+ assert.deepStrictEqual(af.applied, ['formFill'], 'reported once, not twice');
+ assert.ok(!(af.pendingPublish || []).length, 'the bucket is emptied once the feature is in force');
+ const outcome = aiOutcome(r, 'formFill');
+ assert.strictEqual(outcome.status, 'applied');
+ assert.strictEqual(outcome.pendingPublish, undefined, 'no longer pending');
+ assert.match(outcome.reason, /override-row proof/, 'what was claimed is what was proved, not a write that never happened');
+ assert.strictEqual(aiWarnings(events).length, 0, 'a recovered feature is not reported as a problem');
+});
+
+test('ai-features phase: when the publish that should put a saved override in force FAILS, it is NOT YET PUBLISHED — never applied', async () => {
+ const { sdk, calls } = withAiResults([pendingResult(['formFill'])]);
+ withOverrideRow(sdk, []); // the published layer holds nothing: the publish did not happen
+ withAppPublishes(sdk, calls, [failedPublish]);
+ const events = [];
+ const warnings = [];
+ const r = await runSdkBuild(aiProblemSpec(), { sdk, apply: true, phases: ['app-shell', 'ai-features'], emit: (e) => events.push(e), warn: (w) => warnings.push(w) });
+
+ assert.ok(aiWarnings(events).some((l) => /NOT YET PUBLISHED: formFill/.test(l)), JSON.stringify(aiWarnings(events)));
+ assert.ok(warnings.some((w) => /publish app .*FAILED: PublishXml was refused/.test(w)), `the failed publish is reported too: ${JSON.stringify(warnings)}`);
+ assert.strictEqual(find(calls, 'setAppAiFeatures').length, 1, 'a second write could not put it in force either');
+ const af = r.created.ai.appFeatures;
+ assert.ok(!af.applied.includes('formFill'), 'nothing is in force, so nothing is claimed');
+ assert.deepStrictEqual(af.pendingPublish, ['formFill'], 'and a --json consumer sees it as what it is');
+ assert.strictEqual(aiOutcome(r, 'formFill').status, 'pendingPublish');
+});
+
+for (const [label, answer] of [['UNVERIFIABLE', unverifiablePublish], ['verified', verifiedPublish]]) {
+ test(`ai-features phase: after a ${label} publish, what is claimed is what the override-row proof reads`, async () => {
+ // `unverifiable` means PublishXml answered 2xx and only the SDK's own read-back was not possible, so the proof —
+ // the same read --verify makes — decides, in both directions.
+ for (const [rows, applied] of [[[{ value: '2' }], true], [[], false]]) {
+ const { sdk, calls } = withAiResults([pendingResult(['formFill'])]);
+ withOverrideRow(sdk, rows);
+ withAppPublishes(sdk, calls, [answer]);
+ const events = [];
+ const r = await runSdkBuild(aiProblemSpec(), { sdk, apply: true, phases: ['app-shell', 'ai-features'], emit: (e) => events.push(e) });
+ assert.strictEqual(r.created.ai.appFeatures.applied.includes('formFill'), applied, `${label}, ${rows.length ? 'row present' : 'row absent'}`);
+ assert.strictEqual(aiWarnings(events).some((l) => /NOT YET PUBLISHED: formFill/.test(l)), !applied);
+ assert.strictEqual(find(calls, 'setAppAiFeatures').length, 1);
+ }
+ });
+}
+
+for (const [label, answer] of [['FAILED', failedPublish], ['UNVERIFIABLE', unverifiablePublish]]) {
+ test(`ai-features phase: a re-issue that only reaches the unpublished layer after a ${label} publish is NOT YET PUBLISHED, never applied`, async () => {
+ // The first write saved nothing, so it IS written again after the publish. When that publish did not put the app in
+ // force the SDK proves the row where the write put it — the unpublished layer — and answers `applied` with
+ // `pendingPublish`. Counting that `applied` reported a feature nothing serves.
+ const { sdk, calls } = withAiResults([notPersistedResult(['formFill']), pendingResult(['formFill'])]);
+ withOverrideRow(sdk, []);
+ withAppPublishes(sdk, calls, [answer]);
+ const events = [];
+ const r = await runSdkBuild(aiProblemSpec(), { sdk, apply: true, phases: ['app-shell', 'ai-features'], emit: (e) => events.push(e) });
+
+ assert.strictEqual(find(calls, 'setAppAiFeatures').length, 2, 'it was not saved at first, so it is written again after the publish');
+ assert.ok(aiWarnings(events).some((l) => /NOT YET PUBLISHED: formFill/.test(l)), JSON.stringify(aiWarnings(events)));
+ assert.ok(!aiWarnings(events).some((l) => /NOT PERSISTED/.test(l)), 'the first write\u2019s verdict is superseded: the row IS saved');
+ const af = r.created.ai.appFeatures;
+ assert.deepStrictEqual(af.applied, [], 'nothing is in force');
+ assert.deepStrictEqual([af.pendingPublish, af.notPersisted], [['formFill'], []], 'the --json result agrees with the report');
+ assert.strictEqual(aiOutcome(r, 'formFill').status, 'pendingPublish');
+ });
+}
+
+test('ai-features phase: a re-issue the SDK proves in force is applied, whatever the publish before it answered', async () => {
+ const { sdk, calls } = withAiResults([notPersistedResult(['formFill']), inForceResult(['formFill'])]);
+ withAppPublishes(sdk, calls, [unverifiablePublish]);
+ const events = [];
+ const r = await runSdkBuild(aiProblemSpec(), { sdk, apply: true, phases: ['app-shell', 'ai-features'], emit: (e) => events.push(e) });
+ assert.deepStrictEqual(r.created.ai.appFeatures.applied, ['formFill']);
+ assert.strictEqual(aiWarnings(events).length, 0);
+});
+
+for (const [label, answer] of [['FAILED', failedPublish], ['UNVERIFIABLE', unverifiablePublish]]) {
+ test(`ai-features phase: with --publish, a re-issue that only reaches the unpublished layer after a ${label} post-publish publish is NOT YET PUBLISHED`, async () => {
+ // The publish phase published the app (its answer is the first), but the feature was not saved by the first write, so
+ // the post-publish pass publishes once more (its answer is the second) and writes it again.
+ const { sdk, calls } = withAiResults([notPersistedResult(['formFill']), pendingResult(['formFill'])]);
+ withOverrideRow(sdk, []);
+ withAppPublishes(sdk, calls, [verifiedPublish, answer]);
+ const events = [];
+ const r = await runSdkBuild(aiProblemSpec(), { sdk, apply: true, publish: true, phases: ['app-shell', 'ai-features', 'publish'], emit: (e) => events.push(e) });
+ assert.strictEqual(appPublishCalls(calls).length, 2);
+ assert.strictEqual(find(calls, 'setAppAiFeatures').length, 2);
+ assert.ok(aiWarnings(events).some((l) => /NOT YET PUBLISHED: formFill/.test(l)), JSON.stringify(aiWarnings(events)));
+ assert.deepStrictEqual([r.created.ai.appFeatures.applied, r.created.ai.appFeatures.pendingPublish], [[], ['formFill']]);
+ });
+}
+
+test('ai-features phase: when the build\u2019s own publish follows, a saved-but-unpublished feature is only CONFIRMED — no second publish, no second write', async () => {
+ // The publish phase publishes the app in its one envelope, which carries the saved override. Re-issuing the
+ // write after it (a fetch, another PublishXml and a second write with its own proof) would pay again for
+ // what is already in force.
+ const { sdk, calls } = withAiResults([pendingResult(['formFill'])]);
+ withOverrideRow(sdk, [{ value: '2' }]); // in force once published, holding ENABLED for this family
+ const events = [];
+ const r = await runSdkBuild(aiProblemSpec(), { sdk, apply: true, publish: true, phases: ['app-shell', 'ai-features', 'publish'], emit: (e) => events.push(e) });
+
+ assert.strictEqual(find(calls, 'setAppAiFeatures').length, 1, 'no re-issue: the publish phase already put the row in force');
+ const appPublishes = find(calls, 'publishArtifact').filter((c) => c.args[0] === 'app');
+ assert.strictEqual(appPublishes.length, 1, 'the app is published once, by the publish phase');
+ const firstWrite = calls.findIndex((c) => c.name === 'setAppAiFeatures');
+ assert.ok(!calls.some((c, i) => i > firstWrite && c.name === 'fetchArtifact' && c.args[0] === 'app'), 'and not re-fetched for a retry');
+
+ const af = r.created.ai.appFeatures;
+ assert.deepStrictEqual(af.applied, ['formFill']);
+ const outcome = af.outcomes.find((o) => o.feature === 'formFill');
+ assert.strictEqual(outcome.status, 'applied');
+ assert.strictEqual(outcome.pendingPublish, undefined);
+ assert.match(outcome.reason, /override-row proof/, 'the claim is the proof it is: the row was read where the runtime reads it');
+ assert.strictEqual(events.filter((e) => e.phase === 'ai-features' && e.status === 'skip').length, 0);
+});
+
+test('ai-features phase: after the publish the override is read back, and one still not visible is reported, not claimed', async () => {
+ const { sdk } = withAiResults([pendingResult(['formFill'])]);
+ withOverrideRow(sdk, []); // the publish did not carry it
+ const events = [];
+ const r = await runSdkBuild(aiProblemSpec(), { sdk, apply: true, publish: true, phases: ['app-shell', 'ai-features', 'publish'], emit: (e) => events.push(e) });
+ const warnings = events.filter((e) => e.phase === 'ai-features' && e.status === 'skip').map((e) => e.label);
+ assert.ok(warnings.some((l) => /NOT YET PUBLISHED: formFill/.test(l)), JSON.stringify(warnings));
+ const af = r.created.ai.appFeatures;
+ assert.ok(!af.applied.includes('formFill'), 'not claimed as in force');
+ assert.deepStrictEqual(af.pendingPublish, ['formFill'], 'and visible to a --json consumer as what it is');
+});
+
+// ── the proof after a publish: the budget --verify has, and a read that failed said plainly ─────────────────────────
+// A publish can answer before the published `appsettings` row is readable. `--verify` reads the row three times, 500 ms
+// apart, to ride that out; the build's proof after its publish read once, so a row that appeared a moment late was reported
+// NOT YET PUBLISHED (and left out of `applied`) by a run whose own --verify passed.
+
+// An override row that becomes readable on the `visibleOn`th read of it (never, when omitted); `reads.count` is how often it was read.
+const withLateOverrideRow = (sdk, reads, visibleOn = Infinity) => {
+ sdk.queryRecords = async (set) => {
+ if (set === 'appmodule') return [{ appmoduleid: 'APPID' }];
+ if (set === 'settingdefinition') return [{ settingdefinitionid: 'DEFID' }];
+ if (set === 'appsetting') { reads.count += 1; return reads.count >= visibleOn ? [{ value: '2' }] : []; }
+ return [];
+ };
+};
+
+for (const withPublishPhase of [false, true]) {
+ test(`ai-features phase: a published row that appears a moment after the publish is found by the proof, not reported NOT YET PUBLISHED (${withPublishPhase ? 'with' : 'without'} --publish)`, async () => {
+ const { sdk, calls } = withAiResults([pendingResult(['formFill'])]);
+ const reads = { count: 0 };
+ withLateOverrideRow(sdk, reads, 3); // readable on the third read
+ const events = [];
+ const r = await runSdkBuild(aiProblemSpec(), {
+ sdk, apply: true, publish: withPublishPhase,
+ phases: ['app-shell', 'ai-features', ...(withPublishPhase ? ['publish'] : [])],
+ emit: (e) => events.push(e),
+ });
+ assert.strictEqual(reads.count, 3, 'it read until the row was there, and no longer');
+ assert.strictEqual(find(calls, 'setAppAiFeatures').length, 1, 'no second write: the row was saved all along');
+ assert.deepStrictEqual(r.created.ai.appFeatures.applied, ['formFill']);
+ assert.strictEqual(aiWarnings(events).length, 0, JSON.stringify(aiWarnings(events)));
+ assert.match(aiOutcome(r, 'formFill').reason, /override-row proof/);
+ });
+}
+
+test('ai-features phase: a row still absent after the same three reads --verify makes is reported NOT YET PUBLISHED, not claimed', async () => {
+ const { sdk } = withAiResults([pendingResult(['formFill'])]);
+ const reads = { count: 0 };
+ withLateOverrideRow(sdk, reads); // never readable
+ const events = [];
+ const r = await runSdkBuild(aiProblemSpec(), { sdk, apply: true, phases: ['app-shell', 'ai-features'], emit: (e) => events.push(e) });
+ assert.strictEqual(reads.count, 3, 'three reads: the budget --verify has');
+ assert.ok(aiWarnings(events).some((l) => /NOT YET PUBLISHED: formFill/.test(l)), JSON.stringify(aiWarnings(events)));
+ assert.ok(!aiWarnings(events).some((l) => /could not run/.test(l)), 'the check ran and found nothing: it is not reported as unable to run');
+ assert.deepStrictEqual(r.created.ai.appFeatures.pendingPublish, ['formFill']);
+ assert.ok(!r.created.ai.appFeatures.applied.includes('formFill'));
+});
+
+test('the override proof budget is one value for the build and --verify, with the one pair of test seams both take', () => {
+ const { AI_PROOF_BUDGET, proofBudget } = require('../lib/ai-app-settings.js');
+ assert.deepStrictEqual({ ...AI_PROOF_BUDGET }, { attempts: 3, delayMs: 500 });
+ assert.ok(Object.isFrozen(AI_PROOF_BUDGET), 'neither caller can change what the other waits for');
+ assert.deepStrictEqual(proofBudget(), { attempts: 3, delayMs: 500 });
+ assert.deepStrictEqual(proofBudget({}), { attempts: 3, delayMs: 500 });
+ assert.deepStrictEqual(proofBudget({ proofAttempts: 1, proofDelayMs: 0 }), { attempts: 1, delayMs: 0 });
+ assert.deepStrictEqual(proofBudget({ proofAttempts: 5 }), { attempts: 5, delayMs: 500 });
+});
+
+// A check that could not run leaves the verdict from before it standing. The warning has to say it did not look: a reader who sees
+// only that verdict takes the check for having found nothing.
+const READ_FAILURES = [
+ ['the override row cannot be read', (set) => { if (set === 'appsetting') throw new Error('429 Too Many Requests'); }, 'the app-scope override row could not be read: 429 Too Many Requests'],
+ ['the app module cannot be read', (set) => { if (set === 'appmodule') throw new Error('503 Service Unavailable'); }, 'the app module could not be read: 503 Service Unavailable'],
+ ['the setting definition cannot be read', (set) => { if (set === 'settingdefinition') throw new Error('403 Forbidden'); }, 'the setting definition could not be read: 403 Forbidden'],
+];
+for (const [what, fail, readError] of READ_FAILURES) {
+ test(`ai-features phase: when ${what}, the warning says the check could not run — ahead of what the SDK said`, async () => {
+ const sdkSaid = 'no override observed for FormFillBarUXEnabled';
+ const { sdk } = withAiResults([{ applied: [], skipped: [], notPersisted: ['formFill'], unverified: [], failed: [], outcomes: [{ feature: 'formFill', status: 'notPersisted', reason: sdkSaid }] }]);
+ sdk.queryRecords = async (set) => {
+ fail(set);
+ if (set === 'appmodule') return [{ appmoduleid: 'APPID' }];
+ if (set === 'settingdefinition') return [{ settingdefinitionid: 'DEFID' }];
+ return [];
+ };
+ const events = [];
+ await runSdkBuild(aiProblemSpec(), { sdk, apply: true, phases: ['app-shell', 'ai-features'], emit: (e) => events.push(e) });
+ const [warning] = aiWarnings(events);
+ assert.match(warning, /^NOT PERSISTED: formFill \u2014 /, 'the verdict that stands is the first write\u2019s');
+ const couldNotRun = warning.indexOf(`the check after the publish could not run: ${readError}`);
+ assert.ok(couldNotRun > 0, warning);
+ assert.ok(warning.indexOf(sdkSaid) > couldNotRun, `what the SDK said comes after it, and is not lost: ${warning}`);
+ });
+}
+
+test('ai-features phase: the same holds for a feature the re-issue saved but could not put in force', async () => {
+ // The reason that rides along is the one the build files a saved-but-unpublished override under.
+ const { sdk, calls } = withAiResults([notPersistedResult(['formFill']), pendingResult(['formFill'])]);
+ withAppPublishes(sdk, calls, [failedPublish]);
+ sdk.queryRecords = async (set) => {
+ if (set === 'appmodule') return [{ appmoduleid: 'APPID' }];
+ if (set === 'settingdefinition') return [{ settingdefinitionid: 'DEFID' }];
+ if (set === 'appsetting') throw new Error('429 Too Many Requests'); // the override row cannot be read
+ return [];
+ };
+ const events = [];
+ await runSdkBuild(aiProblemSpec(), { sdk, apply: true, phases: ['app-shell', 'ai-features'], emit: (e) => events.push(e) });
+ const [warning] = aiWarnings(events);
+ assert.match(warning, /^NOT YET PUBLISHED: formFill \u2014 the check after the publish could not run: the app-scope override row could not be read: 429 Too Many Requests \u2014 saved in the app's unpublished layer/, warning);
+});
+
+test('ai-features phase: a publish phase whose app publish FAILED does not count — the app is published again and the override proved, with no second write', async () => {
+ const { sdk, calls } = withAiResults([pendingResult(['formFill'])]);
+ withOverrideRow(sdk, [{ value: '2' }]);
+ withAppPublishes(sdk, calls, [failedPublish, verifiedPublish]);
+ const events = [];
+ const r = await runSdkBuild(aiProblemSpec(), { sdk, apply: true, publish: true, phases: ['app-shell', 'ai-features', 'publish'], emit: (e) => events.push(e) });
+ assert.strictEqual(appPublishCalls(calls).length, 2, 'an unpublished app has not put the override in force, so it is published once more');
+ assert.strictEqual(find(calls, 'setAppAiFeatures').length, 1, 'the override was saved by the first write; publishing is all it needed');
+ assert.deepStrictEqual(r.created.ai.appFeatures.applied, ['formFill']);
+ assert.strictEqual(aiWarnings(events).length, 0);
+});
+
+test('ai-features phase: with --publish, an app publish that FAILS twice leaves the saved override NOT YET PUBLISHED', async () => {
+ const { sdk, calls } = withAiResults([pendingResult(['formFill'])]);
+ withOverrideRow(sdk, []);
+ withAppPublishes(sdk, calls, [failedPublish]); // the publish phase's and the post-publish pass's, alike
+ const events = [];
+ const r = await runSdkBuild(aiProblemSpec(), { sdk, apply: true, publish: true, phases: ['app-shell', 'ai-features', 'publish'], emit: (e) => events.push(e) });
+ assert.strictEqual(appPublishCalls(calls).length, 2);
+ assert.ok(aiWarnings(events).some((l) => /NOT YET PUBLISHED: formFill/.test(l)), JSON.stringify(aiWarnings(events)));
+ assert.ok(!r.created.ai.appFeatures.applied.includes('formFill'));
+ assert.deepStrictEqual(r.created.ai.appFeatures.pendingPublish, ['formFill']);
+});
+
+test('ai-features phase: with --publish, an UNVERIFIABLE app publish counts as published: the override is only proved, in either direction', async () => {
+ // PublishXml answered 2xx; only the SDK's read-back was not possible. A second publish would add nothing, and the
+ // proof — which reads the row where the runtime does — settles the verdict.
+ for (const [rows, applied] of [[[{ value: '2' }], true], [[], false]]) {
+ const { sdk, calls } = withAiResults([pendingResult(['formFill'])]);
+ withOverrideRow(sdk, rows);
+ withAppPublishes(sdk, calls, [unverifiablePublish]);
+ const events = [];
+ const r = await runSdkBuild(aiProblemSpec(), { sdk, apply: true, publish: true, phases: ['app-shell', 'ai-features', 'publish'], emit: (e) => events.push(e) });
+ assert.strictEqual(appPublishCalls(calls).length, 1, 'published once, by the publish phase');
+ assert.strictEqual(find(calls, 'setAppAiFeatures').length, 1);
+ assert.strictEqual(r.created.ai.appFeatures.applied.includes('formFill'), applied, rows.length ? 'row present' : 'row absent');
+ assert.strictEqual(aiWarnings(events).some((l) => /NOT YET PUBLISHED: formFill/.test(l)), !applied);
+ }
+});
+
+test('ai-features phase: features that need a write and features that need only the publish share one fetch and one publish', async () => {
+ const spec = makeSpec({ ai: { appFeatures: { formFill: true, nlSearch: true }, summaries: { default: 'off' } } });
+ const first = {
+ applied: ['formFill'], skipped: [], notPersisted: ['nlSearch'], unverified: [], failed: [],
+ outcomes: [pendingOutcome('formFill'), { feature: 'nlSearch', status: 'notPersisted', reason: 'no override observed' }],
+ };
+ const { sdk, calls } = withAiResults([first, inForceResult(['nlSearch'])]);
+ withOverrideRow(sdk, [{ value: '2' }]); // formFill's saved row, in force once published
+ const events = [];
+ const r = await runSdkBuild(spec, { sdk, apply: true, phases: ['app-shell', 'ai-features'], emit: (e) => events.push(e) });
+ const writes = find(calls, 'setAppAiFeatures');
+ assert.strictEqual(writes.length, 2);
+ assert.deepStrictEqual(Object.keys(writes[1].args[1]), ['nlSearch'], 'only the feature that was not saved is written again');
+ const firstWrite = calls.findIndex((c) => c.name === 'setAppAiFeatures');
+ assert.strictEqual(calls.filter((c, i) => i > firstWrite && c.name === 'fetchArtifact' && c.args[0] === 'app').length, 1);
+ assert.strictEqual(appPublishCalls(calls).length, 1, 'one publish serves both');
+ assert.deepStrictEqual([...r.created.ai.appFeatures.applied].sort(), ['formFill', 'nlSearch']);
+ assert.strictEqual(aiWarnings(events).length, 0);
+});
+
+test('ai-features phase: a feature already in force is applied at once, and only the pending one waits for the publish', async () => {
+ const spec = makeSpec({ ai: { appFeatures: { formFill: true, nlSearch: true }, summaries: { default: 'off' } } });
+ const mixed = { applied: ['formFill', 'nlSearch'], skipped: [], notPersisted: [], unverified: [], failed: [], outcomes: [
+ { feature: 'formFill', status: 'applied', appOverrideExists: true },
+ pendingOutcome('nlSearch'),
+ ] };
+ const { sdk, calls } = withAiResults([mixed]);
+ withOverrideRow(sdk, [{ value: '2' }]);
+ const r = await runSdkBuild(spec, { sdk, apply: true, phases: ['app-shell', 'ai-features'] });
+ assert.strictEqual(find(calls, 'setAppAiFeatures').length, 1, 'nothing is written twice');
+ assert.strictEqual(appPublishCalls(calls).length, 1);
+ assert.deepStrictEqual([...r.created.ai.appFeatures.applied].sort(), ['formFill', 'nlSearch']);
+});
+
+test('ai-features phase: an SDK result with no pending outcome is handled exactly as before', async () => {
+ const { sdk, calls } = withAiResults([inForceResult(['formFill'])]);
+ const r = await runSdkBuild(aiProblemSpec(), { sdk, apply: true, phases: ['app-shell', 'ai-features'] });
+ assert.strictEqual(find(calls, 'setAppAiFeatures').length, 1, 'an override already in force needs no second write');
+ assert.strictEqual(find(calls, 'publishArtifact').length, 0, 'and no publish');
+ assert.deepStrictEqual(r.created.ai.appFeatures.applied, ['formFill']);
+});
+
test('ai-features planFor: spec.ai adds enable + per-table summary plan entries', () => {
const spec = makeSpec({ ai: { appFeatures: { formFill: true }, summaries: { default: 'auto' } } });
const items = planFor(spec, { phases: ['ai-features'] });
@@ -4835,6 +5573,40 @@ test('pages phase updates the manifest IN PLACE on a rebuild whose page ids chan
} finally { fs.rmSync(appDir, { recursive: true, force: true }); }
});
+test('rebuild writes: a rebuild whose manifest the solution already holds updates it in place and does not add it again', async () => {
+ const spec = makeSpec();
+ spec.schemaVersion = 2;
+ spec.pages = [{ key: 'overview', name: 'Overview', source: { kind: 'tsx', codeFile: 'o.tsx' } }, { key: 'detail', name: 'Detail', source: { kind: 'tsx', codeFile: 'd.tsx' } }];
+ const appUnique = appUniqueName(spec);
+ const appDir = stagePages(spec.pages);
+ try {
+ const OV = 'a11c9d20-0000-4000-8000-0000000000a1';
+ const existing = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: OV }] }), 'utf8').toString('base64');
+ const sm = `<SiteMap><Area><Group><SubArea GenPageId="${OV}"/></Group></Area></SiteMap>`;
+ const { sdk, calls } = mockSdk({ pageManifest: existing, manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: sm, existingWebResource: true, solutionMembers: [[61, 'wr-manifest']] });
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [OV], pages: [{ pageId: OV, name: 'Overview' }] }), upload: async (o) => ({ pageId: o.pageId || 'a22c9d20-0000-4000-8000-0000000000d2' }) };
+ await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'] });
+ assert.ok(find(calls, 'updateWebResource').some((c) => c.args[0] === 'wr-manifest'), 'the manifest content is still written');
+ assert.deepStrictEqual(addsOf(calls, 61), [], 'it is already a member');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+test('rebuild writes: a multi-page first build adds the manifest to the solution once, not once per page', async () => {
+ const spec = makeSpec();
+ spec.pages = [{ name: 'Overview', codeFile: 'o.tsx' }, { name: 'Detail', codeFile: 'd.tsx' }];
+ const appDir = stagePages(spec.pages);
+ try {
+ const { sdk, calls } = mockSdk({ existingWebResource: true, solutionMembers: [] });
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [], pages: [] }), upload: async (o) => ({ pageId: o.name === 'Detail' ? 'gp-d' : 'gp-o' }) };
+ await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'] });
+ assert.strictEqual(find(calls, 'updateWebResource').length, 1, 'the manifest is still persisted after every create');
+ assert.strictEqual(addsOf(calls, 61).length, 1, 'but the add the first persist made is not repeated');
+ // The manifest is the one component a first build asks about — it is persisted through the membership check even
+ // when it was just created — so a build that deploys pages makes the read, once, and still adds what is missing.
+ assert.strictEqual(find(calls, 'queryRecords').filter((c) => c.args[0] === 'solutioncomponent').length, 1, 'one membership read, shared by every persist');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
test('pages phase HALTS fail-closed when EXISTENCE enumeration fails — never treats it as empty, uploads nothing', async () => {
const spec = makeSpec();
spec.pages = [{ name: 'Overview', codeFile: 'o.tsx' }];
@@ -5104,6 +5876,343 @@ test('pages: a page shared across TWO app sitemaps HALTS pages-shared-across-app
} finally { fs.rmSync(appDir, { recursive: true, force: true }); }
});
+// The shared-page scan is a snapshot: another maker can take a page into another app's navigation while the build runs. So the build scans
+// again right before the first page is written in place, and once more after the last. A page that became shared while a navigation target
+// was being created halts the build there, before any page is updated in place.
+const overviewToDetailSpec = () => {
+ const spec = overviewSpec();
+ spec.pages[0].navigatesTo = [{ targetKey: 'detail' }];
+ spec.pages.push({ key: 'detail', name: 'Detail', source: { kind: 'tsx', codeFile: 'd.tsx' } });
+ spec.appShell.areas[0].groups[0].subAreas.push({ page: 'detail', title: 'Detail' });
+ return spec;
+};
+const NAV_TO_DETAIL = 'export function go(){ Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_detail" }); }\nexport default function P(){ return null; }';
+
+test('pages: a page another app takes in while a navigation target is created HALTS before any page it began with is updated in place', async () => {
+ const spec = overviewToDetailSpec();
+ const appUnique = appUniqueName(spec);
+ const appDir = stagePages(spec.pages, { 'o.tsx': NAV_TO_DETAIL });
+ try {
+ const existing = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: GP_O }] }), 'utf8').toString('base64');
+ const sitemapWithO = `<SiteMap><Area><Group><SubArea GenPageId="${GP_O}" Title="Overview"/></Group></Area></SiteMap>`;
+ const other = { uniquename: 'contoso_secondapp', sitemapxml: '<SiteMap><Area><Group/></Area></SiteMap>' };
+ const { sdk } = mockSdk({ pageManifest: existing, manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: sitemapWithO, otherApps: [other] });
+ const uploads = [];
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [GP_O], pages: [{ pageId: GP_O, name: 'Overview' }] }),
+ upload: async (o) => {
+ uploads.push([o.name, o.pageId]);
+ // While Detail is created, another maker saves Overview into contoso_secondapp's navigation.
+ if (!o.pageId) other.savedSitemapXml = sitemapWithO;
+ return { pageId: o.pageId || GP_D };
+ } };
+ await assert.rejects(
+ runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'] }),
+ (e) => {
+ assert.strictEqual(e.phase, 'pages');
+ assert.strictEqual(e.code, 'pages-shared-across-apps');
+ assert.match(e.message, /^generative page\(s\) became shared across apps while this build ran: /, 'raised ahead of the page step, so the runner does not wrap it');
+ assert.match(e.message, new RegExp(`${GP_O} \\(also in contoso_secondapp \\[saved, not published\\]\\)`));
+ assert.match(e.message, /no page this build began with has been updated in place/);
+ assert.strictEqual(require('../build-model-app.js').isTransientHalt(e), false, 'another app still holds the page, so a re-run of the halt would only halt again');
+ // Marked outright, not left to the text: the message quotes other apps' names, and no transient pattern may ever make the build re-run it.
+ assert.strictEqual(e.transient, false, 'the halt carries transient: false itself');
+ return true;
+ });
+ assert.deepStrictEqual(uploads, [['Detail', undefined]], 'Detail was created; Overview was never written in place');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// What lands while the pages upload cannot be refused: the page is written by then, and no write can be made conditional on another app's
+// navigation. So the scan after the last upload REPORTS it, naming the page and the app that now shows the new content.
+test('pages: a page another app takes in while the pages upload is REPORTED after the uploads, naming the page and the app', async () => {
+ const spec = overviewSpec();
+ spec.pages.push({ key: 'detail', name: 'Detail', source: { kind: 'tsx', codeFile: 'd.tsx' } });
+ spec.appShell.areas[0].groups[0].subAreas.push({ page: 'detail', title: 'Detail' });
+ const appUnique = appUniqueName(spec);
+ const appDir = stagePages(spec.pages);
+ try {
+ const existing = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: GP_O }, { key: 'detail', name: 'Detail', pageId: GP_D }] }), 'utf8').toString('base64');
+ const both = `<SiteMap><Area><Group><SubArea GenPageId="${GP_O}" Title="Overview"/><SubArea GenPageId="${GP_D}" Title="Detail"/></Group></Area></SiteMap>`;
+ const other = { uniquename: 'contoso_secondapp', sitemapxml: '<SiteMap><Area><Group/></Area></SiteMap>' };
+ const { sdk } = mockSdk({ pageManifest: existing, manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: both, otherApps: [other] });
+ const uploads = [];
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [GP_O, GP_D], pages: [{ pageId: GP_O, name: 'Overview' }, { pageId: GP_D, name: 'Detail' }] }),
+ upload: async (o) => {
+ uploads.push([o.name, o.pageId]);
+ // While Overview uploads, another maker saves Detail into contoso_secondapp's navigation: Detail is next, past the last check before a write.
+ if (o.pageId === GP_O) other.savedSitemapXml = `<SiteMap><Area><Group><SubArea GenPageId="${GP_D}" Title="Detail"/></Group></Area></SiteMap>`;
+ return { pageId: o.pageId };
+ } };
+ const warnings = [];
+ await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'], warn: (m) => warnings.push(String(m)) });
+ assert.deepStrictEqual(uploads, [['Overview', GP_O], ['Detail', GP_D]], 'both pages were written in place');
+ const reported = warnings.filter((w) => /was taken into another app's navigation while this build was updating it/.test(w));
+ assert.strictEqual(reported.length, 1, `one report: ${JSON.stringify(warnings)}`);
+ assert.match(reported[0], new RegExp(`^generative page "Detail" ${GP_D} \\(also in contoso_secondapp \\[saved, not published\\]\\) was taken into another app's navigation`));
+ assert.match(reported[0], /so its new content will show there once that app is published\./, 'an app that only SAVED the page shows it once published');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// The pages are written by the time of the last scan, so a scan that fails there is reported rather than halting the build.
+test('pages: a failed scan after the uploads is REPORTED, and the build completes', async () => {
+ const spec = overviewSpec();
+ const appUnique = appUniqueName(spec);
+ const appDir = stagePages(spec.pages);
+ try {
+ const existing = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: GP_O }] }), 'utf8').toString('base64');
+ const sitemapWithO = `<SiteMap><Area><Group><SubArea GenPageId="${GP_O}" Title="Overview"/></Group></Area></SiteMap>`;
+ const options = { pageManifest: existing, manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: sitemapWithO, otherApps: [{ uniquename: 'contoso_secondapp', sitemapxml: '<SiteMap/>' }] };
+ const { sdk } = mockSdk(options);
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [GP_O], pages: [{ pageId: GP_O, name: 'Overview' }] }),
+ upload: async (o) => { options.failAppList = true; return { pageId: o.pageId }; } };
+ const warnings = [];
+ const result = await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'], warn: (m) => warnings.push(String(m)) });
+ assert.ok(result, 'the build completes');
+ const said = warnings.filter((w) => /^could not check again, once they were written, that the 1 page\(s\) this build updated in place are not shared with another app: /.test(w));
+ assert.strictEqual(said.length, 1, JSON.stringify(warnings));
+ assert.doesNotMatch(said[0], /refusing to UPDATE|Re-run to retry|then rebuild/, 'the pages are written: no halt advice in the report');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+const pagesSitemap = (...ids) => `<SiteMap><Area><Group>${ids.map((id) => `<SubArea GenPageId="${id}" Title="x"/>`).join('')}</Group></Area></SiteMap>`;
+const pagesManifest = (pages) => Buffer.from(JSON.stringify({ schemaVersion: 1, pages }), 'utf8').toString('base64');
+const NO_PAGES_SITEMAP = '<SiteMap><Area><Group/></Area></SiteMap>';
+const NAV_TO_OVERVIEW = 'export function back(){ Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_overview" }); }\nexport default function P(){ return null; }';
+const backLinkSpec = () => {
+ const spec = overviewToDetailSpec();
+ spec.pages[1].navigatesTo = [{ targetKey: 'overview' }];
+ return spec;
+};
+
+// The check right before the first in-place write is taken there, inside the loop: a page the loop CREATES before it (a new page first in the
+// spec) leaves the window open until then, and a page another app takes in during that create halts the build before it is written.
+test('pages: a page another app takes in while the loop creates an earlier page HALTS before it is written in place', async () => {
+ const spec = overviewSpec();
+ spec.pages.unshift({ key: 'intro', name: 'Intro', source: { kind: 'tsx', codeFile: 'i.tsx' } });
+ spec.appShell.areas[0].groups[0].subAreas.push({ page: 'intro', title: 'Intro' });
+ const appUnique = appUniqueName(spec);
+ const appDir = stagePages(spec.pages);
+ try {
+ const other = { uniquename: 'contoso_secondapp', sitemapxml: NO_PAGES_SITEMAP };
+ const { sdk } = mockSdk({ pageManifest: pagesManifest([{ key: 'overview', name: 'Overview', pageId: GP_O }]), manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: pagesSitemap(GP_O), otherApps: [other] });
+ const uploads = [];
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [GP_O], pages: [{ pageId: GP_O, name: 'Overview' }] }),
+ upload: async (o) => { uploads.push([o.name, o.pageId || null]); if (!o.pageId) other.savedSitemapXml = pagesSitemap(GP_O); return { pageId: o.pageId || GP_D }; } };
+ await assert.rejects(
+ runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'] }),
+ (e) => e.code === 'pages-shared-across-apps' && /became shared across apps while this build ran/.test(e.message) && /no page this build began with has been updated in place/.test(e.message));
+ assert.deepStrictEqual(uploads, [['Intro', null]], 'Intro was created; Overview was never written in place');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// The check covers EVERY page the loop will write in place, not only the one it is about to write: one taken in after the first scan halts the
+// build before the first of them is written.
+test('pages: the check before the first in-place write covers every page the loop will write in place', async () => {
+ const spec = overviewSpec();
+ spec.pages.push({ key: 'detail', name: 'Detail', source: { kind: 'tsx', codeFile: 'd.tsx' } });
+ spec.appShell.areas[0].groups[0].subAreas.push({ page: 'detail', title: 'Detail' });
+ const appUnique = appUniqueName(spec);
+ const appDir = stagePages(spec.pages);
+ try {
+ const other = { uniquename: 'contoso_secondapp', sitemapxml: NO_PAGES_SITEMAP };
+ const { sdk } = mockSdk({ pageManifest: pagesManifest([{ key: 'overview', name: 'Overview', pageId: GP_O }, { key: 'detail', name: 'Detail', pageId: GP_D }]), manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: pagesSitemap(GP_O, GP_D), otherApps: [other] });
+ const realGet = sdk.dataverse.get;
+ let savedReads = 0;
+ sdk.dataverse.get = async (url) => {
+ const r = await realGet(url);
+ // Once the first scan has read the saved layer, another maker saves Detail — the SECOND page written — into contoso_secondapp's navigation.
+ if (url.startsWith('/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()') && (savedReads += 1) === 1) other.savedSitemapXml = pagesSitemap(GP_D);
+ return r;
+ };
+ const uploads = [];
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [GP_O, GP_D], pages: [{ pageId: GP_O, name: 'Overview' }, { pageId: GP_D, name: 'Detail' }] }),
+ upload: async (o) => { uploads.push([o.name, o.pageId]); return { pageId: o.pageId }; } };
+ await assert.rejects(
+ runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'] }),
+ (e) => e.code === 'pages-shared-across-apps' && e.message.includes(GP_D) && /while this build ran/.test(e.message));
+ assert.deepStrictEqual(uploads, [], 'nothing was written in place, Overview included');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// The check is taken once, before the first in-place write — not before every page: a build that updates three pages in place scans three
+// times in all (the first scan, that check, and the last).
+test('pages: a build that updates three pages in place takes the shared-page scan three times, not once per page', async () => {
+ const GP_X = '2d7b3e4f-5a6c-4d8e-8f9a-0b1c2d3e4f5a';
+ const spec = overviewSpec();
+ spec.pages.push({ key: 'detail', name: 'Detail', source: { kind: 'tsx', codeFile: 'd.tsx' } }, { key: 'extra', name: 'Extra', source: { kind: 'tsx', codeFile: 'x.tsx' } });
+ spec.appShell.areas[0].groups[0].subAreas.push({ page: 'detail', title: 'Detail' }, { page: 'extra', title: 'Extra' });
+ const appUnique = appUniqueName(spec);
+ const appDir = stagePages(spec.pages);
+ try {
+ const { sdk, calls } = mockSdk({ pageManifest: pagesManifest([{ key: 'overview', name: 'Overview', pageId: GP_O }, { key: 'detail', name: 'Detail', pageId: GP_D }, { key: 'extra', name: 'Extra', pageId: GP_X }]), manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: pagesSitemap(GP_O, GP_D, GP_X), otherApps: [{ uniquename: 'contoso_secondapp', sitemapxml: NO_PAGES_SITEMAP }] });
+ const uploads = [];
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [GP_O, GP_D, GP_X], pages: [] }), upload: async (o) => { uploads.push(o.pageId); return { pageId: o.pageId }; } };
+ await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'] });
+ assert.deepStrictEqual(uploads, [GP_O, GP_D, GP_X]);
+ assert.strictEqual(scanReads(calls).filter((u) => u === APPS_LIST_URL).length, 3, 'the first scan, the check before the first in-place write, and the last scan');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// The check is taken ahead of the page's step, so a scan that fails there halts as the first scan's does — recoverable, in its own words —
+// rather than wrapped as a failed step.
+test('pages: a scan that fails at the check before the first in-place write halts as the first scan does: recoverable, unwrapped', async () => {
+ const spec = overviewSpec();
+ const appUnique = appUniqueName(spec);
+ const appDir = stagePages(spec.pages);
+ try {
+ const options = { pageManifest: pagesManifest([{ key: 'overview', name: 'Overview', pageId: GP_O }]), manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: pagesSitemap(GP_O), otherApps: [{ uniquename: 'contoso_secondapp', sitemapxml: NO_PAGES_SITEMAP }] };
+ const { sdk } = mockSdk(options);
+ const realGet = sdk.dataverse.get;
+ let savedReads = 0;
+ // The app list fails from the second scan on: the first scan passes, the check before the first in-place write cannot read.
+ sdk.dataverse.get = async (url) => { const r = await realGet(url); if (url.startsWith('/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()') && (savedReads += 1) === 1) options.failAppList = true; return r; };
+ const uploads = [];
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [GP_O], pages: [] }), upload: async (o) => { uploads.push(o.pageId); return { pageId: o.pageId }; } };
+ await assert.rejects(
+ runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'] }),
+ (e) => {
+ assert.strictEqual(e.code, 'pages-shared-check-failed');
+ assert.strictEqual(e.recoverable, true);
+ assert.match(e.message, /^could not scan the environment for pages shared across apps/);
+ return true;
+ });
+ assert.deepStrictEqual(uploads, [], 'nothing was written');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// A page this run created, first in the spec, is written again (its link resolved) before the loop reaches the first page the build began
+// with — where the check halts. So the halt says no page the build BEGAN WITH was updated in place, which stays true.
+test('pages: a halt after the loop wrote again a page this run created says no page the build began with was updated in place', async () => {
+ const spec = backLinkSpec();
+ spec.pages.reverse(); // Detail (created this run, links back to Overview) first
+ const appUnique = appUniqueName(spec);
+ const appDir = stagePages(spec.pages, { 'o.tsx': NAV_TO_DETAIL, 'd.tsx': NAV_TO_OVERVIEW });
+ try {
+ const other = { uniquename: 'contoso_secondapp', sitemapxml: NO_PAGES_SITEMAP };
+ const { sdk } = mockSdk({ pageManifest: pagesManifest([{ key: 'overview', name: 'Overview', pageId: GP_O }]), manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: pagesSitemap(GP_O), otherApps: [other] });
+ const uploads = [];
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [GP_O], pages: [{ pageId: GP_O, name: 'Overview' }] }),
+ upload: async (o) => { uploads.push([o.name, o.pageId || null]); if (!o.pageId) other.savedSitemapXml = pagesSitemap(GP_O); return { pageId: o.pageId || GP_D }; } };
+ await assert.rejects(
+ runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'] }),
+ (e) => e.code === 'pages-shared-across-apps' && /no page this build began with has been updated in place/.test(e.message));
+ assert.deepStrictEqual(uploads, [['Detail', null], ['Detail', GP_D]], 'Detail, which this run created, was written again; Overview was not written');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// A page this run created was not there to share when the build began, so neither later scan covers it: a fresh app whose pages link both
+// ways (each a navigation target the build creates first, then writes again with the other's id) makes no scan at all, and an unrelated
+// app whose navigation cannot be read does not stop it.
+test('pages: a fresh app whose pages link both ways makes no shared-page scan, even beside an app whose navigation cannot be read', async () => {
+ const spec = backLinkSpec();
+ const appUnique = appUniqueName(spec);
+ const appDir = stagePages(spec.pages, { 'o.tsx': NAV_TO_DETAIL, 'd.tsx': NAV_TO_OVERVIEW });
+ try {
+ const { sdk, calls } = mockSdk({ selfAppUnique: appUnique, otherApps: [{ uniquename: 'contoso_fine', sitemapxml: NO_PAGES_SITEMAP }, { uniquename: 'contoso_broken', sitemapxml: '<SiteMap><Area' }] });
+ const uploads = [];
+ const fresh = [GP_O, GP_D];
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [], pages: [] }),
+ upload: async (o) => { uploads.push([o.name, o.pageId || null]); return { pageId: o.pageId || fresh.shift() }; } };
+ const warnings = [];
+ await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'], warn: (m) => warnings.push(String(m)) });
+ assert.ok(uploads.some(([, id]) => id !== null), `a page this run created is written again with its link resolved: ${JSON.stringify(uploads)}`);
+ assert.deepStrictEqual(scanReads(calls), [], 'no shared-page scan');
+ assert.ok(find(calls, 'updateElement').some((c) => c.args[2] === '/siteMap'), 'the sitemap is written');
+ assert.deepStrictEqual(warnings.filter((w) => /another app/.test(w)), []);
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// A non-navigation page created in step 2 is never written again in place, so another app taking it in at once halts nothing.
+test('pages: a navigation target created in step 2 and taken in by another app at once does not halt the build', async () => {
+ const spec = overviewToDetailSpec();
+ const appUnique = appUniqueName(spec);
+ const appDir = stagePages(spec.pages, { 'o.tsx': NAV_TO_DETAIL });
+ try {
+ const other = { uniquename: 'contoso_secondapp', sitemapxml: NO_PAGES_SITEMAP };
+ const { sdk } = mockSdk({ pageManifest: pagesManifest([{ key: 'overview', name: 'Overview', pageId: GP_O }]), manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: pagesSitemap(GP_O), otherApps: [other] });
+ const uploads = [];
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [GP_O], pages: [{ pageId: GP_O, name: 'Overview' }] }),
+ upload: async (o) => { uploads.push([o.name, o.pageId || null]); if (!o.pageId) other.savedSitemapXml = pagesSitemap(GP_D); return { pageId: o.pageId || GP_D }; } };
+ await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'] });
+ assert.deepStrictEqual(uploads, [['Detail', null], ['Overview', GP_O]]);
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// A changed-only run writes only its selected pages, so the checks cover only those: an unselected page another app takes in after the
+// first scan halts nothing.
+test('pages: in a changed-only run, a page it does not write that another app takes in does not halt it', async () => {
+ const spec = overviewSpec();
+ spec.pages.push({ key: 'detail', name: 'Detail', source: { kind: 'tsx', codeFile: 'd.tsx' } });
+ spec.appShell.areas[0].groups[0].subAreas.push({ page: 'detail', title: 'Detail' });
+ const appUnique = appUniqueName(spec);
+ const appDir = stagePages(spec.pages);
+ try {
+ const other = { uniquename: 'contoso_secondapp', sitemapxml: NO_PAGES_SITEMAP };
+ const { sdk } = mockSdk({ pageManifest: pagesManifest([{ key: 'overview', name: 'Overview', pageId: GP_O }, { key: 'detail', name: 'Detail', pageId: GP_D }]), manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: pagesSitemap(GP_O, GP_D), otherApps: [other] });
+ const realGet = sdk.dataverse.get;
+ let savedReads = 0;
+ sdk.dataverse.get = async (url) => {
+ const r = await realGet(url);
+ // Once the first scan has read the saved layer, another maker saves Detail into contoso_secondapp's navigation.
+ if (url.startsWith('/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()') && (savedReads += 1) === 1) other.savedSitemapXml = pagesSitemap(GP_D);
+ return r;
+ };
+ const uploads = [];
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [GP_O, GP_D], pages: [{ pageId: GP_O, name: 'Overview' }, { pageId: GP_D, name: 'Detail' }] }),
+ upload: async (o) => { uploads.push([o.name, o.pageId]); return { pageId: o.pageId }; } };
+ const warnings = [];
+ await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'], changedOnly: { selectedKeys: ['overview'], skipSitemapFinalize: true }, warn: (m) => warnings.push(String(m)) });
+ assert.deepStrictEqual(uploads, [['Overview', GP_O]], 'only the selected page is written');
+ assert.deepStrictEqual(warnings.filter((w) => /another app/.test(w)), [], 'Detail was not written, so there is nothing to report');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// What the loop wrote before it stopped is written, so the last scan runs when a later page's upload fails too — and the failure still
+// reaches the caller as it was.
+test('pages: a page another app takes in is REPORTED when a later upload then fails, and the failure stands', async () => {
+ const spec = overviewSpec();
+ spec.pages.push({ key: 'detail', name: 'Detail', source: { kind: 'tsx', codeFile: 'd.tsx' } });
+ spec.appShell.areas[0].groups[0].subAreas.push({ page: 'detail', title: 'Detail' });
+ const appUnique = appUniqueName(spec);
+ const appDir = stagePages(spec.pages);
+ try {
+ const other = { uniquename: 'contoso_secondapp', sitemapxml: NO_PAGES_SITEMAP };
+ const { sdk } = mockSdk({ pageManifest: pagesManifest([{ key: 'overview', name: 'Overview', pageId: GP_O }, { key: 'detail', name: 'Detail', pageId: GP_D }]), manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: pagesSitemap(GP_O, GP_D), otherApps: [other] });
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [GP_O, GP_D], pages: [{ pageId: GP_O, name: 'Overview' }, { pageId: GP_D, name: 'Detail' }] }),
+ upload: async (o) => {
+ if (o.pageId === GP_O) { other.savedSitemapXml = pagesSitemap(GP_O); return { pageId: GP_O }; } // Overview is taken in while it uploads…
+ throw new Error('pac genpage upload failed: the request timed out'); // …and Detail's upload then fails.
+ } };
+ const warnings = [];
+ await assert.rejects(
+ runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'], warn: (m) => warnings.push(String(m)) }),
+ (e) => /the request timed out/.test(e.message), 'the upload failure is what the build reports');
+ const reported = warnings.filter((w) => /was taken into another app's navigation while this build was updating it/.test(w));
+ assert.strictEqual(reported.length, 1, JSON.stringify(warnings));
+ assert.match(reported[0], new RegExp(`^generative page "Overview" ${GP_O} `));
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// An app that has PUBLISHED the page shows the new content at once, and the report says so.
+test('pages: a page another app takes into its PUBLISHED navigation while the pages upload is reported as showing there', async () => {
+ const spec = overviewSpec();
+ spec.pages.push({ key: 'detail', name: 'Detail', source: { kind: 'tsx', codeFile: 'd.tsx' } });
+ spec.appShell.areas[0].groups[0].subAreas.push({ page: 'detail', title: 'Detail' });
+ const appUnique = appUniqueName(spec);
+ const appDir = stagePages(spec.pages);
+ try {
+ const other = { uniquename: 'contoso_secondapp', sitemapxml: NO_PAGES_SITEMAP };
+ const { sdk } = mockSdk({ pageManifest: pagesManifest([{ key: 'overview', name: 'Overview', pageId: GP_O }, { key: 'detail', name: 'Detail', pageId: GP_D }]), manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: pagesSitemap(GP_O, GP_D), otherApps: [other] });
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [GP_O, GP_D], pages: [{ pageId: GP_O, name: 'Overview' }, { pageId: GP_D, name: 'Detail' }] }),
+ upload: async (o) => { if (o.pageId === GP_O) other.sitemapxml = pagesSitemap(GP_D); return { pageId: o.pageId }; } }; // published, with Detail in it
+ const warnings = [];
+ await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'], warn: (m) => warnings.push(String(m)) });
+ const reported = warnings.filter((w) => /was taken into another app's navigation while this build was updating it/.test(w));
+ assert.strictEqual(reported.length, 1, JSON.stringify(warnings));
+ assert.match(reported[0], new RegExp(`^generative page "Detail" ${GP_D} \\(also in contoso_secondapp\\) was taken into another app's navigation while this build was updating it, so its new content shows there too\\.`));
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
test('pages: an UNREADABLE other-app sitemap HALTS pages-shared-check-failed (fail-closed — cannot prove non-sharing)', async () => {
const spec = overviewSpec();
const appUnique = appUniqueName(spec);
@@ -5136,6 +6245,96 @@ test('pages: an env app-list failure HALTS pages-shared-check-failed (fail-close
} finally { fs.rmSync(appDir, { recursive: true, force: true }); }
});
+// The build reads other things through the client too; the shared-page scan's own read is the sitemap collection's.
+const SAVED_URL = '/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapxml,componentstate,sitemapnameunique';
+const savedLayerReads = (calls) => find(calls, 'dataverse.get').filter((c) => c.args[0].startsWith('/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()'));
+
+test('pages: a page shared with another app\'s SAVED (unpublished) navigation HALTS pages-shared-across-apps and names where it is saved', async () => {
+ const spec = overviewSpec();
+ const appUnique = appUniqueName(spec);
+ const appDir = stagePages(spec.pages);
+ try {
+ const existing = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: GP_O }] }), 'utf8').toString('base64');
+ const sitemapWithO = `<SiteMap><Area><Group><SubArea GenPageId="${GP_O}" Title="Overview"/></Group></Area></SiteMap>`;
+ // contoso_secondapp's PUBLISHED navigation does not have the page; its maker has saved the page into the draft, and not published it.
+ // The published scan alone read this as "not shared" and the build rewrote the page.
+ const mk = () => mockSdk({ pageManifest: existing, manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: sitemapWithO, otherApps: [{ uniquename: 'contoso_secondapp', sitemapxml: '<SiteMap><Area><Group/></Area></SiteMap>', savedSitemapXml: sitemapWithO }] });
+ const uploads = [];
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [GP_O], pages: [{ pageId: GP_O, name: 'Overview' }] }), upload: async (o) => { uploads.push(o); return { pageId: o.pageId || GP_O }; } };
+ for (const allowDestructive of [false, true]) {
+ const { sdk, calls } = mk();
+ await assert.rejects(
+ runSdkBuild(spec, { sdk, apply: true, allowDestructive, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'] }),
+ (e) => {
+ assert.strictEqual(e.phase, 'pages');
+ assert.strictEqual(e.code, 'pages-shared-across-apps');
+ assert.match(e.message, new RegExp(`${GP_O} \\(also in contoso_secondapp \\[saved, not published\\]\\)`));
+ return true;
+ },
+ `allowDestructive=${allowDestructive}: cross-app mutation has no escape`
+ );
+ assert.strictEqual(savedLayerReads(calls).length, 1, 'the saved layer of every other app is one read');
+ }
+ assert.deepStrictEqual(uploads, [], 'the shared page was never uploaded');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+test('pages: another app\'s saved navigation that cannot be read HALTS pages-shared-check-failed (fail-closed — cannot prove non-sharing)', async () => {
+ const spec = overviewSpec();
+ const appUnique = appUniqueName(spec);
+ const appDir = stagePages(spec.pages);
+ try {
+ const existing = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: GP_O }] }), 'utf8').toString('base64');
+ const sitemapWithO = `<SiteMap><Area><Group><SubArea GenPageId="${GP_O}" Title="Overview"/></Group></Area></SiteMap>`;
+ const empty = '<SiteMap><Area><Group/></Area></SiteMap>';
+ const uploads = [];
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [GP_O], pages: [{ pageId: GP_O, name: 'Overview' }] }), upload: async (o) => { uploads.push(o); return { pageId: o.pageId || GP_O }; } };
+ const cases = {
+ // The whole read fails: no app's draft is known.
+ 'the saved read fails': [{ savedNavigationError: true, otherApps: [{ uniquename: 'contoso_secondapp', sitemapxml: empty }] }, /could not scan the environment[\s\S]*saved \(unpublished\) navigation/],
+ // The read works, but the app's own saved row did not come back: that app's draft cannot be ruled out.
+ 'one app\'s saved row is missing': [{ otherApps: [{ uniquename: 'contoso_secondapp', sitemapxml: empty, savedRows: [] }] }, /1 app\(s\) had an unreadable sitemap \(contoso_secondapp\)/],
+ 'one app\'s saved XML is cut short': [{ otherApps: [{ uniquename: 'contoso_secondapp', sitemapxml: empty, savedRows: [{ sitemapxml: '<SiteMap><Area', componentstate: 1 }] }] }, /1 app\(s\) had an unreadable sitemap \(contoso_secondapp\)/],
+ };
+ for (const [what, [extra, message]] of Object.entries(cases)) {
+ const { sdk } = mockSdk({ pageManifest: existing, manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: sitemapWithO, ...extra });
+ await assert.rejects(
+ runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'] }),
+ (e) => {
+ assert.strictEqual(e.phase, 'pages', what);
+ assert.strictEqual(e.code, 'pages-shared-check-failed', what);
+ assert.match(e.message, message, what);
+ return true;
+ },
+ what
+ );
+ }
+ assert.deepStrictEqual(uploads, [], 'nothing was uploaded while sharing could not be ruled out');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+test('pages: other apps that do not hold the page — in either layer — pass the check, with one saved-layer read per scan', async () => {
+ const spec = overviewSpec();
+ const appUnique = appUniqueName(spec);
+ const appDir = stagePages(spec.pages);
+ try {
+ const existing = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: GP_O }] }), 'utf8').toString('base64');
+ const sitemapWithO = `<SiteMap><Area><Group><SubArea GenPageId="${GP_O}" Title="Overview"/></Group></Area></SiteMap>`;
+ const other = '<SiteMap><Area><Group><SubArea GenPageId="00000000-0000-4000-8000-0000000000aa" Title="Other"/></Group></Area></SiteMap>';
+ const { sdk, calls } = mockSdk({ pageManifest: existing, manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: sitemapWithO, otherApps: [
+ { uniquename: 'contoso_secondapp', sitemapxml: other },
+ { uniquename: 'contoso_thirdapp', sitemapxml: other, savedSitemapXml: other },
+ { uniquename: 'contoso_fourthapp', sitemapxml: other },
+ ] });
+ const uploads = [];
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [GP_O], pages: [{ pageId: GP_O, name: 'Overview' }] }), upload: async (o) => { uploads.push(o); return { pageId: o.pageId || GP_O }; } };
+ await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'] });
+ assert.strictEqual(uploads.length, 1);
+ assert.strictEqual(uploads[0].pageId, GP_O, 'reused (UPDATE): nobody else holds the page');
+ assert.strictEqual(savedLayerReads(calls).length, 3, 'three other apps, one saved-layer read per scan — and three scans, as the build writes a page in place');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
test('pages: a single-app env passes the shared-page check (reads no other sitemaps) and reuses the page', async () => {
const spec = overviewSpec();
const appUnique = appUniqueName(spec);
@@ -5143,13 +6342,147 @@ test('pages: a single-app env passes the shared-page check (reads no other sitem
try {
const existing = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: GP_O }] }), 'utf8').toString('base64');
const sm = `<SiteMap><Area><Group><SubArea GenPageId="${GP_O}"/></Group></Area></SiteMap>`;
- const { sdk } = mockSdk({ pageManifest: existing, manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: sm }); // no otherApps
+ const { sdk, calls } = mockSdk({ pageManifest: existing, manifestId: 'wr-manifest', selfAppUnique: appUnique, liveSitemapXml: sm }); // no otherApps
const uploads = [];
const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [GP_O], pages: [{ pageId: GP_O, name: 'Overview' }] }), upload: async (o) => { uploads.push(o); return { pageId: o.pageId || GP_O }; } };
await runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'] });
assert.strictEqual(uploads.length, 1);
assert.strictEqual(uploads[0].pageId, GP_O, 'reused (UPDATE); a single-app env has no other app to share with');
+ // The cost of knowing there is no draft app: ONE small read of the list of apps that were never published, and no sitemap — saved or published — of any other app.
+ // The scan is taken three times when the build writes a page in place (before any write, right before the first one, and after the last: the
+ // others are the build's own guard against another maker taking a page in while it runs), so that is three such reads in all.
+ assert.deepStrictEqual(scanReads(calls), [APPS_LIST_URL, APPS_LIST_URL, APPS_LIST_URL], 'one request per scan, three scans');
+ assert.strictEqual(savedLayerReads(calls).length, 0);
} finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// An app saved in the maker and never published has no row in the published app list, so the scan read nothing of it: a page it holds was updated without a halt, and the draft
+// then showed a rewritten page when its maker published it. The scan lists such apps (one request) and reads their saved sitemap from the saved-layer read.
+// The shared-page scan's own reads through the client (the build makes others — entity definitions, say): the list of never-published apps, and the sitemaps' saved layer.
+const scanReads = (calls) => find(calls, 'dataverse.get').map((c) => c.args[0]).filter((url) => url.startsWith('/appmodules/') || url.startsWith('/sitemaps/'));
+const APPS_LIST_URL = '/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,uniquename,componentstate';
+const stageUpdate = () => {
+ const spec = overviewSpec();
+ const sitemapWithO = `<SiteMap><Area><Group><SubArea GenPageId="${GP_O}" Title="Overview"/></Group></Area></SiteMap>`;
+ const existing = Buffer.from(JSON.stringify({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: GP_O }] }), 'utf8').toString('base64');
+ const uploads = [];
+ const genpageCli = { enumerateEnv: async () => ({ ok: true, ids: [GP_O], pages: [{ pageId: GP_O, name: 'Overview' }] }), upload: async (o) => { uploads.push(o); return { pageId: o.pageId || GP_O }; } };
+ return { spec, appUnique: appUniqueName(spec), appDir: stagePages(spec.pages), sitemapWithO, existing, uploads, genpageCli };
+};
+const runPagesUpdate = (s, sdk, extra = {}) => runSdkBuild(s.spec, { sdk, apply: true, env: 'https://x', appDir: s.appDir, genpageCli: s.genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'], ...extra });
+
+test('pages: a page shared with a NEVER-PUBLISHED app\'s saved navigation HALTS pages-shared-across-apps and names where it is saved', async () => {
+ const s = stageUpdate();
+ try {
+ // The only other app has never been published: the published list has no row for it. The published scan alone read this environment as having no other app.
+ for (const allowDestructive of [false, true]) {
+ const { sdk, calls } = mockSdk({ pageManifest: s.existing, manifestId: 'wr-manifest', selfAppUnique: s.appUnique, liveSitemapXml: s.sitemapWithO, draftApps: [{ uniquename: 'contoso_draftapp', savedSitemapXml: s.sitemapWithO }] });
+ await assert.rejects(
+ runPagesUpdate(s, sdk, { allowDestructive }),
+ (e) => {
+ assert.strictEqual(e.phase, 'pages');
+ assert.strictEqual(e.code, 'pages-shared-across-apps');
+ assert.match(e.message, new RegExp(`${GP_O} \\(also in contoso_draftapp \\[saved, not published\\]\\)`));
+ return true;
+ },
+ `allowDestructive=${allowDestructive}: cross-app mutation has no escape`
+ );
+ assert.deepStrictEqual(scanReads(calls), [APPS_LIST_URL, SAVED_URL], 'the list of apps, then the one saved-layer read');
+ }
+ assert.deepStrictEqual(s.uploads, [], 'the shared page was never uploaded');
+ // Control: the same environment whose draft app holds some other page passes, and the page is updated.
+ const other = '<SiteMap><Area><Group><SubArea GenPageId="00000000-0000-4000-8000-0000000000aa" Title="Other"/></Group></Area></SiteMap>';
+ const { sdk } = mockSdk({ pageManifest: s.existing, manifestId: 'wr-manifest', selfAppUnique: s.appUnique, liveSitemapXml: s.sitemapWithO, draftApps: [{ uniquename: 'contoso_draftapp', savedSitemapXml: other }] });
+ await runPagesUpdate(s, sdk);
+ assert.strictEqual(s.uploads.length, 1);
+ assert.strictEqual(s.uploads[0].pageId, GP_O);
+ } finally { fs.rmSync(s.appDir, { recursive: true, force: true }); }
+});
+
+test('pages: the list of never-published apps that cannot be read HALTS pages-shared-check-failed, in a single-app environment too', async () => {
+ const s = stageUpdate();
+ try {
+ const { sdk } = mockSdk({ pageManifest: s.existing, manifestId: 'wr-manifest', selfAppUnique: s.appUnique, liveSitemapXml: s.sitemapWithO, draftAppsError: true });
+ await assert.rejects(
+ runPagesUpdate(s, sdk),
+ (e) => {
+ assert.strictEqual(e.phase, 'pages');
+ assert.strictEqual(e.code, 'pages-shared-check-failed');
+ assert.match(e.message, /could not scan the environment[\s\S]*could not list the apps that have never been published/);
+ return true;
+ }
+ );
+ assert.deepStrictEqual(s.uploads, [], 'nothing was uploaded while it could not be told whether a draft app holds the page');
+ } finally { fs.rmSync(s.appDir, { recursive: true, force: true }); }
+});
+
+// An app saved in the maker with nothing but a name has no sitemap component, and no sitemap of its name: it has no navigation and holds no page. A read that SUCCEEDS and finds no component,
+// with no sitemap of the app's name in the saved layer, shows that, and one such app must not stop every page update in the environment; a read that FAILS proves nothing and still halts
+// (the next test, and the unit tests of fetchAppsForPages).
+test('pages: a never-published app with no sitemap component and no sitemap of its name holds no page, so the update goes ahead — for the list of apps and one saved-layer read per scan', async () => {
+ const s = stageUpdate();
+ try {
+ // Another app's sitemap that names the page is nothing to do with it: no row carries this app's name.
+ const bare = { uniquename: 'contoso_bareapp', savedRows: [], noSitemapComponent: true };
+ const alone = mockSdk({ pageManifest: s.existing, manifestId: 'wr-manifest', selfAppUnique: s.appUnique, liveSitemapXml: s.sitemapWithO, draftApps: [bare] });
+ await runPagesUpdate(s, alone.sdk);
+ assert.strictEqual(s.uploads.length, 1);
+ assert.strictEqual(s.uploads[0].pageId, GP_O, 'the page is updated in place');
+ assert.deepStrictEqual(scanReads(alone.calls), [APPS_LIST_URL, SAVED_URL, APPS_LIST_URL, SAVED_URL, APPS_LIST_URL, SAVED_URL],
+ 'the saved layer is read once per scan, which is how the app is shown to have no sitemap (three scans: the build writes a page in place)');
+ // Beside a draft app that does hold the page the build still halts, and names only that app.
+ s.uploads.length = 0;
+ const mixed = mockSdk({ pageManifest: s.existing, manifestId: 'wr-manifest', selfAppUnique: s.appUnique, liveSitemapXml: s.sitemapWithO, draftApps: [bare, { uniquename: 'contoso_draftapp', savedSitemapXml: s.sitemapWithO }] });
+ await assert.rejects(
+ runPagesUpdate(s, mixed.sdk),
+ (e) => e.code === 'pages-shared-across-apps' && new RegExp(`${GP_O} \\(also in contoso_draftapp \\[saved, not published\\]\\)`).test(e.message) && !/contoso_bareapp/.test(e.message)
+ );
+ assert.deepStrictEqual(s.uploads, []);
+ } finally { fs.rmSync(s.appDir, { recursive: true, force: true }); }
+});
+
+// The SDK links an app to its sitemap by the sitemap's unique name, whatever its component rows say, so an app whose layer has no sitemap component can still hold a sitemap — and
+// the page in it. The scan finds it through the saved-layer read it makes anyway, and the update halts like any other shared page.
+test('pages: a never-published app with no sitemap component whose sitemap is linked to it by name HALTS the update, naming the app — a sitemap of another name does not', async () => {
+ const s = stageUpdate();
+ try {
+ const linked = { uniquename: 'contoso_linkedapp', savedSitemapXml: s.sitemapWithO, noSitemapComponent: true };
+ const { sdk, calls } = mockSdk({ pageManifest: s.existing, manifestId: 'wr-manifest', selfAppUnique: s.appUnique, liveSitemapXml: s.sitemapWithO, draftApps: [linked] });
+ await assert.rejects(
+ runPagesUpdate(s, sdk),
+ (e) => e.phase === 'pages' && e.code === 'pages-shared-across-apps' && new RegExp(`${GP_O} \\(also in contoso_linkedapp \\[saved, not published\\]\\)`).test(e.message)
+ );
+ assert.deepStrictEqual(scanReads(calls), [APPS_LIST_URL, SAVED_URL], 'no request beyond the ones a draft app costs anyway');
+ assert.deepStrictEqual(s.uploads, [], 'the shared page was never uploaded');
+ // Control: the same sitemap under another app's name is not this app's, so the update goes ahead.
+ const { sdk: other } = mockSdk({ pageManifest: s.existing, manifestId: 'wr-manifest', selfAppUnique: s.appUnique, liveSitemapXml: s.sitemapWithO, draftApps: [{ ...linked, sitemapName: 'contoso_someoneelse' }] });
+ await runPagesUpdate(s, other);
+ assert.strictEqual(s.uploads.length, 1);
+ } finally { fs.rmSync(s.appDir, { recursive: true, force: true }); }
+});
+
+test('pages: a never-published app whose navigation cannot be read HALTS pages-shared-check-failed and names it', async () => {
+ const s = stageUpdate();
+ try {
+ const cases = {
+ 'its sitemap component read fails': { uniquename: 'contoso_draftapp', savedSitemapXml: s.sitemapWithO, componentReadFails: true },
+ 'its saved row did not come back': { uniquename: 'contoso_draftapp', savedRows: [] },
+ 'its saved XML is cut short': { uniquename: 'contoso_draftapp', savedRows: [{ sitemapxml: '<SiteMap><Area', componentstate: 1 }] },
+ };
+ for (const [what, draft] of Object.entries(cases)) {
+ const { sdk } = mockSdk({ pageManifest: s.existing, manifestId: 'wr-manifest', selfAppUnique: s.appUnique, liveSitemapXml: s.sitemapWithO, draftApps: [draft] });
+ await assert.rejects(
+ runPagesUpdate(s, sdk),
+ (e) => {
+ assert.strictEqual(e.code, 'pages-shared-check-failed', what);
+ assert.match(e.message, /1 app\(s\) had an unreadable sitemap \(contoso_draftapp\)/, what);
+ return true;
+ },
+ what
+ );
+ }
+ assert.deepStrictEqual(s.uploads, []);
+ } finally { fs.rmSync(s.appDir, { recursive: true, force: true }); }
});
test('a by-value publish failure reaches the warn channel through the whole build', async () => {
diff --git a/plugins/model-apps/scripts/tests/sdk-http-client.test.js b/plugins/model-apps/scripts/tests/sdk-http-client.test.js
index 6b33228f8..d84609a13 100644
--- a/plugins/model-apps/scripts/tests/sdk-http-client.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-http-client.test.js
@@ -1,7 +1,7 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
-const { createAzHttpClient, retryAfterMs, isBatchThrottled, batchRetryAfterMs, RETRY_AFTER_CAP_MS } = require('../lib/sdk-http-client.js');
+const { createAzHttpClient, retryAfterMs, isBatchThrottled, isColumnCreateBatch, batchRetryAfterMs, RETRY_AFTER_CAP_MS } = require('../lib/sdk-http-client.js');
// A fake transport that records the last request and returns a scripted response.
function fakeTransport(scripted) {
@@ -515,7 +515,7 @@ test('postRaw DOES re-send a $batch of conditional deletes that was refused with
}
});
-test('postRaw re-sends a 429 $batch ONLY when it is made of conditional deletes and the answer proves nothing ran', async () => {
+test('postRaw re-sends a 429 $batch ONLY when it is made of conditional deletes (or of column creates, below) and the answer proves nothing ran', async () => {
const answers = {
'an operation that committed beside the refused one': batchAnswer(['HTTP/1.1 204 No Content'], ['HTTP/1.1 429 Too Many Requests', '{}']),
'a refusal beside another failure': batchAnswer(['HTTP/1.1 429 Too Many Requests', '{}'], ['HTTP/1.1 500 Internal Server Error', '{}']),
@@ -550,6 +550,116 @@ test('postRaw re-sends a 429 $batch ONLY when it is made of conditional deletes
}
});
+// The ordinary columns of a new table go in one change set (the SDK's createColumns): a POST of each column's definition to the
+// table's `Attributes` collection, with the solution header on each operation. It carries no delete and no conditional write, so a
+// 429 — the server refused to START it, as it can while the table the columns were just created in is still held by its
+// customization lock — proves nothing in it ran, and sending it again cannot remove or overwrite anything.
+const columnChangeSet = (...names) => [
+ '--batch_b', 'Content-Type: multipart/mixed;boundary=changeset_c', '',
+ ...names.flatMap((name, i) => [
+ '--changeset_c', 'Content-Type: application/http', 'Content-Transfer-Encoding: binary', `Content-ID: ${i + 1}`, '',
+ "POST https://org.crm.dynamics.com/api/data/v9.0/EntityDefinitions(LogicalName='new_ticket')/Attributes HTTP/1.1",
+ 'Content-Type: application/json;type=entry', 'MSCRM.SolutionUniqueName: Tickets', '',
+ JSON.stringify({ '@odata.type': 'Microsoft.Dynamics.CRM.StringAttributeMetadata', SchemaName: name }),
+ ]),
+ '--changeset_c--', '--batch_b--', '',
+].join('\r\n');
+const COLUMNS = columnChangeSet('new_a', 'new_b');
+const TABLE_LOCKED_429 = { statusCode: 429, headers: {}, body: JSON.stringify({ error: { code: '0x80072322', message: 'Cannot start the requested operation [Publish] because there is another [EntityCustomization] running at this moment.' } }) };
+
+test('postRaw DOES re-send a $batch that only creates columns when it was refused with 429, in either shape, on the throttle schedule', async () => {
+ const answers = {
+ 'the whole request refused': TABLE_LOCKED_429,
+ 'the whole request refused, no body': { statusCode: 429, headers: {}, body: '' },
+ 'its change set refused': { statusCode: 429, headers: {}, body: batchAnswer(['HTTP/1.1 429 Too Many Requests', TABLE_LOCKED_429.body]) },
+ 'every operation refused, whatever the outer status': { statusCode: 200, headers: {}, body: batchAnswer(['HTTP/1.1 429 Too Many Requests', '{}'], ['HTTP/1.1 429 Too Many Requests', '{}']) },
+ };
+ for (const [what, refused] of Object.entries(answers)) {
+ const slept = [];
+ const { request, calls } = fakeTransport(() => (calls.length <= 2 ? refused : { statusCode: 200, headers: {}, body: BATCH_RESPONSE }));
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, random: () => 0.5, sleep: async (ms) => { slept.push(ms); } });
+ const res = await postBatch(http, COLUMNS);
+ assert.strictEqual(calls.length, 3, `re-sent twice: ${what}`);
+ assert.ok(calls.every((c) => c.body === COLUMNS), `the same change set, byte for byte, each time: ${what}`);
+ assert.deepStrictEqual(slept, [1125, 2250], `the jittered backoff every other throttled request gets: ${what}`);
+ assert.strictEqual(res.status, 200);
+ assert.strictEqual(res.body, BATCH_RESPONSE, `the SDK reads the re-sent batch's own answer: ${what}`);
+ }
+ // It does not give up early, and it stops where every other throttled request stops: six sends in all.
+ const slept = [];
+ const { request, calls } = fakeTransport(TABLE_LOCKED_429);
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, random: () => 0, sleep: async (ms) => { slept.push(ms); } });
+ const gaveUp = await postBatch(http, COLUMNS);
+ assert.strictEqual(calls.length, 6, 'six attempts in all');
+ assert.deepStrictEqual(slept, [1000, 2000, 4000, 8000, 8000]);
+ assert.strictEqual(gaveUp.status, 429, 'after the last attempt the refusal surfaces unchanged');
+ assert.strictEqual(gaveUp.body, TABLE_LOCKED_429.body, 'raw, as the SDK reads it');
+});
+
+test('postRaw sends a $batch of column creates ONCE after every answer but a 429 that proves nothing in it ran', async () => {
+ const answers = {
+ 'a 500': { statusCode: 500, headers: {}, body: '{"error":{"message":"An unexpected error occurred."}}' },
+ 'a 502': { statusCode: 502, headers: {}, body: 'bad gateway' },
+ 'a 503': { statusCode: 503, headers: {}, body: 'busy' },
+ 'a 504': { statusCode: 504, headers: {}, body: '' },
+ 'a refused change set (the failing operation only)': { statusCode: 400, headers: {}, body: batchAnswer(['HTTP/1.1 400 Bad Request', JSON.stringify({ error: { code: '0x80060304', message: 'Attribute createdon already exists for entity new_ticket.' } })]) },
+ 'a plain 400': { statusCode: 400, headers: {}, body: '{"error":{"message":"The attribute metadata is not valid for this table"}}' },
+ // A change set can commit behind any of these.
+ 'an accepted change set': { statusCode: 200, headers: {}, body: BATCH_RESPONSE },
+ 'a SQL deadlock victim (re-sent for conditional deletes only)': BATCH_DEADLOCK_500,
+ 'an operation that committed beside the refused one': { statusCode: 429, headers: {}, body: batchAnswer(['HTTP/1.1 204 No Content'], ['HTTP/1.1 429 Too Many Requests', '{}']) },
+ 'a refusal beside another failure': { statusCode: 429, headers: {}, body: batchAnswer(['HTTP/1.1 429 Too Many Requests', '{}'], ['HTTP/1.1 500 Internal Server Error', '{}']) },
+ 'a multipart answer cut short': { statusCode: 429, headers: {}, body: batchAnswer(['HTTP/1.1 429 Too Many Requests', '{}']).replace(/--batchresponse_b1--\r\n$/, '') },
+ 'a complete answer with no operation results': { statusCode: 429, headers: {}, body: '--batchresponse_b1\r\n--batchresponse_b1--\r\n' },
+ };
+ for (const [what, answer] of Object.entries(answers)) {
+ const { request, calls } = fakeTransport(answer);
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });
+ const res = await postBatch(http, COLUMNS);
+ assert.strictEqual(calls.length, 1, `sent once: ${what}`);
+ assert.strictEqual(res.body, answer.body, `and the answer reaches the SDK as it came: ${what}`);
+ }
+ // No answer at all, or one cut off after the server had answered: the outcome is unknown, so nothing is sent again.
+ for (const [what, outcome] of [['a transport failure', { error: 'ETIMEDOUT' }], ['an answer cut off after the server answered', { error: 'Connection closed before the response completed', incompleteResponse: true, statusCode: 200 }]]) {
+ const { request, calls } = fakeTransport(outcome);
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });
+ await assert.rejects(postBatch(http, COLUMNS), /Request failed/, what);
+ assert.strictEqual(calls.length, 1, `sent once: ${what}`);
+ }
+});
+
+test('postRaw never re-sends a 429 $batch that does more than create columns', async () => {
+ const column = ['POST', "https://org.crm.dynamics.com/api/data/v9.0/EntityDefinitions(LogicalName='new_ticket')/Attributes"];
+ const requests = {
+ 'a column create beside an update': batchRequest(column, ['PATCH', 'https://org.crm.dynamics.com/api/data/v9.0/appmodules(1)', ['If-Match: *']]),
+ 'a column create beside a delete': batchRequest(column, ['DELETE', 'https://org.crm.dynamics.com/api/data/v9.0/appmodules(1)']),
+ 'a column create beside a conditional delete': batchRequest(column, ['DELETE', 'https://org.crm.dynamics.com/api/data/v9.0/appmodules(1)', ['If-Match: W/"1"']]),
+ 'a table create': batchRequest(['POST', 'https://org.crm.dynamics.com/api/data/v9.0/EntityDefinitions']),
+ 'a create in a record collection': batchRequest(['POST', 'https://org.crm.dynamics.com/api/data/v9.0/appmodules']),
+ 'a POST to one column, not to the collection': batchRequest(['POST', "https://org.crm.dynamics.com/api/data/v9.0/EntityDefinitions(LogicalName='new_ticket')/Attributes(11111111-1111-1111-1111-111111111111)"]),
+ 'an update of one column': batchRequest(['PATCH', "https://org.crm.dynamics.com/api/data/v9.0/EntityDefinitions(LogicalName='new_ticket')/Attributes"]),
+ 'no operation at all': '--b\r\n',
+ };
+ for (const [what, body] of Object.entries(requests)) {
+ const { request, calls } = fakeTransport(TABLE_LOCKED_429);
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} });
+ await postBatch(http, body);
+ assert.strictEqual(calls.length, 1, `not re-sent: ${what}`);
+ }
+});
+
+test('isColumnCreateBatch accepts a batch only when EVERY operation is a POST to a table\'s Attributes collection', () => {
+ assert.strictEqual(isColumnCreateBatch(COLUMNS), true);
+ assert.strictEqual(isColumnCreateBatch(columnChangeSet('new_a')), true);
+ assert.strictEqual(isColumnCreateBatch(columnChangeSet(...Array.from({ length: 25 }, (_, i) => `new_c${i}`))), true);
+ assert.strictEqual(isColumnCreateBatch(COLUMNS.replace(/\r\n/g, '\n')), true, 'line endings do not matter');
+ assert.strictEqual(isColumnCreateBatch(APP_DELETE), false);
+ assert.strictEqual(isColumnCreateBatch(''), false);
+ assert.strictEqual(isColumnCreateBatch(undefined), false);
+ assert.strictEqual(isColumnCreateBatch(Buffer.from(COLUMNS)), false, 'a body that is not text');
+ assert.strictEqual(isColumnCreateBatch(COLUMNS.replace("POST https://org.crm.dynamics.com/api/data/v9.0/EntityDefinitions(LogicalName='new_ticket')/Attributes HTTP/1.1", "PUT https://org.crm.dynamics.com/api/data/v9.0/EntityDefinitions(LogicalName='new_ticket')/Attributes HTTP/1.1")), false, 'one operation of another method');
+});
+
test('a throttled answer\u2019s Retry-After is honoured, up to a cap, when it asks for longer than the backoff', async () => {
const NOW = Date.parse('2026-09-30T10:00:00Z');
const cases = [
@@ -562,7 +672,7 @@ test('a throttled answer\u2019s Retry-After is honoured, up to a cap, when it as
['1', 1125], // shorter than the backoff: the backoff
];
for (const [value, want] of cases) {
- for (const [what, send] of [['a GET', (h) => h.get('https://org.crm.dynamics.com/x')], ['a record delete', (h) => h.delete('https://org.crm.dynamics.com/api/data/v9.0/solutions(1)')]]) {
+ for (const [what, send] of [['a GET', (h) => h.get('https://org.crm.dynamics.com/x')], ['a record delete', (h) => h.delete('https://org.crm.dynamics.com/api/data/v9.0/solutions(1)')], ['a change set of column creates', (h) => postBatch(h, COLUMNS)]]) {
const slept = [];
const { request, calls } = fakeTransport(() => (calls.length <= 1 ? { statusCode: 429, headers: { 'retry-after': value }, body: '' } : { statusCode: 204, headers: {}, body: '' }));
const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, random: () => 0.5, now: () => NOW, sleep: async (ms) => { slept.push(ms); } });
@@ -592,12 +702,14 @@ test('a batch refused operation by operation waits for the Retry-After in the re
['the backoff when neither asks for longer', { headers: {}, parts: [part()] }, 1125],
];
for (const [what, { headers, parts }, want] of cases) {
- const slept = [];
- const refused = { statusCode: 429, headers, body: batchAnswer(...parts) };
- const { request, calls } = fakeTransport(() => (calls.length <= 1 ? refused : { statusCode: 200, headers: {}, body: BATCH_RESPONSE }));
- const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, random: () => 0.5, now: () => NOW, sleep: async (ms) => { slept.push(ms); } });
- await postBatch(http);
- assert.deepStrictEqual(slept, [want], what);
+ for (const [kind, batch] of [['conditional deletes', APP_DELETE], ['column creates', COLUMNS]]) {
+ const slept = [];
+ const refused = { statusCode: 429, headers, body: batchAnswer(...parts) };
+ const { request, calls } = fakeTransport(() => (calls.length <= 1 ? refused : { statusCode: 200, headers: {}, body: BATCH_RESPONSE }));
+ const http = createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, random: () => 0.5, now: () => NOW, sleep: async (ms) => { slept.push(ms); } });
+ await postBatch(http, batch);
+ assert.deepStrictEqual(slept, [want], `${what} (${kind})`);
+ }
}
assert.strictEqual(batchRetryAfterMs({ body: batchAnswer(['HTTP/1.1 204 No Content\r\nRetry-After: 30']) }), 0, 'only a refused operation\u2019s wait counts');
assert.strictEqual(batchRetryAfterMs({ body: '{"error":{}}' }), 0, 'a plain answer has no parts');
diff --git a/plugins/model-apps/scripts/tests/sdk-opt-ins.test.js b/plugins/model-apps/scripts/tests/sdk-opt-ins.test.js
new file mode 100644
index 000000000..98661ad04
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/sdk-opt-ins.test.js
@@ -0,0 +1,161 @@
+'use strict';
+// Two performance options of the vendored SDK that this plugin deliberately leaves off, and the facts each
+// decision rests on. Neither is an oversight, and each would be easy to switch on later without noticing what
+// it breaks — so what keeps them off is pinned here, against the real bundle where the SDK is the subject.
+//
+// readConcurrency overlaps the file downloads of a generative page that the SDK reads, and the per-component
+// reads of fetchSolution. The plugin makes neither read: its pages go through
+// `pac model genpage`, and no script fetches a solution. The option would change nothing, so
+// it is not passed. A script that starts to make one of those reads is where it belongs.
+// published:false creates an app as a never-published draft that a later publish covers, saving a publish
+// round trip per create. A draft is not in the PUBLISHED projection that every app-existence
+// probe in the plugin reads (a by-id read answers 404, a by-name query finds nothing), so
+// the plugin creates its apps published.
+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 { appDef } = require('../lib/sdk-build.js');
+const { scriptsMatching } = require('./helpers/production-scripts.js');
+
+const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
+const ENV = 'https://contoso.crm.dynamics.com';
+const ICON_ID = '11111111-2222-3333-4444-555555555555';
+const TABLE_METADATA_ID = '22222222-2222-2222-2222-222222222222';
+const ROLE_ID = '66666666-6666-6666-6666-666666666666';
+
+const tempDirs = [];
+test.after(() => { for (const d of tempDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+// --- readConcurrency --------------------------------------------------------------------------------
+
+test('readConcurrency is passed exactly when some script makes a read it overlaps', () => {
+ // The two loops the option overlaps are a generative page's file downloads (reached by naming the SDK's
+ // 'genPage' artifact type) and fetchSolution's component reads.
+ const readers = scriptsMatching(/\bfetchSolution\b|['"`]genPage['"`]/);
+ const passers = scriptsMatching(/\breadConcurrency\b/);
+ assert.strictEqual(
+ readers.length > 0,
+ passers.length > 0,
+ readers.length
+ ? `${readers.join(', ')} read(s) a generative page or a solution through the SDK, so that SDK instance should be created with `
+ + '`readConcurrency` (4, through one shared constant), after measuring that the overlap helps. The window is 1-8 and defaults to 1.'
+ : `${passers.join(', ')} pass(es) readConcurrency, but no script reads a generative page or a solution through the SDK, so it overlaps nothing. `
+ + 'Drop it, or add the read it is for.'
+ );
+});
+
+// --- published:false ---------------------------------------------------------------------------------
+
+const spec = () => ({
+ solution: { uniqueName: 'probe', publisherPrefix: 'new' },
+ app: { name: 'Probe', description: 'Tickets' },
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Main', subAreas: [{ entity: 'new_torder', label: 'Orders' }] }] }] },
+});
+const appDefinition = () => appDef(spec(), { forms: {}, views: {}, charts: {} }, { iconWebResourceId: ICON_ID });
+
+// A Dataverse that holds the one app a create writes. An appmodule is a DRAFT until a PublishXml names it: a
+// by-id read answers 404 and a plain query finds nothing — only the RetrieveUnpublished* reads see it. That is the
+// platform's published projection, which the SDK's own lookups and every probe in the plugin go through.
+function fakeOrg() {
+ const state = { app: null, sitemap: null, published: false, requests: [] };
+ const appRow = () => ({
+ appmoduleid: state.app.appmoduleid,
+ appmoduleidunique: '99999999-9999-9999-9999-999999999999',
+ name: state.app.name,
+ uniquename: state.app.uniquename,
+ componentstate: state.published ? 0 : 1,
+ '@odata.etag': 'W/"1001"',
+ });
+ const answer = (value) => ({ status: 200, headers: {}, body: { value } });
+ const httpClient = {
+ get: async (url) => {
+ const where = decodeURIComponent(url);
+ state.requests.push({ verb: 'GET', url: where });
+ const table = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(where);
+ if (table) return { status: 200, headers: {}, body: { LogicalName: table[1], MetadataId: TABLE_METADATA_ID, EntitySetName: `${table[1]}s` } };
+ if (/\/appmodulecomponents/.test(where)) {
+ const wantsSitemap = /componenttype eq 62/.test(where);
+ return answer(wantsSitemap ? [{ objectid: state.sitemap && state.sitemap.sitemapid, componenttype: 62 }] : [{ objectid: TABLE_METADATA_ID, componenttype: 1 }]);
+ }
+ if (/\/sitemaps/.test(where)) {
+ const rows = state.sitemap ? [{ ...state.sitemap, '@odata.etag': 'W/"2001"' }] : [];
+ const collection = /RetrieveUnpublishedMultiple/.test(where) || /\/sitemaps\?/.test(where);
+ return { status: 200, headers: { etag: 'W/"2001"' }, body: collection ? { value: rows } : (rows[0] || {}) };
+ }
+ if (/\/appmodules\/Microsoft\.Dynamics\.CRM\.RetrieveUnpublishedMultiple/.test(where)) return answer(state.app ? [appRow()] : []);
+ if (/\/appmodules\(/.test(where)) {
+ if (!state.published) return { status: 404, headers: {}, body: { error: { code: '0x80040217', message: 'Entity appmodule With Id Does Not Exist' } } };
+ return { status: 200, headers: { etag: 'W/"1001"' }, body: appRow() };
+ }
+ if (/\/appmodules/.test(where)) return answer(state.app && state.published ? [appRow()] : []);
+ if (/\/roles/.test(where)) return answer([{ roleid: ROLE_ID }]);
+ return answer([]);
+ },
+ post: async (url, body) => {
+ const where = decodeURIComponent(url);
+ state.requests.push({ verb: 'POST', url: where, body: JSON.stringify(body) });
+ if (/\/appmodules(\?|$)/.test(where)) {
+ state.app = { appmoduleid: body.appmoduleid, name: body.name, uniquename: body.uniquename };
+ return { status: 204, headers: { 'odata-entityid': `${ENV}/api/data/v9.0/appmodules(${body.appmoduleid})` }, body: undefined };
+ }
+ if (/\/sitemaps(\?|$)/.test(where)) {
+ state.sitemap = { sitemapid: body.sitemapid, sitemapnameunique: body.sitemapnameunique, sitemapxml: body.sitemapxml };
+ return { status: 201, headers: { etag: 'W/"2001"' }, body: { sitemapid: body.sitemapid, '@odata.etag': 'W/"2001"' } };
+ }
+ if (/PublishXml/.test(where) && state.app && JSON.stringify(body).includes(state.app.appmoduleid)) state.published = true;
+ return { status: 204, headers: {}, body: undefined };
+ },
+ patch: async () => ({ status: 204, headers: {}, body: undefined }),
+ delete: async () => ({ status: 204, headers: {}, body: undefined }),
+ put: async () => ({ status: 204, headers: {}, body: undefined }),
+ };
+ return { state, httpClient };
+}
+
+async function freshSdk() {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'opt-ins-'));
+ tempDirs.push(dir);
+ const { state, httpClient } = fakeOrg();
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: ENV, httpClient });
+ await sdk.initWorkspace();
+ return { sdk, state };
+}
+
+const publishRequests = (state) => state.requests.filter((r) => r.verb === 'POST' && /PublishXml/.test(r.url));
+
+test('an app created without `published` is published by the same push, and the by-name lookup then finds it', async () => {
+ const { sdk, state } = await freshSdk();
+ const def = appDefinition();
+ const created = await sdk.createArtifact('app', def);
+ const pushed = await sdk.pushArtifact('app', created.id);
+ assert.strictEqual(pushed.saved, true, JSON.stringify(pushed.error && pushed.error.message));
+ assert.strictEqual(pushed.publish.kind, 'submitted');
+ const publishes = publishRequests(state);
+ assert.strictEqual(publishes.length, 1, 'one publish, issued by the create');
+ assert.ok(publishes[0].body.includes(created.id), 'and it names the new app');
+ assert.strictEqual(await sdk.findArtifact('app', { uniqueName: def.uniqueName }), created.id);
+});
+
+test('`published: false` leaves a never-published draft that the by-name lookup does not see', async () => {
+ const { sdk, state } = await freshSdk();
+ const def = appDefinition();
+ const created = await sdk.createArtifact('app', { ...def, published: false });
+ const pushed = await sdk.pushArtifact('app', created.id);
+ assert.strictEqual(pushed.saved, true, JSON.stringify(pushed.error && pushed.error.message));
+ assert.strictEqual(pushed.publish.kind, 'notRequested', 'nothing publishes the app: a build without --publish would leave it a draft');
+ assert.deepStrictEqual(publishRequests(state), []);
+ // findArtifact is what the build's app-existence probe uses. If it ever sees a draft, every other probe still
+ // has to be draft-aware (collision gate, sitemap and navigation reads, verify, download) before the option is
+ // worth turning on — see "Vendored SDK" in plugins/model-apps/AGENTS.md.
+ assert.strictEqual(await sdk.findArtifact('app', { uniqueName: def.uniqueName }), null, 'the draft is invisible to the by-name lookup');
+ const listed = await sdk.resolveArtifact('app', { uniqueName: def.uniqueName });
+ assert.deepStrictEqual(listed.map((app) => app.id), [created.id], 'only the draft-aware listing finds it, which is what teardown uses');
+});
+
+test('the plugin creates every app published: its app definition leaves `published` unset and no script sets it to false', () => {
+ assert.ok(!('published' in appDefinition()), 'appDef must not carry `published`');
+ assert.deepStrictEqual(scriptsMatching(/\bpublished\s*:\s*false\b/), [], 'a script creates a draft app, which its own probes cannot see');
+});
diff --git a/plugins/model-apps/scripts/tests/sdk-resend-layers.test.js b/plugins/model-apps/scripts/tests/sdk-resend-layers.test.js
new file mode 100644
index 000000000..d0c016524
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/sdk-resend-layers.test.js
@@ -0,0 +1,457 @@
+'use strict';
+// Two layers re-send a request that failed for a reason the platform says is transient: the plugin's HTTP client
+// (lib/sdk-http-client.js) and the vendored SDK itself. They sit one above the other, so what a request costs when
+// BOTH apply is the product of their attempts — which is why each layer's trigger is pinned here against the real
+// bundle, driven through the plugin's real client over a fake transport, with the requests counted.
+//
+// What the bundle re-sends: a request that lost a SQL deadlock, for reads, an app create, PublishXml, a form
+// create, a view create, a publisher create and each delete of a row-summary removal (there a 400 that quotes SQL's
+// deadlock-victim message counts as well as the platform's own 500); and an app DELETE that raced the platform's
+// search-index insert (SQL 547 on the AppModule_DVTableSearch_M365AppModuleId constraint). What the client
+// re-sends: any request answered 429/5xx that is neither a record delete nor a $batch, and — for a record delete
+// or a conditional-delete $batch only — a deadlock victim or a throttle.
+//
+// - An app DELETE has two disjoint triggers: the client re-sends 500/1205, the SDK re-sends 400/547. No single
+// answer is both, so they add; they cannot multiply on one condition.
+// - A create POST is re-sent by the client first (it re-sends every 5xx), so the SDK's own deadlock re-send
+// never fires for a deadlock the client clears: one deadlock costs one re-send in all.
+// - A row-summary DELETE is re-sent by the client for a 500/1205 and by the SDK for that or for a 400 quoting
+// the deadlock: one that clears costs one re-send in all, one that never clears is bounded by the product.
+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 { createAzHttpClient } = require('../lib/sdk-http-client.js');
+const { KIND_HANDLERS, deleteStep, runTeardown } = require('../lib/sdk-teardown.js');
+
+const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
+const ENV = 'https://contoso.crm.dynamics.com';
+const APP_ID = '11111111-1111-1111-1111-111111111111';
+const APP_UNIQUE_ID = '22222222-2222-2222-2222-222222222222';
+const SITEMAP_ID = '33333333-3333-3333-3333-333333333333';
+const APP_UNIQUE = 'co_supportdesk';
+const FORM_ID = '44444444-4444-4444-4444-444444444444';
+const SKILL_ID = '55555555-5555-5555-5555-555555555555';
+const MODEL_ID = '66666666-6666-6666-6666-666666666666';
+const TEMPLATE_ID = '77777777-7777-7777-7777-777777777777';
+
+const tempDirs = [];
+test.after(() => { for (const d of tempDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+// The change-set answers the platform gives to the app delete's `$batch` (the SDK sends the appmodule and its
+// sitemap as one atomic change set; only a FAILED operation is answered when it rolls back):
+// --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 400 Bad Request
+// Content-Type: application/json; odata.metadata=minimal
+//
+// {"error":{"code":"0x80048d21","message":"… REFERENCE constraint \"AppModule_DVTableSearch_M365AppModuleId\" … Sql Number: 547"}}
+// --changesetresponse_x--
+// --batchresponse_x--
+const REASONS = { 204: 'No Content', 400: 'Bad Request', 500: 'Internal Server Error' };
+function changeSet(parts) {
+ const lines = ['--batchresponse_x', 'Content-Type: multipart/mixed; boundary=changesetresponse_x', ''];
+ for (const part of parts) {
+ lines.push('--changesetresponse_x', 'Content-Type: application/http', 'Content-Transfer-Encoding: binary', `Content-ID: ${part.id}`, '', `HTTP/1.1 ${part.status} ${REASONS[part.status]}`);
+ if (part.error) lines.push('Content-Type: application/json; odata.metadata=minimal', '', JSON.stringify({ error: part.error }));
+ else lines.push('');
+ }
+ lines.push('--changesetresponse_x--', '--batchresponse_x--', '');
+ return lines.join('\r\n');
+}
+const SEARCH_INDEX_RACE = { code: '0x80048d21', message: 'The DELETE statement conflicted with the REFERENCE constraint "AppModule_DVTableSearch_M365AppModuleId". The conflict occurred in database "org", table "dbo.DVTableSearchBase", column \'M365AppModuleId\'. Sql Number: 547' };
+const DEADLOCK = { code: '0x80044150', message: ' Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205' };
+const raced = () => ({ statusCode: 400, headers: {}, body: changeSet([{ id: 1, status: 400, error: SEARCH_INDEX_RACE }]) });
+const deadlocked = () => ({ statusCode: 500, headers: {}, body: changeSet([{ id: 1, status: 500, error: DEADLOCK }]) });
+const deleted = () => ({ statusCode: 200, headers: {}, body: changeSet([{ id: 1, status: 204 }, { id: 2, status: 204 }]) });
+
+const json = (statusCode, body, headers = {}) => ({ statusCode, headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body) });
+
+// A transport that models the two-row app for deleteAppCascade, and answers each `$batch` from `script` in turn
+// (the last entry repeats). `sleeps` records the client's own back-off waits.
+function appOrg(script) {
+ const requests = [];
+ let batches = 0;
+ async function request({ url, method }) {
+ const u = new URL(url);
+ const where = decodeURIComponent(u.pathname + u.search);
+ requests.push({ method, path: where });
+ if (method === 'POST' && /\/\$batch$/.test(u.pathname)) {
+ const answer = script[Math.min(batches, script.length - 1)];
+ batches += 1;
+ return typeof answer === 'function' ? answer() : answer;
+ }
+ const meta = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(where);
+ if (meta) return json(200, { LogicalName: meta[1], EntitySetName: `${meta[1]}s` });
+ if (/\/appmodules\([^)]+\)/.test(where)) return json(200, { appmoduleid: APP_ID, appmoduleidunique: APP_UNIQUE_ID, uniquename: APP_UNIQUE, name: 'Support Desk', '@odata.etag': 'W/"1001"' }, { etag: 'W/"1001"' });
+ if (/\/sitemaps\([^)]+\)/.test(where)) return json(200, { '@odata.etag': 'W/"2002"', sitemapid: SITEMAP_ID }, { etag: 'W/"2002"' });
+ if (where.includes('/sitemaps')) return json(200, { value: [{ '@odata.etag': 'W/"2003"', sitemapid: SITEMAP_ID, sitemapnameunique: APP_UNIQUE, sitemapxml: '<SiteMap></SiteMap>' }] });
+ return json(200, { value: [] });
+ }
+ return { request, requests, batchPosts: () => requests.filter((r) => r.method === 'POST' && /\$batch/.test(r.path)).length };
+}
+
+async function sdkOver(request, sleeps = []) {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'resend-'));
+ tempDirs.push(dir);
+ const client = createAzHttpClient(ENV, { getToken: () => 'token', request, sleep: async (ms) => { sleeps.push(ms); } });
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: ENV, httpClient: client });
+ await sdk.initWorkspace();
+ return sdk;
+}
+
+// The bundle waits between its own re-sends with setTimeout (1 s, 2 s, 4 s). Mocked, so a persistent failure
+// costs the test no real seconds; the plugin's client waits through the `sleep` it was handed. The loop is bounded
+// by wall time, not by turns of the event loop: the local file writes that follow a request take real time, and a
+// fixed number of `setImmediate` turns can pass before they finish.
+async function settle(t, promise) {
+ let state = 'pending';
+ let value;
+ let error;
+ promise.then((v) => { state = 'resolved'; value = v; }, (e) => { state = 'rejected'; error = e; });
+ const deadline = Date.now() + 20000;
+ while (state === 'pending' && Date.now() < deadline) {
+ await new Promise((resolve) => setImmediate(resolve));
+ t.mock.timers.tick(10000);
+ }
+ if (state === 'pending') throw new Error('the call never settled');
+ if (state === 'rejected') throw error;
+ return value;
+}
+
+// --- an app delete -----------------------------------------------------------------------------------
+
+test('an app delete that races the search-index insert is re-sent by the SDK once, and the client adds nothing', async (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const sleeps = [];
+ const org = appOrg([raced, deleted]);
+ const sdk = await sdkOver(org.request, sleeps);
+ const result = await settle(t, sdk.deleteAppCascade(APP_ID, APP_UNIQUE_ID));
+ assert.ok(result.success, JSON.stringify(result.failures));
+ assert.strictEqual(org.batchPosts(), 2, 'the refused change set and its one re-send');
+ assert.deepStrictEqual(sleeps, [], 'the client re-sends neither the race (a 400) nor anything else here');
+});
+
+test('a persistent search-index race costs four change sets in all — the SDK\u2019s three re-sends, never four times four', async (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const sleeps = [];
+ const org = appOrg([raced]);
+ const sdk = await sdkOver(org.request, sleeps);
+ await assert.rejects(settle(t, sdk.deleteAppCascade(APP_ID, APP_UNIQUE_ID)));
+ assert.strictEqual(org.batchPosts(), 4);
+ assert.deepStrictEqual(sleeps, []);
+});
+
+test('a deadlock on the same change set is the client\u2019s to re-send: the SDK never sees it, and it is re-sent once', async (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const sleeps = [];
+ const org = appOrg([deadlocked, deleted]);
+ const sdk = await sdkOver(org.request, sleeps);
+ const result = await settle(t, sdk.deleteAppCascade(APP_ID, APP_UNIQUE_ID));
+ assert.ok(result.success);
+ assert.strictEqual(org.batchPosts(), 2);
+ assert.deepStrictEqual(sleeps, [1000], 'the client\u2019s own first back-off, and no SDK wait on top of it');
+});
+
+test('a persistent deadlock costs four change sets: the client\u2019s three re-sends, and the SDK adds none', async (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const sleeps = [];
+ const org = appOrg([deadlocked]);
+ const sdk = await sdkOver(org.request, sleeps);
+ await assert.rejects(settle(t, sdk.deleteAppCascade(APP_ID, APP_UNIQUE_ID)));
+ assert.strictEqual(org.batchPosts(), 4);
+ assert.deepStrictEqual(sleeps, [1000, 2000, 4000]);
+});
+
+test('the two triggers add: a race, then a deadlock, then success is three change sets', async (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const org = appOrg([raced, deadlocked, deleted]);
+ const sdk = await sdkOver(org.request);
+ const result = await settle(t, sdk.deleteAppCascade(APP_ID, APP_UNIQUE_ID));
+ assert.ok(result.success);
+ assert.strictEqual(org.batchPosts(), 3);
+});
+
+// --- a create ----------------------------------------------------------------------------------------
+
+// A form create is POSTed to /systemforms. The client re-sends any 5xx on it, so a deadlock the client clears
+// never reaches the SDK's own re-send.
+function formOrg(answers) {
+ const requests = [];
+ let posts = 0;
+ async function request({ url, method, body }) {
+ const u = new URL(url);
+ requests.push({ method, path: u.pathname });
+ if (method === 'POST' && /\/systemforms$/.test(u.pathname)) {
+ const answer = answers[Math.min(posts, answers.length - 1)];
+ posts += 1;
+ if (answer === 'deadlock') return json(500, { error: DEADLOCK });
+ return { statusCode: 204, headers: { 'odata-entityid': `${ENV}/api/data/v9.0/systemforms(${JSON.parse(body).formid})` }, body: '' };
+ }
+ return json(200, { value: [] });
+ }
+ return { request, posts: () => requests.filter((r) => r.method === 'POST').length };
+}
+
+const mainForm = { name: 'Account form', entityLogicalName: 'account', formType: 'Main', status: 'Active' };
+
+test('one deadlock on a form create costs one re-send in all: the client\u2019s, not the SDK\u2019s', async (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const sleeps = [];
+ const org = formOrg(['deadlock', 'ok']);
+ const sdk = await sdkOver(org.request, sleeps);
+ const art = await sdk.createArtifact('form', mainForm);
+ const pushed = await settle(t, sdk.pushArtifact('form', art.id));
+ assert.strictEqual(pushed.saved, true);
+ assert.strictEqual(org.posts(), 2);
+ assert.strictEqual(sleeps.length, 1, 'one client back-off; the SDK\u2019s 1 s wait never happened');
+});
+
+test('a form create that deadlocks every time stays bounded: the client\u2019s attempts times the SDK\u2019s, and no more', async (t) => {
+ // The layers do stack here — the client re-sends every 5xx, and the SDK re-sends a deadlock on this POST — so a
+ // deadlock that never clears is attempted up to (client attempts 6) x (SDK attempts 4). It is a ceiling on a
+ // pathological case, not what a deadlock costs: one that clears is the previous test.
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const org = formOrg(['deadlock']);
+ const sdk = await sdkOver(org.request);
+ const art = await sdk.createArtifact('form', mainForm);
+ await settle(t, sdk.pushArtifact('form', art.id)).catch(() => undefined);
+ assert.ok(org.posts() <= 6 * 4, `${org.posts()} attempts`);
+ assert.ok(org.posts() > 6, 'and the SDK\u2019s re-send is what takes it past the client\u2019s own six');
+});
+
+// A view create is POSTed to /savedqueries, after one read of the table's ObjectTypeCode (the grid `object`
+// attribute a from-scratch layout lacks). The bundle re-sends it on a deadlock, as it does a form create; the
+// client re-sends every 5xx on it too, so the two layers stack here exactly as they do on a form.
+function viewOrg(answers) {
+ const requests = [];
+ let posts = 0;
+ async function request({ url, method, body }) {
+ const u = new URL(url);
+ requests.push({ method, path: u.pathname });
+ if (method === 'POST' && /\/savedqueries$/.test(u.pathname)) {
+ const answer = answers[Math.min(posts, answers.length - 1)];
+ posts += 1;
+ if (answer === 'deadlock') return json(500, { error: DEADLOCK });
+ return { statusCode: 204, headers: { 'odata-entityid': `${ENV}/api/data/v9.0/savedqueries(${JSON.parse(body).savedqueryid})` }, body: '' };
+ }
+ if (method === 'GET' && /EntityDefinitions\(LogicalName='account'\)/.test(decodeURIComponent(u.pathname))) return json(200, { ObjectTypeCode: 1 });
+ return json(200, { value: [] });
+ }
+ return { request, posts: () => requests.filter((r) => r.method === 'POST').length };
+}
+
+// The shape the build's viewDef gives a view.
+const activeAccounts = {
+ name: 'Active accounts', description: '', entityLogicalName: 'account', queryType: 0, isDefault: false,
+ columns: [{ name: 'name', width: 100, order: 0 }],
+ filters: { type: 'and', conditions: [{ attribute: 'statecode', operator: 'eq', value: '0' }], groups: [] },
+ sort: [],
+};
+
+test('one deadlock on a view create costs one re-send in all: the client\u2019s, not the SDK\u2019s', async (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const sleeps = [];
+ const org = viewOrg(['deadlock', 'ok']);
+ const sdk = await sdkOver(org.request, sleeps);
+ const art = await sdk.createArtifact('view', activeAccounts);
+ const pushed = await settle(t, sdk.pushArtifact('view', art.id));
+ assert.strictEqual(pushed.saved, true);
+ assert.strictEqual(org.posts(), 2);
+ assert.strictEqual(sleeps.length, 1, 'one client back-off; the SDK\u2019s 1 s wait never happened');
+});
+
+test('a view create that deadlocks every time stays bounded: the client\u2019s attempts times the SDK\u2019s, and no more', async (t) => {
+ // A bundle that did not re-send a view create would stop at the client's six; this one takes it past them.
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const org = viewOrg(['deadlock']);
+ const sdk = await sdkOver(org.request);
+ const art = await sdk.createArtifact('view', activeAccounts);
+ await settle(t, sdk.pushArtifact('view', art.id)).catch(() => undefined);
+ assert.ok(org.posts() <= 6 * 4, `${org.posts()} attempts`);
+ assert.ok(org.posts() > 6, 'and the SDK\u2019s re-send is what takes it past the client\u2019s own six');
+});
+
+// --- the SDK's kind check on a form or dashboard delete ----------------------------------------------
+
+// `deleteRemoteArtifact('form' | 'dashboard')` reads the row's type before it deletes, and refuses another kind:
+// GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=type
+function typeOrg(type) {
+ const requests = [];
+ async function request({ url, method }) {
+ const u = new URL(url);
+ const where = decodeURIComponent(u.pathname + u.search);
+ requests.push({ method, path: where });
+ if (method === 'GET' && /\/systemforms\([^)]+\)\/Microsoft\.Dynamics\.CRM\.RetrieveUnpublished\(\)/.test(where)) return json(200, { formid: FORM_ID, type });
+ if (method === 'DELETE') return { statusCode: 204, headers: {}, body: '' };
+ return json(200, { value: [] });
+ }
+ return { request, requests, deletes: () => requests.filter((r) => r.method === 'DELETE') };
+}
+
+test('a form delete reads the row\u2019s kind first — one extra GET — and then deletes it', async () => {
+ const org = typeOrg(2);
+ const sdk = await sdkOver(org.request);
+ await sdk.deleteRemoteArtifact('form', FORM_ID);
+ assert.deepStrictEqual(org.requests.map((r) => r.method), ['GET', 'DELETE']);
+ assert.match(org.requests[0].path, /RetrieveUnpublished\(\)\?\$select=type/);
+});
+
+test('teardown reports a refused kind as a failed step with the SDK\u2019s own words, and deletes nothing', async () => {
+ // The plugin resolves a form by (table, name, TYPE) and a pinned dashboard by type, so a wrong kind should
+ // not reach the SDK; this is the second line, for an id that changed kind or was pinned wrongly. The step
+ // must fail loudly (not skip, not read as already gone) so the operator sees which id to correct.
+ const org = typeOrg(5);
+ const sdk = await sdkOver(org.request);
+ const hybrid = {
+ resolveArtifact: async () => [],
+ queryRecords: async (set) => (set === 'systemform' ? [{ formid: FORM_ID }] : []),
+ deleteRemoteArtifact: (type, id) => sdk.deleteRemoteArtifact(type, id),
+ deleteSolution: async () => {},
+ };
+ const spec = {
+ solution: { uniqueName: 'Contoso', publisherPrefix: 'co' },
+ app: { name: 'Support Desk' },
+ entities: [{ schemaName: 'account', primaryAttribute: { schemaName: 'name' }, columns: [], existing: true }],
+ forms: [{ entity: 'account', name: 'Mobile', formType: 'Main' }],
+ };
+ const events = [];
+ const result = await runTeardown(spec, { apply: true }, { sdk: hybrid, emit: (e) => events.push(e) });
+
+ assert.strictEqual(result.ok, false);
+ const failure = result.errors.find((e) => /^form /.test(e.step));
+ assert.ok(failure, JSON.stringify(result.errors));
+ assert.match(failure.message, /Refusing to delete systemform '4{8}-4{4}-4{4}-4{4}-4{12}' as a form: it is a mobile express form \(type 5\)\. Nothing was changed\. Check the id\./);
+ assert.ok(events.some((e) => e.status === 'error' && /^form /.test(e.label) && /Refusing to delete systemform/.test(e.detail)), 'the step prints it, where the operator reads the run');
+ assert.deepStrictEqual(org.deletes(), [], 'no DELETE was sent for the row');
+ assert.ok(!(result.deleted.form || []).length);
+});
+
+test('a refused kind is a failure for dashboards too, and is never read as "already gone"', async () => {
+ const org = typeOrg(2); // a Main form's id, pinned as a dashboard
+ const sdk = await sdkOver(org.request);
+ await assert.rejects(
+ () => deleteStep(sdk, KIND_HANDLERS.dashboard, [{ id: FORM_ID, name: 'Operations' }]),
+ (err) => {
+ assert.strictEqual(err.code, 'SYSTEMFORM_KIND_MISMATCH');
+ assert.match(err.message, /as a dashboard: it is a Main form \(type 2\)/);
+ return true;
+ }
+ );
+ assert.deepStrictEqual(org.deletes(), []);
+});
+
+// --- a row-summary removal ---------------------------------------------------------------------------
+
+// The teardown's aiSummary step calls `removeRowSummary` for each table and treats a failure as best-effort. The
+// bundle reads the skill row, then the model it points at and the template that model must be built from, before it
+// deletes anything:
+// GET /aiskillconfigs?$select=aiskillconfigid,_aimodel_value&$filter=uniquename eq 'ais_RowSummary_account'&$top=1
+// GET /msdyn_aimodels(<model>)?$select=msdyn_name,_msdyn_templateid_value
+// GET /msdyn_aitemplates?$select=msdyn_aitemplateid&$filter=msdyn_uniquename eq 'GptPowerPrompt'&$top=1
+// and then DELETEs the skill row, and the model when it is the one the bundle created. `skill` and `model` script the
+// answers to those two DELETEs in turn (the last repeats).
+const IN_USE = { code: '0x8004f01f', message: 'Cannot delete the AI model because another component still uses it.' };
+// A plugin's wrapping of SQL's own message: HTTP 400, no `Sql Number`.
+const WRAPPED_DEADLOCK = { code: '0x80040265', message: 'Exception output:: System.Data.SqlClient.SqlException (0x80131904): Transaction (Process ID 61) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.' };
+const ANSWERS = {
+ deleted: () => ({ statusCode: 204, headers: {}, body: '' }),
+ inUse: () => json(400, { error: IN_USE }),
+ wrappedDeadlock: () => json(400, { error: WRAPPED_DEADLOCK }),
+ deadlock: () => json(500, { error: DEADLOCK }),
+ refused: () => json(400, { error: { code: '0x80040265', message: 'The operation was refused.' } }),
+};
+
+function summaryOrg({ skill = ['deleted'], model = ['deleted'] } = {}) {
+ const requests = [];
+ const sent = { skill: 0, model: 0 };
+ const next = (script, key) => {
+ const answer = script[Math.min(sent[key], script.length - 1)];
+ sent[key] += 1;
+ return ANSWERS[answer]();
+ };
+ async function request({ url, method }) {
+ const u = new URL(url);
+ const where = decodeURIComponent(u.pathname + u.search);
+ requests.push({ method, path: where });
+ if (method === 'DELETE' && /\/aiskillconfigs\(/.test(where)) return next(skill, 'skill');
+ if (method === 'DELETE' && /\/msdyn_aimodels\(/.test(where)) return next(model, 'model');
+ if (method === 'GET' && /\/aiskillconfigs\?/.test(where)) return json(200, { value: [{ aiskillconfigid: SKILL_ID, _aimodel_value: MODEL_ID }] });
+ if (method === 'GET' && /\/msdyn_aimodels\(/.test(where)) return json(200, { msdyn_name: 'account row summary', _msdyn_templateid_value: TEMPLATE_ID });
+ if (method === 'GET' && /\/msdyn_aitemplates\?/.test(where)) return json(200, { value: [{ msdyn_aitemplateid: TEMPLATE_ID }] });
+ // The read-back after a delete that failed: the row is still there.
+ if (method === 'GET' && /\/aiskillconfigs\(/.test(where)) return json(200, { aiskillconfigid: SKILL_ID });
+ return json(200, { value: [] });
+ }
+ const deletes = (kind) => requests.filter((r) => r.method === 'DELETE' && r.path.includes(kind));
+ return { request, requests, deletes, skillDeletes: () => deletes('/aiskillconfigs(').length };
+}
+
+const removeAccountSummary = (sdk) => sdk.removeRowSummary({ entityLogicalName: 'account' });
+
+test('a row summary is removed skill row first, then its model, each once', async () => {
+ const org = summaryOrg();
+ const sdk = await sdkOver(org.request);
+ await removeAccountSummary(sdk);
+ assert.deepStrictEqual(org.requests.filter((r) => r.method === 'DELETE').map((r) => r.path.replace(/^\/api\/data\/v9\.\d\//, '').replace(/\([^)]+\)/, '(id)')),
+ ['aiskillconfigs(id)', 'msdyn_aimodels(id)']);
+});
+
+test('a model another component still uses is kept, and the removal still succeeds', async () => {
+ // The platform refuses to delete a model a component references (HTTP 400, 0x8004f01f). Deleting the skill row first
+ // is what lets the table be deleted; the model is shared, so it stays — a removal that threw here would fail the
+ // teardown step of every table whose model another component had adopted.
+ const org = summaryOrg({ model: ['inUse'] });
+ const sdk = await sdkOver(org.request);
+ await removeAccountSummary(sdk);
+ assert.strictEqual(org.deletes('/aiskillconfigs(').length, 1);
+ assert.strictEqual(org.deletes('/msdyn_aimodels(').length, 1, 'the model delete was tried once and its refusal accepted');
+ assert.strictEqual(org.requests[org.requests.length - 1].method, 'DELETE', 'nothing is read back: the refusal is the answer');
+});
+
+test('a refused skill-row delete is reported, and the model is left alone', async () => {
+ const org = summaryOrg({ skill: ['refused'] });
+ const sdk = await sdkOver(org.request);
+ await assert.rejects(() => removeAccountSummary(sdk), /refused|400/i);
+ assert.strictEqual(org.skillDeletes(), 1, 'not a deadlock: neither layer re-sends it');
+ assert.deepStrictEqual(org.deletes('/msdyn_aimodels('), [], 'the model is removed only once the skill row is');
+});
+
+test('a skill-row delete that loses a deadlock as a 400 is re-sent by the SDK once, and the client adds nothing', async (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const sleeps = [];
+ const org = summaryOrg({ skill: ['wrappedDeadlock', 'deleted'] });
+ const sdk = await sdkOver(org.request, sleeps);
+ await settle(t, removeAccountSummary(sdk));
+ assert.strictEqual(org.skillDeletes(), 2);
+ assert.deepStrictEqual(sleeps, [], 'a 400 is not the client\u2019s to re-send');
+});
+
+test('a skill-row delete that loses a deadlock as a 500 is the client\u2019s to re-send, and it is re-sent once in all', async (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const sleeps = [];
+ const org = summaryOrg({ skill: ['deadlock', 'deleted'] });
+ const sdk = await sdkOver(org.request, sleeps);
+ await settle(t, removeAccountSummary(sdk));
+ assert.strictEqual(org.skillDeletes(), 2);
+ assert.deepStrictEqual(sleeps, [1000], 'the client\u2019s own first back-off, and no SDK wait on top of it');
+});
+
+test('a skill-row delete that deadlocks every time stays bounded: the client\u2019s four attempts per SDK attempt, and no more', async (t) => {
+ // Both layers act on a 500/1205, so a deadlock that never clears is attempted up to 4 (client) x 4 (SDK) times.
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const org = summaryOrg({ skill: ['deadlock'] });
+ const sdk = await sdkOver(org.request);
+ await assert.rejects(settle(t, removeAccountSummary(sdk)));
+ assert.ok(org.skillDeletes() <= 4 * 4, `${org.skillDeletes()} attempts`);
+ assert.ok(org.skillDeletes() > 4, 'and the SDK\u2019s re-send is what takes it past the client\u2019s own four');
+ assert.deepStrictEqual(org.deletes('/msdyn_aimodels('), [], 'the model is never touched while the skill row stands');
+});
diff --git a/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js b/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js
index b03c52435..9824c857b 100644
--- a/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js
@@ -40,6 +40,9 @@ const SKILL_SDK_SURFACE = [
'createAlternateKey',
'createArtifact',
'createColumn',
+ // A new table's ordinary columns follow the table in ONE atomic change set (entity-provision.js), which needs the
+ // transport's `postRaw` (lib/sdk-http-client.js); a refusal falls back to `createColumn` per column.
+ 'createColumns',
'createCustomerColumn',
'createGlobalOptionSet',
'createPersonaRole',
@@ -57,6 +60,9 @@ const SKILL_SDK_SURFACE = [
'deleteSolution',
'deleteTable',
'deleteWebResource',
+ // A reconcile pushes an artifact only when its workspace copy differs from the last-synced snapshot
+ // (unsynced-edits.js). The check fails open: without this method the engine writes as it always did.
+ 'diffArtifact',
'disassociateRecords',
'enrichDefaultViews',
'fetchArtifact',
@@ -68,6 +74,13 @@ const SKILL_SDK_SURFACE = [
'getArtifact',
'getColumnVisualization',
'getEntityPrivileges',
+ // `scripts/list-languages.js` reads the environment's languages (the planner's language detection, in place of
+ // `pac model list-languages`): LCIDs only — three GETs, no workspace — and maps them to culture codes itself.
+ 'getEnvironmentLanguages',
+ // The dry run's read-only question to the app folder's workspace (workspaceBindingNote in lib/workspace-binding.js): which
+ // environment it belongs to. It reads manifest.json and nothing else — unlike `listArtifacts`, which also parses every
+ // saved copy it lists.
+ 'getManifest',
'getSolution',
'initWorkspace',
'insertStatusValue',
diff --git a/plugins/model-apps/scripts/tests/sdk-uptake-contract.test.js b/plugins/model-apps/scripts/tests/sdk-uptake-contract.test.js
index 02ccd0fcd..150cc37ce 100644
--- a/plugins/model-apps/scripts/tests/sdk-uptake-contract.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-uptake-contract.test.js
@@ -9,6 +9,9 @@
// 1. App icon is now REQUIRED and must be an IMAGE (the behaviour that broke 13 tests on uptake).
// 2. Business-rule authoring, which was previously impossible on our tenants: supported bound
// member first, classic WWF-XAML `workflows` row as a NARROW fallback.
+// 3. The AI setting names the build writes, compared with the bundle's own maps.
+// 4. Exactly one write path for a business rule, so a double write cannot recur.
+// 5. Metadata reads send `Consistency: Strong` (the latest definition), end to end through the plugin client.
const test = require('node:test');
const assert = require('node:assert');
const os = require('node:os');
@@ -415,3 +418,40 @@ test('REAL BUNDLE: the deleted fallback leaves no trace in the bundle', async ()
assert.ok(!src.includes('x:Null x:Key="Parameters"'),
'the business-rule XAML compiler\'s null-parameter emission is back — the fallback has been reintroduced');
});
+
+// ---------------------------------------------------------------------------------------------
+// 5. A metadata read asks for the LATEST definition.
+//
+// The platform caches metadata, and a read right after a metadata write can be served the definition from
+// before it. The SDK now sends `Consistency: Strong` on every read of /EntityDefinitions, /RelationshipDefinitions
+// and /GlobalOptionSetDefinitions (about 10% more per read) and on no other path. The plugin's HTTP client forwards
+// a caller's headers untouched, so the header reaches the wire; it is pinned end to end because a client that
+// rebuilt its headers would turn the fix off without a single other test noticing.
+test('REAL BUNDLE: a metadata read reaches the wire with Consistency: Strong through the plugin client, and a data read does not', async () => {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const { createAzHttpClient } = require('../lib/sdk-http-client.js');
+ const ENV = 'https://contoso.crm.dynamics.com';
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'uptake-'));
+ dirs.push(dir);
+ const seen = [];
+ const request = async ({ url, method, headers }) => {
+ const where = decodeURIComponent(new URL(url).pathname);
+ seen.push({ method, path: where, headers });
+ const body = /EntityDefinitions\(LogicalName='savedquery'\)/.test(where) ? { LogicalName: 'savedquery', EntitySetName: 'savedqueries' } : { value: [] };
+ return { statusCode: 200, headers: {}, body: JSON.stringify(body) };
+ };
+ const client = createAzHttpClient(ENV, { getToken: () => 'token', request, sleep: async () => {} });
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: ENV, httpClient: client });
+ await sdk.initWorkspace();
+
+ await sdk.findTables('account', { top: 5 });
+ await sdk.queryRecords('savedquery', { select: ['savedqueryid'], top: 1 });
+
+ const metadata = seen.find((r) => /\/EntityDefinitions$/.test(r.path));
+ assert.ok(metadata, 'a table search reads /EntityDefinitions; got ' + JSON.stringify(seen.map((r) => r.path)));
+ assert.strictEqual(metadata.headers.Consistency, 'Strong');
+ const data = seen.find((r) => /\/savedqueries$/.test(r.path));
+ assert.ok(data, 'a record query reads /savedqueries; got ' + JSON.stringify(seen.map((r) => r.path)));
+ assert.strictEqual(Object.keys(data.headers).some((h) => h.toLowerCase() === 'consistency'), false,
+ 'a read of any other path is passed through untouched');
+});
diff --git a/plugins/model-apps/scripts/tests/sitemap-pages.test.js b/plugins/model-apps/scripts/tests/sitemap-pages.test.js
index 7c81d94dd..57da614b8 100644
--- a/plugins/model-apps/scripts/tests/sitemap-pages.test.js
+++ b/plugins/model-apps/scripts/tests/sitemap-pages.test.js
@@ -7,6 +7,8 @@ const GP_OVERVIEW = '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8';
const GP_DETAIL = '5c0a4889-45fd-46ea-91a8-ff876914d644';
const APP_UNIQUE_VALUE = 'c0ffee00-0000-4000-8000-00000000dddd';
const SITEMAP_ID = '5111e0f2-0000-4000-8000-0000000000aa';
+// The answer to the list of apps that were never published when there are none (see the scanEnv section below).
+const NO_DRAFT_APPS = { status: 200, body: { value: [] } };
// A realistic sitemap: two GenPage subareas (one Title carries an XML entity), an entity subarea, a Url decoy GUID.
const XML = [
@@ -267,6 +269,8 @@ test('fetchAppsForPages: an id in TWO apps sitemaps is reported under both (Imp5
}
return [];
},
+ // The saved layer of every sitemap, in one read: nothing is pending here, so each app's current row is its published one. No app has never been published.
+ dataverse: { get: async (url) => (url.startsWith('/appmodules/') ? NO_DRAFT_APPS : { status: 200, body: { value: Object.entries(smXmlById).map(([sitemapid, sitemapxml]) => ({ sitemapid, sitemapxml, componentstate: 0 })) } }) },
};
const r = await fetchAppsForPages(sdk, [GP_OVERVIEW]);
assert.strictEqual(r.ok, true);
@@ -308,6 +312,7 @@ test('fetchAppsForPages enumerates with paginate:true and NO top — the complet
if (entity === 'sitemap') return [{ sitemapxml: `<SiteMap><Area><Group><SubArea GenPageId="${GP_OVERVIEW}"/></Group></Area></SiteMap>` }];
return [];
},
+ dataverse: { get: async (url) => (url.startsWith('/appmodules/') ? NO_DRAFT_APPS : { status: 200, body: { value: [{ sitemapid: 'sm', sitemapxml: `<SiteMap><Area><Group><SubArea GenPageId="${GP_OVERVIEW}"/></Group></Area></SiteMap>`, componentstate: 0 }] } }) },
};
const r = await fetchAppsForPages(sdk, [GP_OVERVIEW]);
assert.strictEqual(r.ok, true, 'a large/complete list no longer halts — pagination covers it');
@@ -349,9 +354,468 @@ test('fetchAppsForPages records (does not fail on) an app whose sitemap is unrea
if (entity === 'appmodulecomponent') return [];
return [];
},
+ // The only Dataverse read left is the list of apps that were never published: there are none, and the saved layer has nobody to be joined to.
+ dataverse: { get: async (url) => { assert.ok(url.startsWith('/appmodules/'), url); return NO_DRAFT_APPS; } },
};
const r = await fetchAppsForPages(sdk, [GP_OVERVIEW]);
assert.strictEqual(r.ok, true);
assert.deepStrictEqual(r.unreadable, ['app-b']);
assert.strictEqual(r.byId.size, 0);
});
+
+// ── The other apps' SAVED (current, unpublished) navigation ───────────────────────────────────────────────────────────────────
+// A page another app has saved into its navigation but not published is that app's page as much as one it published: the shared-page
+// scan has to see it, or an UPDATE rewrites a page the other app is about to show. The saved layer is read for ALL other apps in ONE
+// request — the `sitemap` collection's RetrieveUnpublishedMultiple, https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/retrieveunpublishedmultiple —
+// and matched to each app by the sitemap id its published read found. Unreadable means unproven: the scan fails closed exactly as the published read does.
+const SAVED_URL = '/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapxml,componentstate,sitemapnameunique';
+// The list of apps that were never published: the `appmodule` collection's RetrieveUnpublishedMultiple, one request. It answers with every app's CURRENT layer — a published app with nothing
+// pending has one row (componentstate 0), one with a pending edit has two (the published row, and the draft with a layer key of its own), and an app that was never published has one
+// (componentstate 1) — and the published `appmodule` list has no row for that last kind at all.
+const APPS_URL = '/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,uniquename,componentstate';
+const smId = (i) => `5111e0f2-0000-4000-8000-${String(i).padStart(12, '0')}`;
+const layerKey = (i) => `c0ffee00-0000-4000-8000-${String(i).padStart(12, '0')}`;
+const withPage = (...ids) => `<SiteMap><Area><Group>${ids.map((id, i) => `<SubArea Id="p${i}" GenPageId="${id}" Title="Page ${i}"/>`).join('')}</Group></Area></SiteMap>`;
+
+// An environment of `apps` ([{ name, published, saved }]): `published` is the app's published sitemap XML; `saved` is its saved layer —
+// undefined when nothing is pending (the platform answers with the one published row), an XML string for a pending draft (it answers
+// with both layers), or `{ rows }` for rows given verbatim. `savedPages(url)` overrides the response to the saved read, whole, and `appList(url)` the one to the
+// list of apps that were never published.
+// `drafts` ([{ name, saved }]) are apps that were NEVER published: the published list has no row for them, the list of apps has one, their sitemap component hangs off their layer key
+// and their saved sitemap is `saved`. A draft may set `rows` (its rows in the list of apps, verbatim), `noSitemapComponent` (its component read finds none), `componentRows` (its component
+// rows, verbatim), `savedRows` (its saved rows, verbatim — to leave them out, say) or `sitemapName` (the `sitemapnameunique` of its sitemap, which is its own name unless said: the SDK
+// names an app's sitemap after the app, and links the two by that name). Every saved row carries its sitemap's `sitemapnameunique`, as the platform's rows do.
+function scanEnv(apps, { drafts = [], savedPages, appList, noDataverse } = {}) {
+ const calls = { queries: [], gets: [] };
+ const all = apps.map((a, i) => ({ appmoduleid: `app-${i}`, uniquename: a.name, appmoduleidunique: layerKey(i) }));
+ const draftAt = (j) => 100 + j; // a draft's index in the sitemap and layer-key numbering, apart from the published apps'
+ const sdk = {
+ queryRecords: async (entity, o) => {
+ calls.queries.push(entity);
+ const filter = (o && o.filter) || '';
+ if (entity === 'appmodule') {
+ const m = filter.match(/uniquename eq '([^']+)'/);
+ return m ? all.filter((a) => a.uniquename === m[1]) : all;
+ }
+ if (entity === 'appmodulecomponent') {
+ const i = Number(filter.match(/_appmoduleidunique_value eq \S+?(\d{12})\b/)[1]);
+ if (i >= 100 && drafts[i - 100].noSitemapComponent) return [];
+ if (i >= 100 && drafts[i - 100].componentRows) return drafts[i - 100].componentRows;
+ return [{ objectid: smId(i), componenttype: 62 }];
+ }
+ if (entity === 'sitemap') {
+ const i = Number(filter.match(/sitemapid eq \S+?(\d{12})\b/)[1]);
+ return [{ sitemapxml: apps[i].published }];
+ }
+ return [];
+ },
+ };
+ if (!noDataverse) {
+ sdk.dataverse = {
+ get: async (url) => {
+ calls.gets.push(url);
+ if (url.startsWith('/appmodules/')) {
+ if (appList) return appList(url);
+ const rows = [];
+ apps.forEach((a, i) => {
+ rows.push({ appmoduleid: `app-${i}`, appmoduleidunique: layerKey(i), uniquename: a.name, componentstate: 0 });
+ if (typeof a.saved === 'string') rows.push({ appmoduleid: `app-${i}`, appmoduleidunique: layerKey(1000 + i), uniquename: a.name, componentstate: 1 });
+ });
+ drafts.forEach((d, j) => (d.rows ? rows.push(...d.rows) : rows.push({ appmoduleid: `draft-${j}`, appmoduleidunique: layerKey(draftAt(j)), uniquename: d.name, componentstate: 1 })));
+ return { status: 200, body: { value: rows } };
+ }
+ if (savedPages) return savedPages(url);
+ const rows = [];
+ apps.forEach((a, i) => {
+ const sitemapnameunique = a.name;
+ if (a.saved && a.saved.rows) rows.push(...a.saved.rows.map((r) => ({ sitemapid: smId(i), sitemapnameunique, ...r })));
+ else if (typeof a.saved === 'string') rows.push({ sitemapid: smId(i), sitemapnameunique, sitemapxml: a.published, componentstate: 0 }, { sitemapid: smId(i), sitemapnameunique, sitemapxml: a.saved, componentstate: 1 });
+ else rows.push({ sitemapid: smId(i), sitemapnameunique, sitemapxml: a.published, componentstate: 0 });
+ });
+ drafts.forEach((d, j) => {
+ const sitemapnameunique = d.sitemapName === undefined ? d.name : d.sitemapName;
+ if (d.savedRows) rows.push(...d.savedRows.map((r) => ({ sitemapid: smId(draftAt(j)), sitemapnameunique, ...r })));
+ else rows.push({ sitemapid: smId(draftAt(j)), sitemapnameunique, sitemapxml: d.saved, componentstate: 1 });
+ });
+ return { status: 200, body: { value: rows } };
+ },
+ };
+ }
+ return { sdk, calls };
+}
+
+test('fetchAppsForPages: a page only in another app\'s SAVED navigation is a shared page, and says it is not published', async () => {
+ const { sdk } = scanEnv([
+ { name: 'app-a', published: withPage() },
+ { name: 'app-b', published: withPage(GP_DETAIL), saved: withPage(GP_DETAIL, GP_OVERVIEW) },
+ ]);
+ const r = await fetchAppsForPages(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-a' });
+ assert.strictEqual(r.ok, true);
+ assert.deepStrictEqual(r.byId.get(GP_OVERVIEW), ['app-b'], 'the page another app saved into its navigation is found');
+ assert.deepStrictEqual(r.savedOnly.get(GP_OVERVIEW), ['app-b'], 'and reported as saved but not published');
+ assert.deepStrictEqual(r.unreadable, []);
+ // Control: the same environment with nothing saved is clean, so the finding above is the saved layer's alone.
+ const clean = scanEnv([{ name: 'app-a', published: withPage() }, { name: 'app-b', published: withPage(GP_DETAIL) }]);
+ const none = await fetchAppsForPages(clean.sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-a' });
+ assert.strictEqual(none.byId.size, 0);
+ assert.strictEqual(none.savedOnly.size, 0);
+});
+
+test('fetchAppsForPages: a page in an app\'s published AND saved navigation is listed once; a draft that drops it does not clear it', async () => {
+ const { sdk } = scanEnv([
+ { name: 'app-a', published: withPage() },
+ { name: 'app-b', published: withPage(GP_OVERVIEW), saved: withPage(GP_OVERVIEW, GP_DETAIL) },
+ // app-c's draft REMOVED the page, but its published navigation — what its users see — still has it.
+ { name: 'app-c', published: withPage(GP_OVERVIEW), saved: withPage(GP_DETAIL) },
+ ]);
+ const r = await fetchAppsForPages(sdk, [GP_OVERVIEW, GP_DETAIL], { excludeAppUnique: 'app-a' });
+ assert.deepStrictEqual((r.byId.get(GP_OVERVIEW) || []).sort(), ['app-b', 'app-c'], 'each app once, whichever layers hold the page');
+ assert.deepStrictEqual(r.byId.get(GP_DETAIL).sort(), ['app-b', 'app-c']);
+ assert.deepStrictEqual(r.savedOnly.get(GP_OVERVIEW), undefined, 'the published layer holds it, so it is not saved-only');
+ assert.deepStrictEqual(r.savedOnly.get(GP_DETAIL).sort(), ['app-b', 'app-c']);
+});
+
+test('fetchAppsForPages: the saved layer of every other app is ONE request, however many apps there are', async () => {
+ for (const others of [1, 3, 12]) {
+ const apps = [{ name: 'app-self', published: withPage() }];
+ for (let i = 0; i < others; i += 1) apps.push({ name: `app-${i}`, published: withPage(), saved: i === others - 1 ? withPage(GP_OVERVIEW) : undefined });
+ const { sdk, calls } = scanEnv(apps);
+ const r = await fetchAppsForPages(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.deepStrictEqual(r.byId.get(GP_OVERVIEW), [`app-${others - 1}`], `${others} other app(s)`);
+ assert.deepStrictEqual(calls.gets, [APPS_URL, SAVED_URL], `${others} other app(s): the list of never-published apps, then exactly one saved-layer read, unfiltered by app`);
+ // The published layer is unchanged: one app list, then an app row, its sitemap component and its sitemap per OTHER app.
+ assert.strictEqual(calls.queries.length, 1 + 3 * others, `${others} other app(s): the published reads are as they were`);
+ }
+});
+
+test('fetchAppsForPages: a single-app environment reads no other app\'s navigation: the one list of never-published apps, and no sitemap', async () => {
+ const { sdk, calls } = scanEnv([{ name: 'app-self', published: withPage(GP_OVERVIEW) }]);
+ const r = await fetchAppsForPages(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.strictEqual(r.ok, true);
+ assert.strictEqual(r.byId.size, 0);
+ assert.deepStrictEqual(calls.gets, [APPS_URL], 'one small request — the apps that were never published — and no saved-layer request');
+ assert.deepStrictEqual(calls.queries, ['appmodule'], 'only the app list: no component, no sitemap');
+ // And with no page to look for there is nothing to read at all.
+ const idle = scanEnv([{ name: 'app-self', published: withPage() }, { name: 'app-b', published: withPage() }]);
+ await fetchAppsForPages(idle.sdk, [], { excludeAppUnique: 'app-self' });
+ assert.deepStrictEqual([idle.calls.gets, idle.calls.queries], [[], []]);
+});
+
+test('fetchAppsForPages: when the saved layer cannot be read at all, the scan FAILS CLOSED (never "no pages saved")', async () => {
+ const apps = [{ name: 'app-a', published: withPage() }, { name: 'app-b', published: withPage() }];
+ const failures = {
+ 'an HTTP error': () => ({ status: 503, body: null }),
+ 'a body that is no result set': () => ({ status: 200, body: {} }),
+ 'a thrown transport error': () => { throw new Error('socket hang up'); },
+ 'a repeated @odata.nextLink': () => ({ status: 200, body: { value: [], '@odata.nextLink': SAVED_URL } }),
+ 'a malformed @odata.nextLink': () => ({ status: 200, body: { value: [], '@odata.nextLink': 42 } }),
+ };
+ for (const [what, savedPages] of Object.entries(failures)) {
+ const { sdk } = scanEnv(apps, { savedPages });
+ const r = await fetchAppsForPages(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-a' });
+ assert.strictEqual(r.ok, false, what);
+ assert.match(r.error, /saved \(unpublished\) navigation/, what);
+ }
+ const { sdk } = scanEnv(apps, { noDataverse: true });
+ const noClient = await fetchAppsForPages(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-a' });
+ assert.strictEqual(noClient.ok, false, 'no client to read the saved layer with is not an empty saved layer');
+ assert.match(noClient.error, /never been published[\s\S]*no Dataverse client/, 'it is the first Dataverse read, and it already needs the client');
+});
+
+test('fetchAppsForPages: an app whose saved navigation is missing, ambiguous or malformed is listed unreadable', async () => {
+ const published = withPage();
+ const cases = {
+ 'no saved row for its sitemap': { rows: [] },
+ 'two rows and neither is the saved layer': { rows: [{ sitemapxml: published, componentstate: 0 }, { sitemapxml: published, componentstate: 0 }] },
+ 'two saved layers': { rows: [{ sitemapxml: published, componentstate: 1 }, { sitemapxml: published, componentstate: 1 }] },
+ 'empty XML': { rows: [{ sitemapxml: '', componentstate: 1 }] },
+ 'XML cut short': { rows: [{ sitemapxml: '<SiteMap><Area><Group><SubArea GenPageId="13ecbc57-a3a4-4132-b0a2', componentstate: 1 }] },
+ 'a page id that is no GUID': { rows: [{ sitemapxml: '<SiteMap><Area><Group><SubArea GenPageId="not-a-guid"/></Group></Area></SiteMap>', componentstate: 1 }] },
+ };
+ for (const [what, saved] of Object.entries(cases)) {
+ const { sdk } = scanEnv([{ name: 'app-a', published }, { name: 'app-b', published, saved }, { name: 'app-c', published, saved: withPage(GP_OVERVIEW) }], {});
+ const r = await fetchAppsForPages(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-a' });
+ assert.strictEqual(r.ok, true, what);
+ assert.deepStrictEqual(r.unreadable, ['app-b'], what);
+ assert.deepStrictEqual(r.byId.get(GP_OVERVIEW), ['app-c'], `${what}: the readable app is still scanned`);
+ }
+});
+
+test('fetchAppsForPages: the saved read follows @odata.nextLink to completion', async () => {
+ const apps = [{ name: 'app-a', published: withPage() }, { name: 'app-b', published: withPage() }, { name: 'app-c', published: withPage() }];
+ const second = `${SAVED_URL}&$skiptoken=2`;
+ const savedPages = async (url) => (url === SAVED_URL
+ ? { status: 200, body: { value: [{ sitemapid: smId(1), sitemapxml: withPage(), componentstate: 0 }], '@odata.nextLink': second } }
+ : { status: 200, body: { value: [{ sitemapid: smId(2), sitemapxml: withPage(), componentstate: 0 }, { sitemapid: smId(2), sitemapxml: withPage(GP_OVERVIEW), componentstate: 1 }] } });
+ const { sdk, calls } = scanEnv(apps, { savedPages });
+ const r = await fetchAppsForPages(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-a' });
+ assert.deepStrictEqual(calls.gets, [APPS_URL, SAVED_URL, second]);
+ assert.deepStrictEqual(r.byId.get(GP_OVERVIEW), ['app-c'], 'an app on the second page is scanned too');
+ assert.deepStrictEqual(r.unreadable, []);
+});
+
+// ── Apps that were NEVER published ────────────────────────────────────────────────────────────────────────────────────────────
+// An app saved in the maker and never published has no row in the published `appmodule` list, so the scan above — which starts from that list — never read its navigation, and a page
+// it holds was updated without a word. Its saved sitemap IS in the saved-layer read; what was missing is the app it belongs to. They are listed by the same collection's
+// RetrieveUnpublishedMultiple (one request, whatever the number of apps), and each one's sitemap is found through its layer key's sitemap component and joined from the saved read.
+test('fetchAppsForPages: a page only in a NEVER-PUBLISHED app\'s saved navigation is a shared page, reported as saved but not published', async () => {
+ const { sdk } = scanEnv([{ name: 'app-a', published: withPage() }, { name: 'app-b', published: withPage(GP_DETAIL) }], {
+ drafts: [{ name: 'app-draft', saved: withPage(GP_OVERVIEW) }],
+ });
+ const r = await fetchAppsForPages(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-a' });
+ assert.strictEqual(r.ok, true);
+ assert.deepStrictEqual(r.byId.get(GP_OVERVIEW), ['app-draft'], 'the page a draft app holds is found');
+ assert.deepStrictEqual(r.savedOnly.get(GP_OVERVIEW), ['app-draft'], 'and it has no published layer, so it is saved only');
+ assert.deepStrictEqual(r.unreadable, []);
+ // Controls: the same environment without the draft is clean, and a draft that does not hold the page is not a finding.
+ const without = scanEnv([{ name: 'app-a', published: withPage() }, { name: 'app-b', published: withPage(GP_DETAIL) }]);
+ assert.strictEqual((await fetchAppsForPages(without.sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-a' })).byId.size, 0);
+ const elsewhere = scanEnv([{ name: 'app-a', published: withPage() }], { drafts: [{ name: 'app-draft', saved: withPage(GP_DETAIL) }] });
+ const other = await fetchAppsForPages(elsewhere.sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-a' });
+ assert.strictEqual(other.ok, true);
+ assert.strictEqual(other.byId.size, 0);
+ assert.deepStrictEqual(other.unreadable, []);
+});
+
+test('fetchAppsForPages: the page of a never-published app is found when it is the ONLY other app, beside several published ones, and next to a draft of a published app', async () => {
+ // Only other app: a single published app (self) and a draft. The published reads find no other app, and the saved layer is read all the same, for the draft.
+ const alone = scanEnv([{ name: 'app-self', published: withPage() }], { drafts: [{ name: 'app-draft', saved: withPage(GP_OVERVIEW) }] });
+ const r = await fetchAppsForPages(alone.sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.deepStrictEqual(r.byId.get(GP_OVERVIEW), ['app-draft']);
+ assert.deepStrictEqual(alone.calls.gets, [APPS_URL, SAVED_URL]);
+ // Several published apps — one with a pending edit of its own — and two drafts: every app holding the page is named once, in either layer.
+ const many = scanEnv([
+ { name: 'app-self', published: withPage() },
+ { name: 'app-pub', published: withPage(GP_OVERVIEW) },
+ { name: 'app-pending', published: withPage(), saved: withPage(GP_OVERVIEW) },
+ ], { drafts: [{ name: 'app-draft-1', saved: withPage(GP_OVERVIEW, GP_DETAIL) }, { name: 'app-draft-2', saved: withPage(GP_DETAIL) }] });
+ const all = await fetchAppsForPages(many.sdk, [GP_OVERVIEW, GP_DETAIL], { excludeAppUnique: 'app-self' });
+ assert.deepStrictEqual(all.byId.get(GP_OVERVIEW).sort(), ['app-draft-1', 'app-pending', 'app-pub']);
+ assert.deepStrictEqual(all.byId.get(GP_DETAIL).sort(), ['app-draft-1', 'app-draft-2']);
+ assert.deepStrictEqual(all.savedOnly.get(GP_OVERVIEW).sort(), ['app-draft-1', 'app-pending'], 'saved only: the pending edit of a published app, and the draft; not the published page');
+ assert.deepStrictEqual(all.unreadable, []);
+ // A published app with a pending edit has two rows in the list of apps and is not a never-published app: no component read is made for its draft layer.
+ const layerKeysRead = [];
+ const spy = scanEnv([{ name: 'app-self', published: withPage() }, { name: 'app-pending', published: withPage(), saved: withPage(GP_OVERVIEW) }]);
+ const queryRecords = spy.sdk.queryRecords;
+ spy.sdk.queryRecords = async (entity, o) => { if (entity === 'appmodulecomponent') layerKeysRead.push(o.filter.match(/_appmoduleidunique_value eq (\S+)/)[1]); return queryRecords(entity, o); };
+ await fetchAppsForPages(spy.sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.deepStrictEqual(layerKeysRead, [layerKey(1)], 'only the published layer of the published app — the pending layer key is never taken for a never-published app');
+});
+
+test('fetchAppsForPages: the list of never-published apps is ONE request however many there are, and each draft costs its sitemap component read and nothing else', async () => {
+ for (const drafts of [0, 1, 4]) {
+ const list = Array.from({ length: drafts }, (_, j) => ({ name: `app-draft-${j}`, saved: j === drafts - 1 ? withPage(GP_OVERVIEW) : withPage(GP_DETAIL) }));
+ const { sdk, calls } = scanEnv([{ name: 'app-self', published: withPage() }, { name: 'app-b', published: withPage() }], { drafts: list });
+ const r = await fetchAppsForPages(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.deepStrictEqual(r.byId.get(GP_OVERVIEW), drafts ? [`app-draft-${drafts - 1}`] : undefined, `${drafts} draft app(s)`);
+ assert.deepStrictEqual(calls.gets, [APPS_URL, SAVED_URL], `${drafts} draft app(s): one list of apps and one saved-layer read, shared by the published app and the drafts`);
+ // The published app costs its app row, component and sitemap (3); each draft one component read (the app list already has its layer key, the saved read its sitemap).
+ assert.strictEqual(calls.queries.length, 1 + 3 + drafts, `${drafts} draft app(s): the published reads are as they were, plus one read per draft`);
+ assert.strictEqual(calls.queries.filter((q) => q === 'appmodulecomponent').length, 1 + drafts);
+ }
+ // Without any other published app the saved layer is still read — once — because of the draft.
+ const only = scanEnv([{ name: 'app-self', published: withPage() }], { drafts: [{ name: 'app-draft', saved: withPage() }, { name: 'app-draft-2', saved: withPage() }] });
+ await fetchAppsForPages(only.sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.deepStrictEqual(only.calls.gets, [APPS_URL, SAVED_URL]);
+ assert.deepStrictEqual(only.calls.queries, ['appmodule', 'appmodulecomponent', 'appmodulecomponent']);
+});
+
+test('fetchAppsForPages: the app itself is never scanned as a never-published app, whatever its rows say', async () => {
+ // A draft row named like self (matched by name, as published apps are) is skipped: self cannot share a page with itself, and is not unreadable either.
+ const { sdk, calls } = scanEnv([{ name: 'app-self', published: withPage() }], {
+ drafts: [{ name: 'App-Self', saved: withPage(GP_OVERVIEW) }, { name: 'app-other', saved: withPage(GP_DETAIL) }],
+ });
+ const r = await fetchAppsForPages(sdk, [GP_OVERVIEW, GP_DETAIL], { excludeAppUnique: 'app-self' });
+ assert.deepStrictEqual([...r.byId], [[GP_DETAIL, ['app-other']]], 'only the other draft app holds a page');
+ assert.deepStrictEqual(r.unreadable, []);
+ assert.strictEqual(calls.queries.filter((q) => q === 'appmodulecomponent').length, 1, 'self\'s layer was not read');
+});
+
+test('fetchAppsForPages: when the list of never-published apps cannot be read, the scan FAILS CLOSED before reading any sitemap', async () => {
+ const apps = [{ name: 'app-self', published: withPage() }, { name: 'app-b', published: withPage() }];
+ const failures = {
+ 'an HTTP error': () => ({ status: 503, body: null }),
+ 'a forbidden read': () => ({ status: 403, body: { error: { message: 'no privilege' } } }),
+ 'a body that is no result set': () => ({ status: 200, body: {} }),
+ 'a thrown transport error': () => { throw new Error('socket hang up'); },
+ 'a repeated @odata.nextLink': () => ({ status: 200, body: { value: [], '@odata.nextLink': APPS_URL } }),
+ 'a malformed @odata.nextLink': () => ({ status: 200, body: { value: [], '@odata.nextLink': 42 } }),
+ 'a row with no appmoduleid': () => ({ status: 200, body: { value: [{ uniquename: 'app-x', componentstate: 1 }] } }),
+ 'a null row': () => ({ status: 200, body: { value: [null] } }),
+ };
+ for (const [what, appList] of Object.entries(failures)) {
+ const { sdk, calls } = scanEnv(apps, { appList });
+ const r = await fetchAppsForPages(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.strictEqual(r.ok, false, what);
+ assert.match(r.error, /could not list the apps that have never been published/, what);
+ assert.deepStrictEqual(calls.queries, ['appmodule'], `${what}: nothing else was read — no sitemap, no component`);
+ }
+ // Also with a single app, where it is the only read there is.
+ const single = scanEnv([{ name: 'app-self', published: withPage() }], { appList: () => ({ status: 503, body: null }) });
+ assert.strictEqual((await fetchAppsForPages(single.sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' })).ok, false, 'a single-app environment is not exempt: it cannot be told that no draft app exists');
+});
+
+test('fetchAppsForPages: the list of never-published apps follows @odata.nextLink to completion', async () => {
+ const second = `${APPS_URL}&$skiptoken=2`;
+ const appList = (url) => (url === APPS_URL
+ ? { status: 200, body: { value: [{ appmoduleid: 'app-0', appmoduleidunique: layerKey(0), uniquename: 'app-self', componentstate: 0 }], '@odata.nextLink': second } }
+ : { status: 200, body: { value: [{ appmoduleid: 'draft-0', appmoduleidunique: layerKey(100), uniquename: 'app-draft', componentstate: 1 }] } });
+ const { sdk, calls } = scanEnv([{ name: 'app-self', published: withPage() }], { drafts: [{ name: 'app-draft', saved: withPage(GP_OVERVIEW) }], appList });
+ const r = await fetchAppsForPages(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.deepStrictEqual(calls.gets.slice(0, 2), [APPS_URL, second]);
+ assert.deepStrictEqual(r.byId.get(GP_OVERVIEW), ['app-draft'], 'a draft app on the second page is scanned too');
+});
+
+test('fetchAppsForPages: a never-published app whose layer, sitemap component or saved sitemap cannot be read is listed unreadable, and the other apps are still scanned', async () => {
+ const draft = (extra) => ({ name: 'app-broken', saved: withPage(), ...extra });
+ const row = (over) => ({ appmoduleid: 'draft-0', appmoduleidunique: layerKey(100), uniquename: 'app-broken', componentstate: 1, ...over });
+ const cases = {
+ 'no saved row for its sitemap': draft({ savedRows: [] }),
+ 'two saved layers': draft({ savedRows: [{ sitemapxml: withPage(), componentstate: 1 }, { sitemapxml: withPage(), componentstate: 1 }] }),
+ 'empty XML': draft({ savedRows: [{ sitemapxml: '', componentstate: 1 }] }),
+ 'XML cut short': draft({ savedRows: [{ sitemapxml: '<SiteMap><Area><Group><SubArea GenPageId="13ecbc57-a3a4-4132-b0a2', componentstate: 1 }] }),
+ 'a page id that is no GUID': draft({ savedRows: [{ sitemapxml: '<SiteMap><Area><Group><SubArea GenPageId="not-a-guid"/></Group></Area></SiteMap>', componentstate: 1 }] }),
+ // A sitemap component that is there but names no sitemap is an answer that cannot be read — unlike no component at all (the next test).
+ 'a sitemap component that names no sitemap': draft({ componentRows: [{ componenttype: 62 }] }),
+ 'a sitemap component with an empty id': draft({ componentRows: [{ objectid: '', componenttype: 62 }] }),
+ 'two current layers': draft({ rows: [row({}), row({ appmoduleidunique: layerKey(101) })] }),
+ 'no authored layer among several': draft({ rows: [row({ componentstate: 0 }), row({ appmoduleidunique: layerKey(101), componentstate: 0 })] }),
+ 'a layer key that is no GUID': draft({ rows: [row({ appmoduleidunique: 'not-a-guid' })] }),
+ 'no layer key': draft({ rows: [row({ appmoduleidunique: undefined })] }),
+ };
+ for (const [what, d] of Object.entries(cases)) {
+ const { sdk } = scanEnv([{ name: 'app-self', published: withPage() }, { name: 'app-pub', published: withPage(GP_OVERVIEW) }], { drafts: [d] });
+ const r = await fetchAppsForPages(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.strictEqual(r.ok, true, what);
+ assert.deepStrictEqual(r.unreadable, ['app-broken'], what);
+ assert.deepStrictEqual(r.byId.get(GP_OVERVIEW), ['app-pub'], `${what}: the readable app is still scanned`);
+ }
+ // A failed component read is unreadable too, not a thrown error and not "no sitemap, no page".
+ const { sdk } = scanEnv([{ name: 'app-self', published: withPage() }], { drafts: [draft({})] });
+ const queryRecords = sdk.queryRecords;
+ sdk.queryRecords = async (entity, o) => { if (entity === 'appmodulecomponent') throw new Error('socket hang up'); return queryRecords(entity, o); };
+ const failed = await fetchAppsForPages(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.strictEqual(failed.ok, true);
+ assert.deepStrictEqual(failed.unreadable, ['app-broken']);
+ // A draft row that names no app is listed by its id, so the halt can still say which one.
+ const nameless = scanEnv([{ name: 'app-self', published: withPage() }], { drafts: [draft({ rows: [row({ uniquename: undefined, appmoduleidunique: undefined })] })] });
+ assert.deepStrictEqual((await fetchAppsForPages(nameless.sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' })).unreadable, ['draft-0']);
+});
+
+// A never-published app saved in the maker with nothing but a name has no sitemap component in its layer, and no sitemap of its name: it has no navigation, so it holds no page. A read that
+// SUCCEEDS and finds no component, with no sitemap of the app's name to be found in the saved layer, shows that — it is not "unreadable", and one such app must not stop every page update in
+// the environment. Only a read that FAILS, or a component that names no sitemap, proves nothing (the test above). The saved-layer read is what rules a sitemap linked by name out, so it is made.
+test('fetchAppsForPages: a never-published app with no sitemap component and no sitemap of its name holds no page — it is skipped, not listed unreadable', async () => {
+ // No sitemap row carries its name; another app's sitemap, which does name the page, is nothing to do with it.
+ const bare = { name: 'app-bare', saved: withPage(), savedRows: [], noSitemapComponent: true };
+ // Beside a published app that holds the page: the page is found there, and nothing is unreadable.
+ const beside = scanEnv([{ name: 'app-self', published: withPage() }, { name: 'app-pub', published: withPage(GP_OVERVIEW) }], { drafts: [bare] });
+ const r = await fetchAppsForPages(beside.sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.strictEqual(r.ok, true);
+ assert.deepStrictEqual(r.unreadable, []);
+ assert.deepStrictEqual(r.byId.get(GP_OVERVIEW), ['app-pub']);
+ // The only other app: its component read, and the one saved-layer read that shows no sitemap carries its name.
+ const alone = scanEnv([{ name: 'app-self', published: withPage() }], { drafts: [bare] });
+ const only = await fetchAppsForPages(alone.sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.strictEqual(only.ok, true);
+ assert.deepStrictEqual(only.unreadable, []);
+ assert.strictEqual(only.byId.size, 0);
+ assert.deepStrictEqual(alone.calls.gets, [APPS_URL, SAVED_URL], 'the list of apps and the one saved-layer read, which is how the app is shown to have no sitemap');
+ assert.deepStrictEqual(alone.calls.queries, ['appmodule', 'appmodulecomponent']);
+ // Beside a draft app that does hold the page, the bare one changes nothing: the other is still found, and only it is named.
+ const mixed = scanEnv([{ name: 'app-self', published: withPage() }], { drafts: [bare, { name: 'app-draft', saved: withPage(GP_OVERVIEW) }] });
+ const both = await fetchAppsForPages(mixed.sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.deepStrictEqual(both.byId.get(GP_OVERVIEW), ['app-draft']);
+ assert.deepStrictEqual(both.savedOnly.get(GP_OVERVIEW), ['app-draft']);
+ assert.deepStrictEqual(both.unreadable, []);
+ assert.deepStrictEqual(mixed.calls.gets, [APPS_URL, SAVED_URL], 'the one saved-layer read serves both');
+});
+
+// The vendored SDK ties an app to its sitemap BY NAME: it looks the sitemap up by `sitemapnameunique` equal to the app's unique name and takes a sitemap for the app only while that column holds the
+// name (so does this plugin's own ensureSitemapInSolution). An app whose layer has no sitemap component — a half-made or broken one — can therefore still hold a sitemap, and pages in it,
+// that only its name links to it; skipping it would let the update through.
+test('fetchAppsForPages: a never-published app with no sitemap component whose sitemap is linked to it by NAME holds that sitemap\'s pages', async () => {
+ const linked = { name: 'app-linked', saved: withPage(GP_OVERVIEW), noSitemapComponent: true };
+ // The app's name and the sitemap's are compared in lower case: a maker-made unique name usually has capitals (`contoso_SalesHub`), and the sitemap row may carry it in any case.
+ const cases = [
+ ['the same case', 'app-linked', 'app-linked'],
+ ['another case — Dataverse compares names without regard to case', 'app-linked', 'APP-Linked'],
+ ['an app name with capitals, against a sitemap of the same name in lower case', 'App-Linked', 'app-linked'],
+ ];
+ for (const [what, appName, sitemapName] of cases) {
+ const { sdk, calls } = scanEnv([{ name: 'app-self', published: withPage() }], { drafts: [{ ...linked, name: appName, sitemapName }] });
+ const r = await fetchAppsForPages(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.strictEqual(r.ok, true, what);
+ assert.deepStrictEqual(r.byId.get(GP_OVERVIEW), [appName], `${what}: the page its sitemap holds is found`);
+ assert.deepStrictEqual(r.savedOnly.get(GP_OVERVIEW), [appName], `${what}: and it has no published layer, so it is saved only`);
+ assert.deepStrictEqual(r.unreadable, [], what);
+ // No request beyond the ones a draft app costs anyway: the list of apps, its component read, and the one saved-layer read, which carries the name.
+ assert.deepStrictEqual(calls.gets, [APPS_URL, SAVED_URL], what);
+ assert.deepStrictEqual(calls.queries, ['appmodule', 'appmodulecomponent'], what);
+ }
+ // A sitemap that holds some other page is not a finding, and a sitemap of ANOTHER name is not this app's whatever it holds.
+ const other = scanEnv([{ name: 'app-self', published: withPage() }], { drafts: [{ ...linked, saved: withPage(GP_DETAIL) }] });
+ const elsewhere = await fetchAppsForPages(other.sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.strictEqual(elsewhere.byId.size, 0);
+ assert.deepStrictEqual(elsewhere.unreadable, []);
+ const named = scanEnv([{ name: 'app-self', published: withPage() }], { drafts: [{ ...linked, sitemapName: 'app-someone-else' }] });
+ const unrelated = await fetchAppsForPages(named.sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.strictEqual(unrelated.byId.size, 0, 'a sitemap that carries another app\'s name is that app\'s');
+ assert.deepStrictEqual(unrelated.unreadable, []);
+ // Beside a published app and a draft app whose component names its sitemap, the same single saved-layer read serves all of them.
+ const together = scanEnv([{ name: 'app-self', published: withPage() }, { name: 'app-pub', published: withPage(GP_DETAIL) }], { drafts: [linked, { name: 'app-draft', saved: withPage(GP_DETAIL) }] });
+ const all = await fetchAppsForPages(together.sdk, [GP_OVERVIEW, GP_DETAIL], { excludeAppUnique: 'app-self' });
+ assert.deepStrictEqual(all.byId.get(GP_OVERVIEW), ['app-linked']);
+ assert.deepStrictEqual(all.byId.get(GP_DETAIL).sort(), ['app-draft', 'app-pub']);
+ assert.deepStrictEqual(together.calls.gets, [APPS_URL, SAVED_URL]);
+});
+
+test('fetchAppsForPages: a name-linked sitemap that cannot be read — two sitemaps of the name, ambiguous or malformed rows — lists the app unreadable', async () => {
+ const linked = { name: 'app-linked', saved: withPage(), noSitemapComponent: true };
+ const cases = {
+ 'two saved layers': { ...linked, savedRows: [{ sitemapxml: withPage(), componentstate: 1 }, { sitemapxml: withPage(), componentstate: 1 }] },
+ 'empty XML': { ...linked, savedRows: [{ sitemapxml: '', componentstate: 1 }] },
+ 'XML cut short': { ...linked, savedRows: [{ sitemapxml: '<SiteMap><Area><Group><SubArea GenPageId="13ecbc57-a3a4-4132-b0a2', componentstate: 1 }] },
+ };
+ for (const [what, draft] of Object.entries(cases)) {
+ const { sdk } = scanEnv([{ name: 'app-self', published: withPage() }, { name: 'app-pub', published: withPage(GP_OVERVIEW) }], { drafts: [draft] });
+ const r = await fetchAppsForPages(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.strictEqual(r.ok, true, what);
+ assert.deepStrictEqual(r.unreadable, ['app-linked'], what);
+ assert.deepStrictEqual(r.byId.get(GP_OVERVIEW), ['app-pub'], `${what}: the readable app is still scanned`);
+ }
+ // Two different sitemaps with the app's name: which one is the app's cannot be told, and either may hold the page.
+ const twice = scanEnv([{ name: 'app-self', published: withPage() }], { drafts: [linked] });
+ const get = twice.sdk.dataverse.get;
+ twice.sdk.dataverse.get = async (url) => {
+ const res = await get(url);
+ if (url.startsWith('/sitemaps/')) res.body.value.push({ sitemapid: smId(900), sitemapnameunique: 'app-linked', sitemapxml: withPage(GP_OVERVIEW), componentstate: 1 });
+ return res;
+ };
+ const r = await fetchAppsForPages(twice.sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.strictEqual(r.ok, true);
+ assert.deepStrictEqual(r.unreadable, ['app-linked']);
+ assert.strictEqual(r.byId.size, 0);
+});
+
+test('fetchAppsForPages: when the saved layer cannot be read at all, a never-published app does not make the scan pass — whether or not its layer has a sitemap component', async () => {
+ for (const noSitemapComponent of [false, true]) {
+ const { sdk } = scanEnv([{ name: 'app-self', published: withPage() }], { drafts: [{ name: 'app-draft', saved: withPage(), noSitemapComponent }], savedPages: () => ({ status: 503, body: null }) });
+ const r = await fetchAppsForPages(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-self' });
+ assert.strictEqual(r.ok, false, `noSitemapComponent=${noSitemapComponent}`);
+ assert.match(r.error, /saved \(unpublished\) navigation/);
+ }
+});
+
+test('fetchSitemap: includeSitemapId adds the sitemap id the read resolved, and nothing else changes', async () => {
+ const sdk = sdkWith({
+ apps: [{ appmoduleid: 'a', appmoduleidunique: APP_UNIQUE_VALUE }],
+ comps: [{ objectid: `{${SITEMAP_ID.toUpperCase()}}`, componenttype: 62 }],
+ sms: [{ sitemapxml: XML }],
+ });
+ const plain = await fetchSitemap(sdk, 'contoso_app');
+ assert.deepStrictEqual(plain, { ok: true, xml: XML, ids: [GP_OVERVIEW, GP_DETAIL].sort() }, 'the default result has no sitemapId');
+ const withId = await fetchSitemap(sdk, 'contoso_app', { includeSitemapId: true });
+ assert.deepStrictEqual(withId, { ...plain, sitemapId: SITEMAP_ID }, 'lower-cased, without braces, so it matches a row of the saved read');
+});
diff --git a/plugins/model-apps/scripts/tests/solution-membership.test.js b/plugins/model-apps/scripts/tests/solution-membership.test.js
new file mode 100644
index 000000000..cb75e587c
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/solution-membership.test.js
@@ -0,0 +1,280 @@
+'use strict';
+// Solution membership is read once, and a component the solution is PROVEN to hold is not added again — by a row of
+// its own, or, for a view, chart or form, by its table being held with ALL its subcomponents.
+// The wire-level behaviour (what the build sends over a rebuild) is pinned in rebuild-writes-real-bundle.test.js;
+// these pin the helper's contract with the SDK reader stubbed, including every way the proof can fail.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { readSolutionMembers, createSolutionMembership, ensureSolutionComponent } = require('../lib/solution-membership.js');
+
+const SOL = '11111111-2222-4333-8444-555555555555';
+const A = 'aaaaaaaa-0000-4000-8000-000000000001';
+const B = 'bbbbbbbb-0000-4000-8000-000000000002';
+const C = 'cccccccc-0000-4000-8000-000000000003';
+
+// An SDK reader answering the two queries the helper makes, recording every call.
+function reader({ solutions = [{ solutionid: SOL }], components = [], failOn } = {}) {
+ const calls = [];
+ return {
+ calls,
+ async queryRecords(entity, options) {
+ calls.push([entity, options]);
+ if (failOn === entity) throw new Error(`${entity} unreadable`);
+ return entity === 'solution' ? solutions : components;
+ },
+ };
+}
+
+test('solution membership: the members are keyed by component type and bare lower-case id', async () => {
+ const read = reader({ components: [
+ { objectid: A.toUpperCase(), componenttype: 26 },
+ { objectid: `{${B}}`, componenttype: '60' },
+ ] });
+ const { members } = await readSolutionMembers(read, 'ContosoSD', [26, 60]);
+ assert.deepEqual([...members].sort(), [`26:${A}`, `60:${B}`].sort());
+});
+
+test('solution membership: the read asks for exactly the types given, restricted to this solution, and pages', async () => {
+ const read = reader();
+ await readSolutionMembers(read, "Contoso'SD", [26, 59, 26, 60]);
+ assert.equal(read.calls.length, 2);
+ assert.deepEqual(read.calls[0], ['solution', { select: ['solutionid'], filter: "uniquename eq 'Contoso''SD'", top: 1 }]);
+ const [entity, options] = read.calls[1];
+ assert.equal(entity, 'solutioncomponent');
+ assert.deepEqual(options.select, ['objectid', 'componenttype', 'rootcomponentbehavior']);
+ // Tables ride along (type 1) because a view, chart or form can be vouched for by its table.
+ assert.equal(options.filter, `_solutionid_value eq ${SOL} and (componenttype eq 26 or componenttype eq 59 or componenttype eq 60 or componenttype eq 1)`);
+ assert.equal(options.paginate, true);
+ assert.equal('top' in options, false, 'paginate and top cannot be combined: the SDK refuses it, and $top would cap the read at one page');
+
+ // Kinds a table never vouches for need no table rows: nothing is asked beyond them.
+ const rootsOnly = reader();
+ await readSolutionMembers(rootsOnly, 'ContosoSD', [20, 29, 61, 62, 80]);
+ assert.equal(rootsOnly.calls[1][1].filter, `_solutionid_value eq ${SOL} and (componenttype eq 20 or componenttype eq 29 or componenttype eq 61 or componenttype eq 62 or componenttype eq 80)`);
+});
+
+test('solution membership: nothing is proven when the solution cannot be identified — and nothing is read for a built-in one', async () => {
+ const none = reader({ solutions: [] });
+ assert.equal(await readSolutionMembers(none, 'Missing', [26]), null);
+ assert.equal(none.calls.length, 1, 'no component read without a solution row');
+
+ // The id is interpolated unquoted into an Edm.Guid comparison, so anything but a GUID must stop here.
+ const hostile = reader({ solutions: [{ solutionid: "x or 1 eq 1" }] });
+ assert.equal(await readSolutionMembers(hostile, 'ContosoSD', [26]), null);
+ assert.equal(hostile.calls.length, 1);
+
+ for (const name of ['Default', 'active', 'BASIC']) {
+ const builtIn = reader();
+ assert.equal(await readSolutionMembers(builtIn, name, [26]), null);
+ assert.equal(builtIn.calls.length, 0, `${name}: a built-in container holds every unmanaged customization, so its membership proves nothing`);
+ }
+ assert.equal(await readSolutionMembers(reader(), '', [26]), null);
+ assert.equal(await readSolutionMembers(reader(), 'ContosoSD', []), null);
+ assert.equal(await readSolutionMembers({}, 'ContosoSD', [26]), null, 'a reader without queryRecords proves nothing');
+});
+
+test('solution membership: a row that is not an (id, positive type) pair is ignored rather than trusted', async () => {
+ const read = reader({ components: [
+ { objectid: A, componenttype: 26 },
+ { objectid: null, componenttype: 26 },
+ { objectid: '', componenttype: 26 },
+ { objectid: B, componenttype: 'x' },
+ { objectid: B, componenttype: null },
+ { objectid: B, componenttype: 0 },
+ null,
+ ] });
+ assert.deepEqual([...(await readSolutionMembers(read, 'ContosoSD', [26])).members], [`26:${A}`]);
+ assert.equal(await readSolutionMembers(reader({ components: 'oops' }), 'ContosoSD', [26]), null, 'a non-list answer is unknown, not empty');
+});
+
+test('solution membership: has() is true only for what the read returned, and a failed read proves nothing — and is not retried', async () => {
+ const read = reader({ components: [{ objectid: A, componenttype: 26 }] });
+ const membership = createSolutionMembership({ read, solutionUniqueName: 'ContosoSD', componentTypes: [26, 60] });
+ assert.equal(await membership.has(A, 26), true);
+ assert.equal(await membership.has(A, 60), false, 'the same id under another component type is a different component');
+ assert.equal(await membership.has(B, 26), false);
+ assert.equal(await membership.has(A.toUpperCase(), 26), true);
+ assert.equal(await membership.has(`{${A}}`, 26), true);
+
+ const broken = reader({ failOn: 'solutioncomponent' });
+ const unknown = createSolutionMembership({ read: broken, solutionUniqueName: 'ContosoSD', componentTypes: [26] });
+ assert.equal(await unknown.has(A, 26), false);
+ assert.equal(await unknown.has(A, 26), false);
+ assert.equal(broken.calls.filter(([entity]) => entity === 'solutioncomponent').length, 1, 'a failed read is remembered, not repeated for every component');
+ unknown.note(A, 26);
+ assert.equal(await unknown.has(A, 26), false, 'noting a component cannot invent membership the read did not establish');
+});
+
+test('solution membership: concurrent callers share one read, and it starts only at first use', async () => {
+ const read = reader({ components: [{ objectid: A, componenttype: 26 }] });
+ const membership = createSolutionMembership({ read, solutionUniqueName: 'ContosoSD', componentTypes: [26] });
+ assert.equal(read.calls.length, 0, 'nothing has asked yet, so nothing is read');
+ const answers = await Promise.all([A, B, A, B, A].map((id) => membership.has(id, 26)));
+ assert.deepEqual(answers, [true, false, true, false, true]);
+ assert.equal(read.calls.length, 2, 'one solution lookup and one component read, however many callers');
+});
+
+test('solution membership: ensureSolutionComponent adds only what is not proven present, and remembers what it added', async () => {
+ const read = reader({ components: [{ objectid: A, componenttype: 26 }] });
+ const membership = createSolutionMembership({ read, solutionUniqueName: 'ContosoSD', componentTypes: [26] });
+ const adds = [];
+ const sdk = { addSolutionComponent: async (o) => { adds.push(o); } };
+ const present = { componentId: A, componentType: 26, solutionUniqueName: 'ContosoSD' };
+ const absent = { componentId: B, componentType: 26, solutionUniqueName: 'ContosoSD' };
+
+ assert.equal(await ensureSolutionComponent(sdk, membership, present), false);
+ assert.deepEqual(adds, []);
+ assert.equal(await ensureSolutionComponent(sdk, membership, absent), true);
+ assert.deepEqual(adds, [absent], 'the add carries exactly the arguments a direct call would');
+ assert.equal(await ensureSolutionComponent(sdk, membership, absent), false, 'a second assert of what this run just added is skipped');
+ assert.equal(adds.length, 1);
+});
+
+test('solution membership: without a membership, or when the add fails, ensureSolutionComponent behaves as a direct add', async () => {
+ const adds = [];
+ const sdk = { addSolutionComponent: async (o) => { adds.push(o); } };
+ const o = { componentId: A, componentType: 26, solutionUniqueName: 'ContosoSD' };
+ assert.equal(await ensureSolutionComponent(sdk, undefined, o), true);
+ assert.deepEqual(adds, [o]);
+
+ const membership = createSolutionMembership({ read: reader(), solutionUniqueName: 'ContosoSD', componentTypes: [26] });
+ const failing = { addSolutionComponent: async () => { throw new Error('refused'); } };
+ await assert.rejects(ensureSolutionComponent(failing, membership, o), /refused/, 'each call site keeps its own policy for a failed add');
+ assert.equal(await membership.has(A, 26), false, 'a failed add records nothing');
+});
+
+// ------------------------------------------------------------------- views, charts and forms vouched for by their table
+//
+// The rows below are the shapes the platform returns (see the header of lib/solution-membership.js), and the reader
+// answers the query the way it does: only the types asked for, only the columns selected, the primary key always.
+// a table { solutioncomponentid, objectid: <MetadataId>, componenttype: 1, rootcomponentbehavior: 0 | 1 | 2 }
+// a component { solutioncomponentid, objectid: <its own id>, componenttype: 26 | 59 | 60 | …, rootcomponentbehavior: null }
+// A table held with all its subcomponents (0) has no row for its views, forms or charts; one held at 1 or 2 has a row
+// for each of those that was added on its own, and for no other.
+const T_WHOLE = 'a1a1a1a1-0000-4000-8000-0000000000a1'; // held with ALL its subcomponents
+const T_META = 'a2a2a2a2-0000-4000-8000-0000000000a2'; // "Do not include subcomponents": the table's own metadata
+const T_SHELL = 'a3a3a3a3-0000-4000-8000-0000000000a3'; // "Include As Shell Only"
+const T_NULL = 'a4a4a4a4-0000-4000-8000-0000000000a4'; // a table row that carries no behavior
+const T_ABSENT = 'a5a5a5a5-0000-4000-8000-0000000000a5'; // not in the solution at all
+let rowCount = 0;
+const solutionRow = (objectid, componenttype, rootcomponentbehavior) => ({ solutioncomponentid: `5c000000-0000-4000-8000-${String(++rowCount).padStart(12, '0')}`, objectid, componenttype, rootcomponentbehavior });
+const tableRow = (objectid, behavior) => solutionRow(objectid, 1, behavior);
+const componentRow = (objectid, componenttype) => solutionRow(objectid, componenttype, null);
+
+function dataverseReader(rows, { failOn } = {}) {
+ const calls = [];
+ return {
+ calls,
+ async queryRecords(entity, options) {
+ calls.push([entity, options]);
+ if (failOn === entity) throw new Error(`${entity} unreadable`);
+ if (entity === 'solution') return [{ solutionid: SOL }];
+ const types = [...String(options.filter).matchAll(/componenttype eq (\d+)/g)].map((m) => Number(m[1]));
+ return rows.filter((row) => types.includes(row.componenttype))
+ .map((row) => Object.fromEntries(Object.entries(row).filter(([name]) => name === 'solutioncomponentid' || options.select.includes(name))));
+ },
+ };
+}
+
+// A membership over `rows`, with a table resolver answering from `tableIds` (an Error value throws) and recording
+// every table it is asked about in `asked`.
+function membershipOver(rows, tableIds = {}, { read = dataverseReader(rows) } = {}) {
+ const asked = [];
+ const resolveTableId = async (logical) => {
+ asked.push(logical);
+ const id = tableIds[logical];
+ if (id instanceof Error) throw id;
+ return id;
+ };
+ return { asked, read, membership: createSolutionMembership({ read, solutionUniqueName: 'ContosoSD', componentTypes: [20, 26, 29, 59, 60], resolveTableId }) };
+}
+const TABLES = { new_whole: T_WHOLE, new_meta: T_META, new_shell: T_SHELL, new_null: T_NULL, new_absent: T_ABSENT };
+const ALL_TABLE_ROWS = () => [tableRow(T_WHOLE, 0), tableRow(T_META, 1), tableRow(T_SHELL, 2), tableRow(T_NULL, null)];
+
+test('solution membership: only a table held with ALL its subcomponents (behavior 0) is told apart as whole', async () => {
+ const rows = [...ALL_TABLE_ROWS(), tableRow(B, '0'), tableRow(C, undefined), tableRow('d4d4d4d4-0000-4000-8000-0000000000d4', ''), componentRow(A, 26)];
+ const { members, wholeTables } = await readSolutionMembers(dataverseReader(rows), 'ContosoSD', [26, 59, 60]);
+ assert.deepEqual([...wholeTables].sort(), [T_WHOLE, B].sort(), 'behavior 0, as a number or as the string the SDK also accepts — not null, not empty, not absent');
+ assert.ok(members.has(`1:${T_SHELL}`), 'a table held in part is still in the solution; it just proves nothing about its views');
+ assert.ok(members.has(`26:${A}`));
+});
+
+test('solution membership: a view, chart or form of a table held with all its subcomponents is a member without a row of its own', async () => {
+ const { membership, asked } = membershipOver(ALL_TABLE_ROWS(), TABLES);
+ for (const type of [26, 59, 60]) assert.equal(await membership.has(A, type, { table: 'new_whole' }), true, `type ${type}`);
+ assert.deepEqual(asked, ['new_whole'], 'the table is resolved once for all three kinds');
+ assert.equal(await membership.has(A, 26, { table: 'New_Whole' }), true, 'the logical name is matched case-insensitively');
+});
+
+test('solution membership: a table held in part, held without behavior, or not held proves nothing about its views, charts and forms', async () => {
+ const { membership } = membershipOver(ALL_TABLE_ROWS(), TABLES);
+ for (const table of ['new_meta', 'new_shell', 'new_null', 'new_absent']) {
+ for (const type of [26, 59, 60]) assert.equal(await membership.has(A, type, { table }), false, `${table} / type ${type}: they need rows of their own`);
+ }
+ assert.equal(await membership.has(A, 26), false, 'with no table given there is nothing to vouch for it');
+ assert.equal(await membership.has(A, 26, { table: undefined }), false);
+});
+
+test('solution membership: a row of its own still counts, whatever its table is held at, and without asking about the table', async () => {
+ const { membership, asked } = membershipOver([...ALL_TABLE_ROWS(), componentRow(B, 26), componentRow(C, 60)], TABLES);
+ assert.equal(await membership.has(B, 26, { table: 'new_shell' }), true);
+ assert.equal(await membership.has(C, 60, { table: 'new_absent' }), true);
+ assert.deepEqual(asked, [], 'a row answers the question; no table is resolved for it');
+});
+
+test('solution membership: a table vouches for views, charts and forms only — never for a kind that gets a row of its own', async () => {
+ const { membership, asked } = membershipOver(ALL_TABLE_ROWS(), TABLES);
+ // Role, workflow (business rule, process flow), web resource, sitemap, app, and the table itself.
+ for (const type of [20, 29, 61, 62, 80, 1]) assert.equal(await membership.has(A, type, { table: 'new_whole' }), false, `type ${type}`);
+ assert.deepEqual(asked, [], 'and the table is not even resolved for them');
+});
+
+test('solution membership: a failed or unusable table lookup proves nothing, is not retried per component, and never throws', async () => {
+ const failing = membershipOver(ALL_TABLE_ROWS(), { new_whole: new Error('metadata unavailable') });
+ for (const id of [A, B, C]) assert.equal(await failing.membership.has(id, 26, { table: 'new_whole' }), false);
+ assert.deepEqual(failing.asked, ['new_whole'], 'a failure is remembered, not repeated for every component');
+
+ for (const answer of [undefined, null, '', 'not-a-guid', 42, T_WHOLE.slice(1)]) {
+ const { membership } = membershipOver(ALL_TABLE_ROWS(), { new_whole: answer });
+ assert.equal(await membership.has(A, 26, { table: 'new_whole' }), false, `answer ${JSON.stringify(answer)}`);
+ }
+ const noResolver = createSolutionMembership({ read: dataverseReader(ALL_TABLE_ROWS()), solutionUniqueName: 'ContosoSD', componentTypes: [26] });
+ assert.equal(await noResolver.has(A, 26, { table: 'new_whole' }), false, 'without a resolver only rows count');
+});
+
+test('solution membership: a MetadataId is matched however it is written, and a table lookup is shared by concurrent callers', async () => {
+ for (const written of [T_WHOLE.toUpperCase(), `{${T_WHOLE}}`, ` ${T_WHOLE} `]) {
+ const { membership } = membershipOver(ALL_TABLE_ROWS(), { new_whole: written });
+ assert.equal(await membership.has(A, 26, { table: 'new_whole' }), true, written);
+ }
+ const { membership, asked } = membershipOver(ALL_TABLE_ROWS(), TABLES);
+ const answers = await Promise.all([[A, 'new_whole'], [B, 'new_whole'], [C, 'new_shell'], [A, 'new_shell'], [B, 'new_whole']].map(([id, table]) => membership.has(id, 60, { table })));
+ assert.deepEqual(answers, [true, true, false, false, true]);
+ assert.deepEqual(asked.sort(), ['new_shell', 'new_whole'], 'one lookup per table');
+});
+
+test('solution membership: a solution that holds no table with all its subcomponents never pays for a table lookup', async () => {
+ const { membership, asked } = membershipOver([tableRow(T_META, 1), tableRow(T_SHELL, 2), componentRow(A, 26)], TABLES);
+ assert.equal(await membership.has(B, 26, { table: 'new_meta' }), false);
+ assert.equal(await membership.has(A, 26, { table: 'new_meta' }), true);
+ assert.deepEqual(asked, []);
+});
+
+test('solution membership: a component the table carries is not added, one it does not carry is, and the add never carries the table', async () => {
+ const { membership } = membershipOver(ALL_TABLE_ROWS(), TABLES);
+ const adds = [];
+ const sdk = { addSolutionComponent: async (o) => { adds.push(o); } };
+ const view = { componentId: A, componentType: 26, solutionUniqueName: 'ContosoSD' };
+ assert.equal(await ensureSolutionComponent(sdk, membership, view, { table: 'new_whole' }), false);
+ assert.deepEqual(adds, []);
+ assert.equal(await ensureSolutionComponent(sdk, membership, view, { table: 'new_shell' }), true);
+ assert.deepEqual(adds, [view], 'exactly the arguments a direct add sends: the table is evidence, not a parameter');
+ assert.equal(await ensureSolutionComponent(sdk, membership, view, { table: 'new_shell' }), false, 'and what this run added is remembered');
+ assert.equal(adds.length, 1);
+});
+
+test('solution membership: when the read itself fails, no table is consulted and everything is added', async () => {
+ const { membership, asked } = membershipOver(ALL_TABLE_ROWS(), TABLES, { read: dataverseReader(ALL_TABLE_ROWS(), { failOn: 'solutioncomponent' }) });
+ assert.equal(await membership.has(A, 26, { table: 'new_whole' }), false);
+ assert.deepEqual(asked, []);
+});
diff --git a/plugins/model-apps/scripts/tests/source-literals.test.js b/plugins/model-apps/scripts/tests/source-literals.test.js
index d36b5162d..4c52b087c 100644
--- a/plugins/model-apps/scripts/tests/source-literals.test.js
+++ b/plugins/model-apps/scripts/tests/source-literals.test.js
@@ -9,14 +9,15 @@ const assert = require('node:assert');
const fs = require('node:fs');
const path = require('node:path');
const { execFileSync, spawnSync } = require('node:child_process');
-const { blankLiterals, blankNonCodePreservingTemplateExpressions, commentRanges, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets, scanTemplateExpressionEnd, expressionPosition, opensTypeParameters, elementFailsAt, elementChildren, isTrivia, isSingleLineTrivia, trimTrivia, TRIVIA_CLASS, WS, AMBIGUITY_KINDS, ANGLE_AFTER, ANGLE_AFTER_LINE_BREAK, RESERVED_WORDS } = require('../lib/source-literals.js');
-const { navReferencedKeys, strayPageRefs } = require('../lib/pageref-resolver.js');
+const { blankLiterals, blankNonCodePreservingTemplateExpressions, commentRanges, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets, scanTemplateExpressionEnd, expressionPosition, opensTypeParameters, elementFailsAt, elementChildren, isTrivia, isSingleLineTrivia, trimTrivia, TRIVIA_CLASS, WS, AMBIGUITY_KINDS, ANGLE_AFTER, ANGLE_AFTER_LINE_BREAK, NO_MEMBER_BEFORE, RESERVED_WORDS } = require('../lib/source-literals.js');
+const { navReferencedKeys, strayPageRefs, resolvePageRefs } = require('../lib/pageref-resolver.js');
const { pageStructureProblems } = require('../lib/page-structure.js');
const { loadTypescriptOracle, loadBabelOracle } = require('./helpers/typescript-oracle.js');
-const { FRAMES, tokenVocabulary, programsFor, cleanSourceFile, readingAt, isElement, SIGNATURE_ENDINGS, HIDING_ENDINGS, CERTAIN_ELEMENTS, GUESSED_ELEMENTS, signaturePages, elementPages, SIGNATURE_FRAMES, DECOYS, signaturePage } = require('./helpers/angle-frames.js');
+const { FRAMES, tokenVocabulary, programsFor, cleanSourceFile, readingAt, isElement, SIGNATURE_ENDINGS, HIDING_ENDINGS, CERTAIN_ELEMENTS, GUESSED_ELEMENTS, HIDDEN_TEXT_ELEMENTS, UNREAD_LIST_ELEMENTS, MEMBER_ELEMENT_FRAMES, NO_MEMBER_ELEMENT_FRAMES, signaturePages, elementPages, SIGNATURE_FRAMES, DECOYS, signaturePage, EXACT_DEFAULTS, UNREAD_DEFAULTS, UNTERMINATED_DEFAULTS, PROSE_SHAPED_LINES, PROSE_HIDING_ELEMENTS, proseElements } = require('./helpers/angle-frames.js');
const { FUNCTION_TYPE_DECLARATIONS, ELEMENT_LOOKALIKE_PAGES } = require('./helpers/misread-page.js');
const { judgeDirect } = require('./helpers/jsx-element-fuzz.js');
+const { BASE_TOKENS, ALL_TOKENS, tokenTexts, drawnTexts, memberTexts, keywordTexts, keywordPairTexts, bracketTexts, wordTexts, numberWordTexts, importTypeTexts, drawnImportTypeTexts, accessorNameTexts, drawnAccessorNameTexts, tupleTexts } = require('./helpers/type-member-texts.js');
function parseDiagnosticMessages(ts, code) {
return ts.createSourceFile('snippet.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)
@@ -1703,12 +1704,18 @@ test('a "<" that starts an expression opens type parameters only by the TSX rule
// `<T extends` and a `/` is an element where an expression starts, by the rule; but in a type the `<` opens type parameters, and parseTypeParameter reads a constraint that starts no type as an
// expression, where a `/` starts a regex (only the checker objects): `let f: <T extends />;…[/]/>(a: T) => T` is a function type whose constraint is the regex `/>;…[/]/`, and the `/>` that
-// ends the element's tag is the regex's first characters. The lexer does not know which of the two it is in, so the head is a guess, read as an element. `/=` is one token to TypeScript's
-// scanner, not the `/` the rule names: type parameters in both.
-test('`<T extends` and a `/` is an element where an expression starts and type parameters in a type, so it is a guess; `/=` is type parameters in both', (t) => {
+// ends the element's tag is the regex's first characters. The lexer does not know which of the two it is in, so the head is a guess, read as an element — unless the regex does not close on its
+// line: TypeScript's scanner ends one at a line break (reScanSlashToken) and reports it unterminated (TS1161, a parse error), so no type has the text and the element is certain. `/=` is one token to
+// TypeScript's scanner, not the `/` the rule names: type parameters in both.
+test('`<T extends` and a `/` is an element where an expression starts and type parameters in a type, so it is a guess where its regex closes on the line, and an element where it does not; `/=` is type parameters in both', (t) => {
const GUESS = { generic: false, ambiguity: 'generic' };
- const GUESSED = ['<T extends/>', '<T extends />', '<T extends /x/>(a: T) => T', '<T extends />;f();[/]/>(a: T) => T', '<T extends/* c *//x/>(a: T) => T', '<const T extends />', '<T extends\n/>'];
- for (const code of GUESSED) assert.deepStrictEqual(opens(code), GUESS, code);
+ const GUESSED = ['<T extends /x/>(a: T) => T', '<T extends />;f();[/]/>(a: T) => T', '<T extends/* c *//x/>(a: T) => T', '<T extends\n/x/>(a: T) => T', '<T extends />; const r = a / b;', '<T extends /[/]/>(a: T) => T', '<T extends /\\//>(a: T) => T',
+ '<T extends /x/g>(a: T) => T', '<T extends />; const r = a />(a: T) => T;', '<T extends />; // c / d\n', `<T extends /${'a'.repeat(2500)}`];
+ for (const code of GUESSED) assert.deepStrictEqual(opens(code), GUESS, code.slice(0, 60));
+ // The regex that no `/` closes on its line: the end of the text, or a line break of any kind first — a backslash does not carry a regex over one, as it does a string.
+ const ELEMENTS = ['<T extends/>', '<T extends />', '<const T extends />', '<T extends\n/>', '<T extends />;\nf();[/]/>(a: T) => T', '<T extends />;\r\n/x/', '<T extends />;\u2028/x/', '<T extends />;\u2029/x/',
+ '<T extends /\\\n/>', '<T extends /[/>;', '<T extends /\\/>;', '<T extends /* c */ />;', '<T extends // c\n/>;\n/x/'];
+ for (const code of ELEMENTS) assert.deepStrictEqual(opens(code), ELEMENT, JSON.stringify(code));
for (const code of ['<T extends /=x/>(a: T) => a', '<T extends/=x/>(a: T) => a']) assert.deepStrictEqual(opens(code), GENERIC, code);
const ts = loadTypescriptOracle();
if (!ts) return t.diagnostic('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to check the readings');
@@ -1722,6 +1729,16 @@ test('`<T extends` and a `/` is an element where an expression starts and type p
assert.strictEqual(reading('interface I { <T extends />;f();[/]/>(a: T): T }'), 'CallSignature');
assert.strictEqual(reading('const f = <T extends /=x/>(a: T) => a;'), 'ArrowFunction');
assert.strictEqual(reading('let f: <T extends /=x/>(a: T) => T;'), 'FunctionType');
+ // Where its regex does not close on the line the text is no type in any place a type stands: the regex is unterminated (TS1161). A regex that closes leaves both — the pairs above.
+ for (const [what, frame] of [['an annotation', (head) => `let f: ${head}`], ['a type alias', (head) => `type F = ${head}`], ['an interface', (head) => `interface I { ${head} }`], ['a parameter', (head) => `function g(a: ${head}) {}`],
+ ['a construct signature', (head) => `interface I { new ${head} }`], ['an argument', (head) => `g<${head}>()`], ['a union', (head) => `let f: A | ${head}`]]) {
+ for (const head of ['<T extends />;', '<T extends/>;', '<T extends />;\nconst x = a / b;', '<T extends /x', '<T extends /\\\n/>(a: T) => T;']) {
+ assert.match(parseDiagnosticMessages(ts, frame(head)).join('\n'), /Unterminated regular expression literal/, `${what}: ${JSON.stringify(head)} is no type`);
+ }
+ }
+ for (const code of ['const e = <T extends />;', 'const e = <T extends/>;\nconst r = a / b;', 'const e = <div><T extends /></div>;']) assertTsParses(ts, code, `the element ${JSON.stringify(code)} parses`);
+ // The same text where the regex closes on its line is a function type that TypeScript parses: both readings compile, and the head is a guess.
+ for (const code of ['let f: <T extends />;f();[/]/>(a: T) => T;', 'let f: <T extends />; const r = a />(a: T) => T;']) assert.strictEqual(reading(code), 'FunctionType', code);
});
// A `>` in JSX text does not compile: TypeScript reports TS1382, "Unexpected token. Did you mean `{'>'}` or `&gt;`?" (the test after next checks it against the
@@ -2616,8 +2633,9 @@ test('the TSX rule and the generic function type read past every character TypeS
`<T${c}extends${c}X>(x: T) => x`, `<T${c},>(x: T) => x`, `<${c}T,>(x: T) => x`, `<const${c}T,>(x: T) => x`, `<T${c}= string>(x: T) => x`, `<T${c}${c}extends${c}${c}X>(x: T) => x`,
]) assert.deepStrictEqual(opens(code), GENERIC, visible(code));
for (const code of [`<T extends${c}>text</T>`, `<T${c}extends${c}>text</T>`, `<T${c}x>text</T>`, `<${c}T>text</T>`]) assert.deepStrictEqual(opens(code), ELEMENT, visible(code));
- // `extends` and a `/` is the guess whatever is between them (the test of the rule above says why).
- assert.deepStrictEqual(opens(`<T extends${c}/>`), { generic: false, ambiguity: 'generic' }, visible(`<T extends${c}/>`));
+ // `extends` and a `/` is the guess whatever is between them where the regex closes on its line, and an element where it does not (the test of the rule above says why).
+ assert.deepStrictEqual(opens(`<T extends${c}/>`), ELEMENT, visible(`<T extends${c}/>`));
+ assert.deepStrictEqual(opens(`<T extends${c}/x/>(a: T) => T`), { generic: false, ambiguity: 'generic' }, visible(`<T extends${c}/x/>(a: T) => T`));
// A generic function type has trivia between its `>`, its parameter list and its arrow: the list is found, and the type is certain.
for (const code of [`<T>${c}(x: T) => T`, `<T>(x: T)${c}=> T`, `<T>${c}(x: T)${c}=> T`]) assert.deepStrictEqual(opens(code), GENERIC, visible(code));
}
@@ -3075,14 +3093,21 @@ test('JSX text that starts with a parenthesis is an element, for certain, wherev
});
test('JSX text that starts with a parenthesis is a guess where the closing tag could be inside a template, a comment or a regex that its text opens: the element is read, nothing after it is trusted', (t) => {
- const pages = elementPages(GUESSED_ELEMENTS);
+ // Where a member of a type may begin at the head, the text could be a type's members; a list that the scan cannot read is a guess wherever the head stands.
+ const pages = [...elementPages(HIDDEN_TEXT_ELEMENTS, undefined, MEMBER_ELEMENT_FRAMES), ...elementPages(UNREAD_LIST_ELEMENTS)];
for (const { code, at, label } of pages) {
assert.deepStrictEqual(earliestAmbiguity(code), [at, 'generic'], label);
assert.notStrictEqual(maskOf(code)[code.indexOf('(', at)], '(', `${label}: read as an element`);
}
+ // After an `=`, a `(`, a `[`, a `:` or an `=>` no member of a type begins, and a head with a parameter list that neither `=>` nor `:` follows is an element, for certain, whatever its text holds.
+ const certain = elementPages(HIDDEN_TEXT_ELEMENTS, undefined, NO_MEMBER_ELEMENT_FRAMES);
+ for (const { code, at, label } of certain) {
+ assert.deepStrictEqual(ambiguities(code), [], label);
+ assert.notStrictEqual(maskOf(code)[code.indexOf('(', at)], '(', `${label}: read as an element`);
+ }
const ts = loadTypescriptOracle();
if (!ts) return t.diagnostic('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to check the readings');
- for (const { code, at, label } of pages) {
+ for (const { code, at, label } of [...pages, ...certain]) {
const source = cleanSourceFile(ts, code);
assert.ok(source, `TypeScript parses ${label}`);
assert.ok(isElement(readingAt(ts, source, at)), `${label}: TypeScript reads an element, so the guess is a cost`);
@@ -3113,13 +3138,15 @@ test('opensTypeParameters: a parameter list with no arrow and no colon after it
// The text is scanned as a type would scan it, as code: a `/` after a word or a number divides (and is an error in a type), a comment or a template that is closed before the closing tag
// hides nothing, and a line comment that ends before it hides nothing; a comment that is open at the closing tag, or a `//` on its line, hides it.
['<T>(x), a/b</T>', ELEMENT], ['<T>(x), 1/2 done</T>', ELEMENT], ['<T>(x);\n and/or more</T>', ELEMENT], ['<T>(x)\n `x`</T>', ELEMENT], ['<T>(x); /* c */ </T>', ELEMENT], ['<T>(x); // c\n</T>', ELEMENT],
- ['<T>(x), see https://x.y</T>', ELEMENT], ['<T>(x); // c </T>', GUESS], ['<T>(x);\n /* c </T>', GUESS], ['<T>(x); m: `a ${b} </T>', GUESS], ['<T>(x), = /re/ </T>', GUESS], ['<T>(x), return/exchange </T>', GUESS],
+ ['<T>(x), see https://x.y</T>', ELEMENT], ['<T>(x); // c </T>', GUESS], ['<T>(x);\n /* c </T>', GUESS], ['<T>(x); m: `a ${b} </T>', GUESS], ['<T>(x), = /re/ </T>', ELEMENT], ['<T>(x), return/exchange </T>', ELEMENT],
// Where the text before the first thing that could hide the closing tag cannot be the members of a type — two names on a line, a name and a string or a `/`, a template or a regex where a member
- // would begin — no type holds the closing tag in anything: an element. A name alone, a modifier, a name on the next line, a colon or a character that is no prose leaves both programs possible.
+ // would begin, a name and a sign, a `.` or a quote, a colon after a type — no type holds the closing tag in anything: an element. A name alone, a modifier, a name on the next line, a colon and a
+ // type, or a computed name leaves both programs possible.
['<T>(x); `a ${b} </T>', ELEMENT], ['<T>(x);\n /re </T>', ELEMENT], ['<T>(a = `x </T>`); m', GUESS],
["<T>(x), see 'a </T> b'", ELEMENT], ['<T>(x), a b // </T>', ELEMENT], ['<T>(x); 1 2 // </T>', ELEMENT], ['<T>(x), see a/b // </T>', ELEMENT], ['<T>(x);\n see https://x.y more\n </T>', ELEMENT], ['<T>(x), a, b c // </T>', ELEMENT],
- ['<T>(x), a // </T>', GUESS], ['<T>(x), a\n b // </T>', GUESS], ['<T>(x), readonly b // </T>', GUESS], ['<T>(x), get b // </T>', GUESS], ['<T>(x), public b // </T>', GUESS], ['<T>(x), see: https://x.y</T>', GUESS],
- ["<T>(x); 'a </T> b'", GUESS], ['<T>(x), a, // </T>', GUESS], ["<T>(x), it's // </T>", GUESS], ['<T>(x), é b // </T>', GUESS], ['<T>(x), a.b c // </T>', GUESS], ['<T>(x), a? b // </T>', GUESS],
+ ['<T>(x), see: https://x.y</T>', ELEMENT], ['<T>(x), é b // </T>', ELEMENT], ['<T>(x), a.b c // </T>', ELEMENT], ['<T>(x), a? b // </T>', ELEMENT], ["<T>(x), it's // </T>", ELEMENT], ['<T>(x), a-b // </T>', ELEMENT],
+ ['<T>(x), a // </T>', GUESS], ['<T>(x), a\n b // </T>', GUESS], ['<T>(x), readonly b // </T>', GUESS], ['<T>(x), get b // </T>', GUESS], ['<T>(x), public b // </T>', GUESS], ['<T>(x), see: a // </T>', GUESS],
+ ["<T>(x); 'a </T> b'", GUESS], ['<T>(x), a, // </T>', GUESS], ['<T>(x), a: b // </T>', GUESS], ['<T>(x), a? // </T>', GUESS], ['<T>(x), é // </T>', GUESS], ['<T>(x), default: // </T>', GUESS],
['<T>(x); m: { <U>(y: U): void }', GUESS], ['<T>(x); m: { a / b }</T>', GUESS], ['<T>(x), </T c></T>', GUESS], ['<T>(x), </* c */T>', CODE], ['<T>(x);', GUESS], ['<T>(x), <b>y', GUESS],
// A `</*` after the `)` is a `<`, a comment and a name: the next signature's type parameters, `</* c */T extends X>(y)`, which no closing tag is. (`</* c */T>` is one to the element reading.)
['<T>(x)\n</* c */T extends X>(y) }', CODE], ['<T>(x)\n</* c */T>(y)', CODE], ['<T>(x); </* c */T>(y) }', CODE], ['<T>(x)\n</ T>', ELEMENT], ['<T>(x)\n</ /* c */ T>', ELEMENT],
@@ -3132,6 +3159,87 @@ test('opensTypeParameters: a parameter list with no arrow and no colon after it
assert.deepStrictEqual(opensTypeParameters(`<T>(${'x, '.repeat(900)}x) }`, 0), GUESS);
});
+// A head that stands where no member of a type begins (NO_MEMBER_BEFORE) — after an `=` or an assignment operator, an `=>`, a `(`, a `[` and a `:`: a call signature, a construct signature and a method are members of a type, and a function type needs the
+// `=>` that its list lacks here, so `<Name>(…)` that neither `=>` nor `:` follows is an element whatever its text holds. Anywhere else a member may begin, and a text that could hide the closing tag makes the head a guess.
+test('opensTypeParameters, where no member of a type begins: a list that neither `=>` nor `:` follows is an element for certain, whatever its text holds; where one may begin the same text is a guess', () => {
+ const ELEMENT = { generic: false, ambiguity: null };
+ const GUESS = { generic: false, ambiguity: 'generic' };
+ const texts = ['<T>(x); // c </T>', "<T>(x); m: '</T>'", '<T>(x); m: `</T>`', '<T>(x);\n /* c </T>', '<T>(x), a // </T>', '<T>(x); [ // c\n/b </T>', '<T>(x), f(a = // c\n/b </T>', "<T>(x); 'a </T> b'", '<T>(x), readonly b // </T>', '<T>(x); m: { <U>(y: U): void }'];
+ for (const code of texts) {
+ assert.deepStrictEqual(opensTypeParameters(code, 0), GUESS, `where a member may begin: ${JSON.stringify(code)}`);
+ assert.deepStrictEqual(opensTypeParameters(code, 0, null, false, true), ELEMENT, `where none does: ${JSON.stringify(code)}`);
+ }
+ // A `:` after the list is a signature's return type and JSX text alike, and an `=>` a function type: the place decides neither.
+ for (const code of ['<T>(x): T }', '<T>(x): text</T>', '<T>(x) => y }', '<T>(x) => y</T>']) assert.deepStrictEqual(opensTypeParameters(code, 0, null, false, true), opensTypeParameters(code, 0), JSON.stringify(code));
+ // The tokens are the ones that are an operator or a bracket that opens what an expression or a type fills: a separator, a closing bracket, a `{`, a `?` and a keyword are not (`return <T>(x)` is a method named `return`, `m? <T>(x)` an optional one).
+ assert.deepStrictEqual([...NO_MEMBER_BEFORE].sort(), ['(', ':', '=', '=>', '[', '+=', '-=', '*=', '**=', '/=', '%=', '<<=', '&=', '|=', '^=', '&&=', '||=', '??='].sort());
+ for (const token of NO_MEMBER_BEFORE) assert.ok(ANGLE_AFTER.rule.includes(token), `${token} is read by the rule`);
+});
+
+// The tokens of NO_MEMBER_BEFORE are the tokens that no program has before type parameters with no arrow and no colon (TypeScript's parser says so), and every one of the other tokens that the rule is asked after has a program that does:
+// the pages below are parsed, and a head that is the type parameters of a signature is found in the tree.
+test('TypeScript: no program has type parameters with no arrow and no `:` after a token of NO_MEMBER_BEFORE; each token the rule reads that is left out has one, and the lexer does not read it as an element', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.diagnostic('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to check the tokens');
+ const typeParameters = (code) => {
+ const source = cleanSourceFile(ts, code);
+ if (!source) return null;
+ let found = false;
+ const visit = (node) => {
+ if (ts.isTypeParameterDeclaration(node) && node.name.text === 'T') found = true;
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ return found;
+ };
+ // Every place the token can stand, as syntax: the token is the operator, the `=>`, the bracket or the colon that precedes the head, so a program parses where the head is an element (a closing tag after it) and where it is none.
+ const assignment = (t) => [(tail) => `let a: any; a ${t} ${tail};`, (tail) => `let o: any; o.k ${t} ${tail};`, (tail) => `let a: any; (a) ${t} ${tail};`];
+ const framesOf = (token) => {
+ if (token === '=') return [...assignment(token), (tail) => `const a ${token} ${tail};`, (tail) => `class C { m ${token} ${tail} }`, (tail) => `function f(a ${token} ${tail}) {}`, (tail) => `const { a ${token} ${tail} } = o;`, (tail) => `type A<T ${token} ${tail}> = x;`];
+ if (token === '=>') return [(tail) => `const f = () ${token} ${tail};`, (tail) => `const f = async (a) ${token} ${tail};`, (tail) => `type F = () ${token} ${tail};`, (tail) => `const f = (a) ${token} ({ k: ${tail} });`];
+ if (token === '(') return [(tail) => `f ${token} ${tail});`, (tail) => `new f ${token} ${tail});`, (tail) => `if ${token} ${tail}) {}`, (tail) => `const a = f ${token} ${tail}, 1);`, (tail) => `interface I { m ${token} ${tail}): void }`, (tail) => `function f ${token} ${tail}) {}`];
+ if (token === '[') return [(tail) => `const l = ${token} ${tail}];`, (tail) => `a ${token} ${tail}];`, (tail) => `const { ${token} ${tail}]: v } = o;`, (tail) => `type Tup = ${token} ${tail}];`, (tail) => `interface I { ${token} ${tail}]: string }`];
+ if (token === ':') return [(tail) => `const o = { k ${token} ${tail} };`, (tail) => `const o = c ? a ${token} ${tail};`, (tail) => `let v ${token} ${tail};`, (tail) => `function f(a ${token} ${tail}) {}`, (tail) => `interface I { m ${token} ${tail} }`,
+ (tail) => `type L = { k ${token} ${tail} };`, (tail) => `class C { m ${token} ${tail} }`, (tail) => `a ${token} ${tail};`, (tail) => `switch (a) { case 1 ${token} ${tail}; }`, (tail) => `const e = <div x={c ? a ${token} ${tail}} />;`];
+ return assignment(token);
+ };
+ // What follows the token: an element that a closing tag ends, text that goes on, and what no arrow and no colon follows in a type, which no program parses after these tokens.
+ const tails = ['<T>(x)</T>', '<T>(x); m: 1 </T>', '<T>(x), y</T>', '<T>(x)', '<T>(x);', '<T>(x),', '<T>(x)\n'];
+ let programs = 0;
+ let elements = 0;
+ for (const token of NO_MEMBER_BEFORE) {
+ for (const frame of framesOf(token)) {
+ for (const tail of tails) {
+ const code = frame(tail);
+ const found = typeParameters(code);
+ if (found === null) continue;
+ programs += 1;
+ if (tail.endsWith('</T>')) elements += 1;
+ assert.strictEqual(found, false, `type parameters after ${token}: ${JSON.stringify(code)}`);
+ }
+ }
+ }
+ t.diagnostic(`${programs} programs that parse after the tokens of NO_MEMBER_BEFORE (${elements} with an element), none with type parameters`);
+ assert.ok(elements >= 40 && programs >= elements, `only ${programs} programs parse, ${elements} with an element`);
+ // The tokens that the rule reads and that are left out: each is a name or ends a member, so a program has type parameters there, and the lexer reads the head as a signature or a guess, never as the element it would be.
+ const witnesses = {
+ '?': 'interface I { m? <T>(x); a: "</T>" }', return: 'interface I { return <T>(x); a: "</T>" }', new: 'interface I { new <T>(x); a: "</T>" }', extends: 'interface I { extends <T>(x); a: "</T>" }', throw: 'interface I { throw <T>(x); a: "</T>" }',
+ case: 'interface I { case <T>(x); a: "</T>" }', else: 'interface I { else <T>(x); a: "</T>" }', do: 'interface I { do <T>(x); a: "</T>" }', yield: 'interface I { yield <T>(x); a: "</T>" }', of: 'interface I { of <T>(x); a: "</T>" }',
+ default: 'interface I { default <T>(x); a: "</T>" }', break: 'interface I { break <T>(x); a: "</T>" }', continue: 'interface I { continue <T>(x); a: "</T>" }', ',': 'interface I { a: A, <T>(x); b: "</T>" }',
+ ';': 'interface I { a: A; <T>(x); b: "</T>" }', '{': 'let a: { <T>(x); b: "</T>" };', ')': 'interface I { m(x)\n<T>(y); b: "</T>" }', '}': 'interface I { a: { b: 1 }\n<T>(y); b: "</T>" }',
+ };
+ for (const token of ANGLE_AFTER.rule) {
+ if (NO_MEMBER_BEFORE.has(token)) continue;
+ const code = witnesses[token];
+ assert.ok(code, `a program with type parameters after ${token}`);
+ assert.strictEqual(typeParameters(code), true, `TypeScript reads type parameters after ${token}: ${JSON.stringify(code)}`);
+ const head = code.indexOf('<T>');
+ // The head is a guess, or is read as the type parameters it is (a `(` that the mask keeps); it is never the element it would be after an `=`.
+ const guessed = ambiguities(code).some(([at]) => at === head);
+ assert.ok(guessed || maskOf(code)[head + 3] === '(', `${token}: the lexer reads the head as an element for certain: ${JSON.stringify(code)}`);
+ }
+});
+
// A parameter list whose first token no parameter starts with — a number, a string, a template, a `#`, an operator, a parenthesis — is TS1003 in a call signature, a construct signature and a function type
// alike, so only the element compiles, with a `:` after the list or without one: `<li>(1): First</li>` is JSX text, and a call after it is read. A list that may hold parameters, or whose first character is
// not judged (beyond ASCII, a `.` that may start `...`), leaves both readings (parameterListMayStart).
@@ -3159,15 +3267,17 @@ test('a parameter list that can hold no parameters makes the head an element, fo
// The parenthesis scan of a parameter list skips comments and strings, but reads a regex, JSX text and a statement as code and ends a template at its first back-tick, so where the list may
// hold an expression — after an `=`, a `[` other than `[]`, an `@` or `import` — the `)` it finds may be another: in `interface I { <T>(a = /[)]/); m: '</T>…' }` the `]` after the regex's
-// `)` read as the text of an element, and the string's token was rewritten. Each head below is a guess in every frame a signature stands in, whatever follows it.
+// `)` read as the text of an element, and the string's token was rewritten. A default whose first token is a regex or an element is read exactly now (initializerReading), a `/` after a
+// name or a number divides, and a template with no `${` holds nothing but itself; every other head below is a guess in every frame a signature stands in, whatever follows it.
const RISKY_LIST_HEADS = [
- '<T>(a = /[)]/)', '<T>(a = /\\)/)', "<T>(a = /'/, b = '')", '<T>(a = // c\n /[)]/)', '<T>(a = () => { if (x) /[)]/.test(y) })', '<T>(@d(/[)]/) a)', '<T>(a: { [/[)]/.source]: 1 })',
- '<T>(a = /[/*]/)', '<T>(a = /\\/*/)', '<T>(a = /(/)', '<T>(a = /[)(]/)', '<T>(a = `${`)`}`)', '<T>(a = `${"}" + `)`}`)', '<T>(a = `${/}/.source + `)`}`)',
+ '<T>(a = () => { if (x) /[)]/.test(y) })', '<T>(@d(/[)]/) a)', '<T>(a: { [/[)]/.source]: 1 })',
+ '<T>(a = `${`)`}`)', '<T>(a = `${"}" + `)`}`)', '<T>(a = `${/}/.source + `)`}`)',
'<T>(a = function () { if (x) /[)]/.test(y) })', '<T>(a = class { static { if (x) ; else {} /[)]/.test(y) } })', '<T>(a = typeof /[)]/)', '<T>(a = class C implements /[)]/ {})',
- // A regex that a `*` or a `/` follows, a block after a return type, `break` and a line break, a spread, a default after type arguments, an import type's attributes, JSX in a template and
- // in a default: each holds what the scan misreads, and only the `=`, the `[` or `import` before it says so.
- '<T>(a = /x/*1)', '<T>(a = /x//1)', '<T>(a = function (): number[] { if (a) /[)]/.test(""); return [] })', '<T>(a = () => { for (;;) { break\n/[)]/.test("") } })', '<T>(a = [.../[)]/.source])',
- '<T>(a: A<B>= /[)]/)', '<T>(a: import("x", { with: { k: /[)]/ } }))', "<T>(a = `${<p>it's</p>}${'}' + `)`}`)", '<T>(a = <p>)</p>)', "<T>(a = <p>it's</p>)", '<T>(a = <p x="\\" y=")" />)',
+ // A regex that a `/` follows, a block after a return type, `break` and a line break, a spread, a default after type arguments, an import type's attributes, JSX in a template: each holds what the
+ // scan misreads, and only the `=`, the `[` or `import` before it says so. So does a regex or an element that is no default's first token, and a `/` after what is no name or number.
+ '<T>(a = /x//1)', '<T>(a = function (): number[] { if (a) /[)]/.test(""); return [] })', '<T>(a = () => { for (;;) { break\n/[)]/.test("") } })', '<T>(a = [.../[)]/.source])',
+ '<T>(a: A<B>= /[)]/)', '<T>(a: import("x", { with: { k: /[)]/ } }))', "<T>(a = `${<p>it's</p>}${'}' + `)`}`)", '<T>(a = f(/[)]/))', '<T>(a = x ? /[)]/ : y)', '<T>(a = b + /[)]/)', "<T>(a = f(<p>it's</p>))",
+ '<T>(a = <p>)</p> / 2)', '<T>(a: A<B> = /[)]/)', '<T>(a = <p>(</p>, b = <q>)</q>)', '<T>(a = b / (c) / d)', '<T>(a = x, b = /[)]/)',
// A template literal type nests with no `=` before it: the scan's skip ends at the inner back-tick, and only a template that is whole is skipped (templateSkipIsWhole) — not one with a
// template in a substitution, behind a string type that holds a brace, or behind a comment that holds one.
'<T>(a: `${`)`}`)', '<T>(a: `${"}" | `)`}`)', '<T>(a: `${/* } */ `)`}`)',
@@ -3179,6 +3289,17 @@ const RISKY_LIST_HEADS = [
// an expression too, and a `/`, a `<` or a back-tick after one leaves the scan untrusted.
'<T>(a: { get x() { return 1 / 2 } })', '<T>(a: { set x(v) { v / 2 } })', '<T>(a: { get x() { return <p>)</p> } })', '<T>(a: { get x() { return <p>(</p> } })',
'<T>(f: <U extends /x/>() => void)', '<T>(a: { m<U extends /x/>(): void })',
+ // A regex after a line comment: the last token is the operator, keyword or bracket before the comment, and the word that the comment ends in is no operand, so the `)` in the regex is no end of the list; a `/` after a
+ // block comment, which ends in a `/`, and after a line break with no comment are the same guess, and so is a division after a line comment, which is as valid (slashFollowsAnOperand).
+ '<T>(a = 1 + // c\n/[)]/)', '<T>(a = x || // c\n/\\)/)', '<T>(value: T, pattern = /\\s/ || // fallback\n /\\)/)', '<T>(a: T, re = x && // c1\r\n/(x)/)', '<T>(a = f(// $\n/[)]/))', '<T>(a = 1 + // c\u2028/[)]/)', '<T>(a = x ?? // c\r/[)]/)',
+ '<T>(a: <U extends // c\n/x)/>(b: U) => U)', '<T>(a = b // c\n/ (c))', '<T>(a = 1 // c\n/ 2)', '<T>(a = 1 + /* c */ /[)]/)', '<T>(a = 1 +\n/[)]/)',
+];
+// ... and the heads that hold a default whose first token is a regex or an element, a division of a name or a number, or a template with no substitution: the scan finds the `)` that ends the list
+// exactly, so a signature that nothing after it can make an element is code for certain, and a closing tag in a string after it is data.
+const EXACT_LIST_HEADS = [
+ '<T>(a = /[)]/)', '<T>(a = /\\)/)', "<T>(a = /'/, b = '')", '<T>(a = // c\n /[)]/)', '<T>(a = /[/*]/)', '<T>(a = /\\/*/)', '<T>(a = /(/)', '<T>(a = /[)(]/)', '<T>(a = /x/*1)', '<T>(a = /x/g)', '<T>(a = /=x/)',
+ '<T>(a = <p>)</p>)', "<T>(a = <p>it's</p>)", '<T>(a = <p x="\\" y=")" />)', '<T>(a = <p/>)', '<T>(a = <A.B>)</A.B>)', '<T>(a = <p x={")"}>y</p>)', '<T>(a = <p>{")"}</p>)',
+ '<T>(a = `)`)', '<T>(a = `(`, b = `)`)', '<T>(a = `\\``)', '<T>(a = b/(c))', '<T>(a = 1/2)', '<T>(a = b/c/d)',
];
// ... and the lists that hold none of those: a `/` there is in no type, so the text is the element's; text whose parameters fail before a type, a default or a pattern; a list in which
// something may start an expression but no `/`, `<` or back-tick follows, which the scan reads exactly; a template literal type.
@@ -3203,9 +3324,12 @@ const PLAIN_LIST_ELEMENTS = [
'<p>(Tip: this works best in <a href="/x">Chrome</a>)</p>', '<p>(Note: this is a preview, see <a href="/docs">docs</a>)</p>', '<p>(Type: string, <a href="/x">docs</a>)</p>',
'<p>(this opens <a href="/x">settings</a>)</p>',
];
-// ... and the text in which something may start an expression and a `/`, a `<` or a back-tick follows, which a signature's parameter list shares: the guess.
-const INITIALIZER_LIST_ELEMENTS = ['<p>(a = /x/)</p>', '<p>(a = b/(c))</p>', '<p>(a = /(x)/)</p>', '<p>(a = <b>c</b>)</p>', '<p>(a = `x`)</p>'];
-test('a parameter list in which an expression may start and a `/`, a `<` or a back-tick follows is a guess; one without is read as before', (t) => {
+// ... and the text in which something may start an expression and a `/`, a `<` or a back-tick follows, which a signature's parameter list shares: the guess — except where the default's first token is a
+// regex or an element, a `/` divides a name or a number, or the template has no `${`, which the scan reads exactly (EXACT_INITIALIZER_ELEMENTS).
+const INITIALIZER_LIST_ELEMENTS = ['<p>(a = f(/x/))</p>', '<p>(a = (b)/c)</p>', '<p>(a = typeof /x/)</p>', '<p>(a = <b>c</b> / 2)</p>', '<p>(a = `${b}`)</p>', '<p>(a = x ? /y/ : z)</p>', '<p>(a = [/x/])</p>', '<p>(a = b + /x/)</p>'];
+const EXACT_INITIALIZER_ELEMENTS = ['<p>(a = /x/)</p>', '<p>(a = b/(c))</p>', '<p>(a = /(x)/)</p>', '<p>(a = <b>c</b>)</p>', '<p>(a = `x`)</p>', '<p>(a = /[)]/)</p>', '<p>(score = 3/5)</p>', '<p>(Status = <Badge>OK</Badge>)</p>',
+ '<p>(rate = 4/5 stars)</p>', '<p>(x = 1/2, y = 3/4)</p>', '<p>(a = <b/>)</p>', "<p>(a = <b>it's</b>)</p>", '<p>(a = <b>(c)</b>)</p>', '<p>(a = `)`)</p>'];
+test('a parameter list in which an expression may start and a `/`, a `<` or a back-tick follows is a guess unless the scan reads it exactly; one without is read as before', (t) => {
const pages = [];
for (const [frameName, frame] of SIGNATURE_FRAMES) {
for (const head of RISKY_LIST_HEADS) {
@@ -3215,8 +3339,24 @@ test('a parameter list in which an expression may start and a `/`, a `<` or a ba
}
}
for (const { code, at, label } of pages) assert.deepStrictEqual(earliestAmbiguity(code), [at, 'generic'], label);
+ // The heads the scan reads exactly: no guess, the signature is code, the token in the string after it is data and the real call is read.
+ const exact = [];
+ for (const [frameName, frame] of SIGNATURE_FRAMES) {
+ for (const head of EXACT_LIST_HEADS) {
+ for (const ending of ['', ';\n m: string', '\n <U>(y)']) {
+ for (const [decoyName, decoy] of Object.entries(DECOYS)) {
+ if (decoyName !== 'double-quoted string') exact.push({ ...signaturePage(frame, head, ending, decoy), label: `${frameName} / ${JSON.stringify(head)} / ${JSON.stringify(ending)} / ${decoyName}` });
+ }
+ }
+ }
+ }
+ for (const { code, label } of exact) {
+ assert.deepStrictEqual(ambiguities(code), [], label);
+ assert.deepStrictEqual(strayPageRefs(code).map((found) => found.start), [code.indexOf('PAGEREF_detail')], `${label}: the token in the decoy is stray, and the real call is not`);
+ assert.deepStrictEqual(navReferencedKeys(code), ['detail'], label);
+ }
const call = 'navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})';
- for (const element of PLAIN_LIST_ELEMENTS) assert.deepStrictEqual(strayPageRefs(`const e = ${element};\n${call};\n`), [], element);
+ for (const element of [...PLAIN_LIST_ELEMENTS, ...EXACT_INITIALIZER_ELEMENTS]) assert.deepStrictEqual(strayPageRefs(`const e = ${element};\n${call};\n`), [], element);
for (const element of INITIALIZER_LIST_ELEMENTS) assert.deepStrictEqual(earliestAmbiguity(`const e = ${element};\n${call};\n`), [10, 'generic'], element);
assert.deepStrictEqual(opensTypeParameters('<T>(x: `a${string}`) => T', 0), { generic: true, ambiguity: null }, 'a template literal type is skipped whole');
// ... and so is one in whose substitution something may start an expression with no `<` after it: no JSX is in it, and its strings are strings.
@@ -3240,13 +3380,13 @@ test('a parameter list in which an expression may start and a `/`, a `<` or a ba
const ts = loadTypescriptOracle();
if (!ts) return t.diagnostic('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to check the readings');
// The double-quoted decoy holds the call's own double quotes, so it parses in no frame; the others parse everywhere.
- for (const { code, at, label } of pages.filter((page, index) => index % 5 === 0 && !page.label.endsWith('/ double-quoted string'))) {
+ for (const { code, at, label } of [...pages, ...exact].filter((page, index) => index % 5 === 0 && !page.label.endsWith('/ double-quoted string'))) {
const source = cleanSourceFile(ts, code);
assert.ok(source, `TypeScript parses ${label}`);
assert.ok(!isElement(readingAt(ts, source, at)), `${label}: TypeScript reads a signature`);
}
- const declared = 'declare const done: number, total: number, url: string, a: any, b: any, c: any, y: any;\n';
- for (const element of [...PLAIN_LIST_ELEMENTS, ...INITIALIZER_LIST_ELEMENTS]) assertTsParses(ts, `${declared}const e = ${element};`, element);
+ const declared = 'declare const done: number, total: number, url: string, a: any, b: any, c: any, y: any, x: any, rate: any, score: any, Status: any;\n';
+ for (const element of [...PLAIN_LIST_ELEMENTS, ...EXACT_INITIALIZER_ELEMENTS, ...INITIALIZER_LIST_ELEMENTS]) assertTsParses(ts, `${declared}const e = ${element};`, element);
for (const list of FAILING_LISTS) {
for (const code of [`interface I { <T>(${list}) }`, `type F = <T>(${list}) => void;`]) assert.ok(parseDiagnosticMessages(ts, code).length > 0, `TypeScript rejects ${JSON.stringify(code)}`);
}
@@ -3425,6 +3565,304 @@ test('a parameter type that fails at its second token fails the list, wherever T
assert.ok(failed >= 60000, `only ${failed} lists were read as no list`);
});
+// ─── JSX text that starts with a parenthesis and a label, where the list that the text would be fails ───────────────────────────────────────────────────────────
+//
+// A hint after a label is JSX text: `<p>(Size: 10 MB max, <a href="/x">upgrade</a>)</p>`. In a type the same characters are a parameter list, `Size: 10` and then more, and a call after the element was refused while the
+// text could be one. Each text below is a list that TypeScript rejects in a call signature, a construct signature and a function type alike — the label is a parameter's name, and what follows its colon is a type that
+// fails at its second token — so only the element compiles, and the lexer says so (typeStartFails, genericFunctionTypeFollows):
+// a number and a name `10 MB` a number literal is a type, which ends there; a name after it is TS1005 unless it is a conditional type's `extends`
+// an object type `{user.name}` a member is a name and then `?`, `:`, `(`, `<`, `,`, `;`, the `}` or a line's end; a `.` or an operator after it is TS1131
+// `new` `new <a href=` a constructor type is `new`, type parameters if a `<` follows, and a `(`: anything else after `new` is TS1005
+// `import` `import <a href=` an import type is `import` and a `(`: anything else after it is TS1005
+// an `=` `use <code>=</code>` the `=` after the type `use<code>` is an initializer's, and no expression starts with `</` (TS1109)
+const LIST_FRAMES = [(list) => `interface I { <T>(${list}): string }`, (list) => `interface C { new <T>(${list}): string }`, (list) => `type F = <T>(${list}) => string;`, (list) => `interface I { <T>(${list}) }`];
+const readsAsNoList = (list) => {
+ const read = opensTypeParameters(`<T>(${list}): x</T>`, 0);
+ return !read.generic && read.ambiguity === null;
+};
+const FAILING_LIST_TEXTS = [
+ ['a number and a name', 'Size: 10 MB max, <a href="/x">upgrade</a>', /',' expected/],
+ ['an object type whose first member is no member', 'Name: {user.name}, <a href={profile}>edit</a>', /Property or signature expected/],
+ ['`new` and type parameters that fail', 'Mode: new <a href="/x">beta</a>', /',' expected/],
+ ['`import` and no parenthesis', 'Hint: import <a href="/x">docs</a>', /'\(' expected/],
+ ['an `=` and a closing tag', 'Tip: use <code>=</code>', /Expression expected/],
+];
+// The page an author writes: the hint is in the component, and a button navigates to another page.
+const hintPage = (text) => `import * as React from "react";\n\nexport default function UploadPage() {\n const open = () => navigateTo({ pageType: "generative", pageId: "PAGEREF_detail" });\n return (\n <div>\n <p>${text}</p>\n <button onClick={open}>Open</button>\n </div>\n );\n}\n`;
+test('JSX text that starts with a parenthesis and a label is an element, for certain, where the list it would be fails: a number and a name, an object type that is none, `new`, `import`, an `=` and a closing tag', (t) => {
+ for (const [what, list] of FAILING_LIST_TEXTS) {
+ assert.deepStrictEqual(opensTypeParameters(`<p>(${list})</p>`, 0), ELEMENT, what);
+ assert.strictEqual(readsAsNoList(list), true, what);
+ // The page resolves: no guess, the one real call is read, its token is the page id and nothing is left over.
+ const page = hintPage(`(${list})`);
+ assert.deepStrictEqual(ambiguities(page), [], `${what}: no guess`);
+ assert.deepStrictEqual(strayPageRefs(page), [], `${what}: no token is left`);
+ assert.deepStrictEqual(navReferencedKeys(page), ['detail'], `${what}: the call is read`);
+ assert.deepStrictEqual(pageStructureProblems(page), [], `${what}: a complete page`);
+ }
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.diagnostic('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to check the readings');
+ for (const [what, list, message] of FAILING_LIST_TEXTS) {
+ for (const frame of LIST_FRAMES) assert.match(parseDiagnosticMessages(ts, frame(list)).join('\n'), message, `${what}: TypeScript rejects ${frame(list)}`);
+ const source = cleanSourceFile(ts, hintPage(`(${list})`));
+ assert.ok(source, `${what}: TypeScript parses the page`);
+ assert.ok(isElement(readingAt(ts, source, hintPage(`(${list})`).indexOf('<p>'))), `${what}: and reads an element`);
+ }
+});
+
+// What each rule reads as no list, and what it leaves: every list is put in a call signature, a construct signature and a function type, and TypeScript says which parse. A list read as no list is rejected in all of
+// them; a list that TypeScript parses is never read so. The rows in GUESSED are lists that parse, or that no rule here reads (a number with an exponent or a radix, a name beyond ASCII, a string).
+const LIST_RULES = {
+ number: {
+ failing: ['Size: 10 MB', 'Size: 10 MB max, <a href="/x">upgrade</a>', 'Size: -5 px', 'Size: - 5 px', 'Size: -\n5 px', 'Size: 1.5 GB', 'Size: 0 items', 'Size: 007 MB', 'Size: 10\nMB', 'Size: 10\u00a0MB', 'Size: 10\u0085MB', 'Size: 10\u2028MB',
+ 'Size: 10/* c */MB', 'Size: 10 // c\nMB', 'a, b: 10 MB', 'a: this is 10 MB', 'a: Foo<10 MB>', 'a: Foo<10 MB, c>', 'Size: 10 in', 'Size: 10 is', 'Size: 10 as', 'Size: 10 keyof', 'Size: 10 new', 'Size: 10 of x'],
+ guessed: ['Size: 10', 'Size: 10 extends X ? 1 : 2', 'Size: 10\nextends X ? 1 : 2', 'Size: 10 | 20', 'Size: 10[]', 'Size: 10 & X', 'Size: 10, b', 'Size: -10 | 5', 'Size: 10MB', 'Size: 0x1F MB', 'Size: 1e3 MB', 'Size: 1_000 MB',
+ 'Size: 10n MB', 'Size: .5 MB', 'Size: 10. MB', 'Size: 1.5.2 MB', 'Size: 10 MB\u00e9', 'Size: 10 \\u004dB', 'Size: 10 \u00e9', 'Size: "10" MB', 'Size: +10 MB', 'Size: --10 MB'],
+ },
+ 'object type': {
+ failing: ['Name: {user.name}', 'Name: {a.b.c}', 'Name: { a . b }', 'Name: {a\n.b}', 'Name: {a /* c */ . b}', 'Name: {a // c\n.b}', 'Name: {count + 1}', 'Name: {a - b}', 'Name: {a * b}', 'Name: {a % b}', 'Name: {a & b}', 'Name: {a | b}',
+ 'Name: {a ^ b}', 'Name: {a!}', 'Name: {a ~ b}', 'Name: {a / b}', 'Name: {this.x}', 'Name: {readonly.x}', 'Name: {get.x}', 'Name: {set + 1}', 'Name: {items.length}', 'Name: {new.x}', 'Name: {a.}', 'Name: {a...b}',
+ 'Name: {a.b}, <a href={profile}>edit</a>', 'a, b: {c.d}', 'a: this is {c.d}', 'a: Foo<{c.d}>'],
+ guessed: ['Name: {count}', 'Name: {a: T}', 'Name: {a?: T}', 'Name: {a(): T}', 'Name: {a<T>(): T}', 'Name: {a, b}', 'Name: {a; b}', 'Name: {a\nb}', 'Name: {readonly a: T}', 'Name: {readonly .5: T}', 'Name: {get .5(): T}', 'Name: {a\n.5}',
+ 'Name: {a .5}', 'Name: {a = 1}', 'Name: {a?.b}', 'Name: {"a".b}', 'Name: {1.b}', 'Name: {\u00e9.x}', 'Name: {\\u0061.x}', 'Name: {...a}', 'Name: {[k]: T}', 'Name: {}', 'Name: { }', 'Name: {a b}', 'Name: {a = b.c}'],
+ },
+ new: {
+ failing: ['Mode: new feature', 'Mode: new', 'Mode: new <a href="/x">beta</a>', 'Mode: new <a b>', 'Mode: new <a href=', 'Mode: new, b', 'Mode: new = 1', 'Mode: new.target', 'Mode: new\nfeature', 'Mode: new /* c */ feature', 'Mode: new 1',
+ 'Mode: new "x"', 'a, b: new c', 'a: this is new c', 'a: Foo<new c>', 'Mode: new <a b="c">', 'Mode: new [x]', 'Mode: new { a: T }'],
+ guessed: ['Mode: new () => T', 'Mode: new (x: T) => T', 'Mode: new <T>() => T', 'Mode: new <T>(x: T) => T', 'Mode: new <T, U>() => T', 'Mode: new <const T>() => T', 'Mode: new <T extends X>() => T', 'Mode: new <T = X>() => T', 'Mode: new\n() => T',
+ 'Mode: new /* c */ () => T', 'Mode: new <in T>() => T', 'Mode: new <private x>() => x', 'Mode: new\\u0078', 'Mode: new\u00e9', 'Mode: newx', 'Mode: abstract new () => T', 'Mode: typeof new', 'Mode: new<T>() => T', 'Mode: new <a.b c>'],
+ },
+ import: {
+ failing: ['Hint: import <a href="/x">docs</a>', 'Hint: import from CSV', 'Hint: import', 'Hint: import.meta', 'Hint: import, b', 'Hint: import\nx', 'Hint: import /* c */ x', 'Hint: import <a>', 'Hint: import = 1', 'Hint: import {a}', 'a, b: import c',
+ 'a: this is import c', 'a: Foo<import c>', 'Hint: import "x"', 'Hint: import 1'],
+ guessed: ['Hint: import("x")', 'Hint: import ("x")', 'Hint: import\n("x")', 'Hint: import /* c */ ("x")', 'Hint: typeof import("x")', 'Hint: import("x").A<B>', 'Hint: import("x", { with: { k: "v" } })', 'Hint: imported',
+ 'Hint: import\u00e9', 'Hint: import\\u0078'],
+ },
+ 'equals and a closing tag': {
+ failing: ['Tip: use <code>=</code>', 'a = </x>', 'a: T = </x>', 'a?: T = </x>', 'a: A<B>=</x>', 'a: A<B> = </x>', 'a, b = </x>', 'a = /* c */ </x>', 'a =\n</x>', 'a = // c\n</x>', 'a: <U = </x>>() => U', 'a: { b: T } = </x>',
+ 'a = </ x>', 'a = </>', 'a = \u00a0</x>', 'a = \u0085</x>', 'Tip: <b>a</b> <code>=</code> <b>b</b>', 'a: x<=</c>'],
+ guessed: ['a = </* c */ T,>(x) => x', 'a = </* c */ x>', 'a = <b>=</b>', 'a = <></>', 'a = < /x>', 'a = <b>x</b>', 'a = x</x>', 'a = 1 </x>', 'a: A<B> = x'],
+ },
+};
+test('each rule that reads a list as no list reads the lists it is meant for, and no list that TypeScript parses', (t) => {
+ for (const [rule, { failing, guessed }] of Object.entries(LIST_RULES)) {
+ for (const list of failing) assert.strictEqual(readsAsNoList(list), true, `${rule}: ${JSON.stringify(list)} is no list`);
+ for (const list of guessed) assert.strictEqual(readsAsNoList(list), false, `${rule}: ${JSON.stringify(list)} is not read as no list`);
+ }
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.diagnostic('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to check the readings');
+ let parsing = 0;
+ for (const [rule, { failing, guessed }] of Object.entries(LIST_RULES)) {
+ for (const list of failing) for (const frame of LIST_FRAMES) assert.ok(parseDiagnosticMessages(ts, frame(list)).length > 0, `${rule}: TypeScript rejects ${JSON.stringify(frame(list))}`);
+ // The lists the rule leaves are the ones it must: they include lists that parse (the property is not vacuous), each in some frame.
+ for (const list of guessed) if (LIST_FRAMES.some((frame) => parseDiagnosticMessages(ts, frame(list)).length === 0)) parsing += 1;
+ }
+ assert.ok(parsing >= 40, `only ${parsing} of the lists that are left parse in TypeScript`);
+});
+
+// The same, as a sweep over generated variants: the words (every keyword TypeScript has, and names), white space of every kind TypeScript skips between two tokens, comments, line breaks, letters beyond ASCII and
+// escapes, the endings that could complete a list. Wherever the lexer reads a list as no list, TypeScript rejects it in all of the frames: a list that parses and is read as no list would be read as JSX text, and the
+// text of the type after it as an element's.
+test('sweep (TypeScript parser): a list that a rule reads as no list is rejected by TypeScript in a call signature, a construct signature and a function type', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const keywords = [];
+ for (let kind = ts.SyntaxKind.FirstKeyword; kind <= ts.SyntaxKind.LastKeyword; kind += 1) keywords.push(ts.tokenToString(kind));
+ const words = [...keywords, 'MB', 'max', 'x', 'user', 'count', 'a1', '$a', '_a', '\u00e9', '\u03a9mega', '\\u0078'];
+ const space = [' ', '\n', '\t', '\u00a0', '\u0085', '\u200b', '\u2028', '\ufeff', '/* c */', ' /* c\n */ ', ' // c\n ', '\r\n', ''];
+ const lists = new Map();
+ const add = (family, list) => { if (!lists.has(list)) lists.set(list, family); };
+ // A number and a word: every word after a few numbers and every white space after each of them.
+ const numbers = ['10', '1.5', '0', '-10', '- 10', '-1.5', '007', '1e3', '0x1F', '10n', '1_000', '.5', '10.', '1.5.2', '+10'];
+ for (const number of numbers) for (const word of words) add('number', `Size: ${number} ${word} max, <a href="/x">upgrade</a>`);
+ for (const number of ['10', '-5', '1.5']) for (const gap of space) for (const word of ['MB', 'extends', 'in', 'new']) for (const tail of ['', ' T ? 1 : 2', ', b', '[]']) add('number', `Size:${gap}${number}${gap}${word}${tail}`);
+ // An object type: every name before each character that may follow it, with each ending.
+ const junk = ['.', '+', '-', '*', '%', '&', '|', '^', '!', '~', '/', '?', ':', '(', '<', ',', ';', '=', '[', '>', '?.', '...', '.5', '..', '=>', '#', '"x"', '5', '{'];
+ const endings = ['}', ' b }', ': T }', '5 }', '.5: T }', '(): T }', '"x" }', '[k: string]: T }'];
+ for (const name of words) for (const j of junk) for (const end of ['}', ' b }']) add('object type', `Name: {${name}${j}${end}`);
+ for (const gap of [' ', '\n', '/* c */', '\u00a0', '']) for (const name of ['a', 'readonly', 'get', 'set', 'new', 'static', 'break']) for (const j of junk) for (const end of endings) add('object type', `Name: {${gap}${name}${gap}${j}${end}`);
+ // `new` and `import`, with everything that may follow them.
+ const follows = [...words.filter((word) => !word.startsWith('\\')), '<a href="/x">beta</a>', '<T>', '<T,>', '<T extends X>', '<a b>', ')', ',', '=', '[', '{', '(', '()', '(x)', '(x: T) => T', '<T>(x: T) => T', '<T>() => T', '("x")', '(x, y)',
+ '.meta', '*', '/', '|', '&', '?', ':', '...', '1', '"x"', '`x`'];
+ for (const head of ['new', 'import', 'abstract new', 'typeof import', 'keyof new']) {
+ for (const gap of [' ', '\n', '/* c */', '\u00a0', '']) for (const follow of follows) {
+ if (gap === '' && /^[A-Za-z0-9_$\u00e9\u03a9]/.test(follow)) continue;
+ for (const tail of ['', ' end']) add(head, `Mode: ${head}${gap}${follow}${tail}`);
+ }
+ }
+ // An `=` and a closing tag, in every place a default stands.
+ for (const gap of space) for (const before of ['a = ', 'a: T = ', 'a?: T = ', 'a: A<B>=', 'a, b =', 'Tip: use <code>=', 'a: <U = ', 'a: x<=', 'a: { b: T } = ', '{ a }: P = ']) {
+ for (const tag of ['</code>', '</x>', '</ x>', '</>', '</* c */ T,>(x) => x', '</* c */ x>', '< /x>', '<b>=</b>', '<b>x</b>', '<></>', '</x', '</']) add('equals', `${before}${gap}${tag}`);
+ }
+ const claimed = new Map();
+ const unsound = [];
+ for (const [list, family] of lists) {
+ if (!readsAsNoList(list)) continue;
+ claimed.set(family, (claimed.get(family) || 0) + 1);
+ if (LIST_FRAMES.some((frame) => parseDiagnosticMessages(ts, frame(list)).length === 0)) unsound.push(JSON.stringify(list));
+ }
+ t.diagnostic(`${lists.size} lists; read as no list: ${[...claimed].map(([family, n]) => `${family} ${n}`).join(', ')}`);
+ assert.deepStrictEqual(unsound.slice(0, 8), [], `${unsound.length} lists that TypeScript parses are read as no list`);
+ for (const [family, least] of [['number', 800], ['object type', 3000], ['new', 500], ['import', 500], ['equals', 400]]) assert.ok((claimed.get(family) || 0) >= least, `${family}: only ${claimed.get(family) || 0} lists were read as no list`);
+});
+
+// ─── A default value that the scan reads exactly ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+//
+// The parenthesis scan of a parameter list reads a regex, JSX and a statement as code, so once a default value may hold one the `)` it finds may be another, and the list is a guess (`interface I { <T>(a = /[)]/); … }`).
+// Three things are read exactly, because TypeScript reads them one way: the first token of a default is a regex if it is a `/` (an expression starts after the `=` and nothing is there to divide), which ends at its
+// own `/` on its line, and an element if it is a `<` that the arrow rule leaves one, which ends at its closing tag; a `/` after a name or a number divides in an expression; and a template with no `${` holds only its own
+// text. The `=` must be an initializer's, so no `<` stands before it (it may be a type parameter's default, where a `<` opens a function type), and a `{` before the `/` may open a function body, where a statement
+// starts. A regex that its line does not close is unterminated (TS1161), and an `=` before `</` is no default at all (TS1109). EXACT_DEFAULTS and UNREAD_DEFAULTS are in helpers/angle-frames.js.
+test('a default value whose first token is a regex or an element, a division of a name or a number, and a template with no substitution are read exactly; every other default stays a guess', (t) => {
+ const GUESS = { generic: false, ambiguity: 'generic' };
+ const call = 'navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})';
+ for (const [kind, defaults] of Object.entries(EXACT_DEFAULTS)) {
+ for (const value of defaults) {
+ for (const label of ['a = ', 'a: T = ', 'a?: T = ', 'a, b = ', 'a=', '{ a }: P = ']) {
+ // The element reading: the closing tag right after the `)`, where no type has one.
+ assert.deepStrictEqual(opensTypeParameters(`<p>(${label}${value})</p>`, 0), ELEMENT, `${kind}: ${JSON.stringify(`<p>(${label}${value})</p>`)}`);
+ // The type reading: the signature ends at the `)`, and the `}` after it ends the type — code, for certain.
+ assert.deepStrictEqual(opensTypeParameters(`<p>(${label}${value}) }`, 0), GENERIC, `${kind}: ${JSON.stringify(`<p>(${label}${value}) }`)}`);
+ }
+ assert.deepStrictEqual(strayPageRefs(`const e = <p>(a = ${value})</p>;\n${call};\n`), [], `${kind}: ${JSON.stringify(value)}: the call after the element is read`);
+ }
+ }
+ for (const value of UNREAD_DEFAULTS) {
+ assert.deepStrictEqual(opensTypeParameters(`<p>(a = ${value})</p>`, 0), GUESS, JSON.stringify(value));
+ assert.deepStrictEqual(opensTypeParameters(`<p>(a = ${value}) }`, 0), GUESS, JSON.stringify(value));
+ }
+ // The `=` is an initializer's only where no `<` stands before it: after one it may be a type parameter's default, where a `<` opens a function type, and the lexer reads nothing exactly.
+ for (const text of ['<p>(a: A<B> = /x/)</p>', '<p>(a: A<B>= <b>c</b>)</p>', '<p>(cb: <U = /x/>() => U)</p>', '<p>(cb: <U = <b>c</b>>() => U)</p>']) assert.deepStrictEqual(opensTypeParameters(text, 0), GUESS, text);
+ // A division that a `{` may precede is a guess (a function body may hold a statement, where a `/` after a `)` begins a regex), but one that no `{` precedes is exact.
+ assert.deepStrictEqual(opensTypeParameters('<p>(a = () => b/c)</p>', 0), ELEMENT);
+ assert.deepStrictEqual(opensTypeParameters('<p>(a = () => { b/c })</p>', 0), GUESS);
+ // A regex that its line does not close is unterminated: no type has the text, and the list is the element's, whatever follows. (A `/` after the `)` on the same line closes it: `(a = /docs)</p>` is the regex
+ // `/docs)</`, and then no `)` follows.)
+ for (const text of ['<p>(a = /docs)\n</p>', '<p>(a = /docs)\r\n</p>', '<p>(a = /docs)\u2028</p>', '<p>(a = /x)\n more</p>', '<p>(see = /docs and more)\n</p>', '<p>(a = /[)\n</p>', '<p>(a = />)\n</p>', '<p>(a = /\\)\n</p>',
+ '<p>(a = /docs)']) assert.deepStrictEqual(opensTypeParameters(text, 0), ELEMENT, JSON.stringify(text));
+ for (const value of UNTERMINATED_DEFAULTS) {
+ for (const label of ['a = ', 'a: T = ', 'a, b = ']) {
+ assert.deepStrictEqual(opensTypeParameters(`<p>(${label}${value})</p>`, 0), ELEMENT, `${JSON.stringify(`${label}${value}`)} as the text of an element`);
+ assert.deepStrictEqual(opensTypeParameters(`<p>(${label}${value}) }`, 0), ELEMENT, `${JSON.stringify(`${label}${value}`)}: no type has the text either`);
+ }
+ }
+ // The `/` of the closing tag that follows closes no regex, so the list is not read on into the code after the element — where a `)` and a `;` or a `}` could end it for a signature.
+ for (const text of ['<p>(a = /docs)\n</p>;\nf(x);', '<p>(a = /docs)\n</p>;\ng(y) }', '{<p>(a = /docs)\n</p>}</p>;\nh(z);']) assert.deepStrictEqual(opensTypeParameters(text, text.indexOf('<p>')), ELEMENT, JSON.stringify(text));
+ assert.deepStrictEqual(opensTypeParameters(`<p>(a = /${'x'.repeat(2500)})</p>`, 0), GUESS, 'a regex that runs past the window is not told');
+ // An `=` and a closing tag, wherever the `=` stands: no expression and no type starts with `</`; and `</*` is a `<` and a comment, which starts what a `<` does.
+ for (const text of ['<p>(a = </x>)</p>', '<p>(a: A<B>=</x>)</p>', '<p>(cb: <U = </x>>() => U)</p>', '<p>(Tip: use <code>=</code>)</p>', '<p>(a =\n</x>)</p>']) assert.deepStrictEqual(opensTypeParameters(text, 0), ELEMENT, text);
+ for (const text of ['<p>(a = </* c */ T,>(x) => x)</p>', '<p>(a = </* c */ x>)</p>']) assert.deepStrictEqual(opensTypeParameters(text, 0), GUESS, text);
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.diagnostic('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to check the readings');
+ // TypeScript: the element parses, and the same text as a signature does not (a closing tag after it is no member); the type reading parses with a `}` where the closing tag was.
+ const declared = 'declare const a: any, b: any, c: any, x: any, y: any, of: any, yield: any, P: any, T: any, X: any;\n';
+ for (const defaults of Object.values(EXACT_DEFAULTS)) {
+ for (const value of defaults) {
+ for (const label of ['a = ', 'a: T = ', 'a, b = ']) {
+ assertTsParses(ts, `${declared}const e = <p>(${label}${value})</p>;`, `the element with ${JSON.stringify(`${label}${value}`)}`);
+ assert.ok(parseDiagnosticMessages(ts, `interface I { <p>(${label}${value})</p> }`).length > 0, `TypeScript rejects the signature with ${JSON.stringify(`${label}${value}`)} and a closing tag`);
+ assertTsParses(ts, `interface I { <p>(${label}${value}) }`, `the signature with ${JSON.stringify(`${label}${value}`)}`);
+ }
+ }
+ }
+ for (const text of ['<p>(a = /docs)\n</p>', '<p>(a = /x)\n more</p>', '<p>(see = /docs and more)\n</p>', '<p>(a = />)\n</p>']) assert.match(parseDiagnosticMessages(ts, `interface I { ${text.replace('</p>', '')} }`).join('\n'), /Unterminated regular expression literal/, text);
+});
+
+// ─── A `/` after a comment ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+//
+// A `/` after a name or a number divides in an expression, and a type has no division, so in no program that parses does a regex start after one (slashFollowsAnOperand). A comment is trivia to TypeScript, though: a block
+// comment ends in a `/`, which is no word, but a line comment ends in whatever its text does, and after it the last token is the one before the comment:
+// interface I { <T>(a = 1 + // x the last token is the `+`, so the `/` on the next line begins a regex
+// /[)]/); m: '</T>;navigateTo(…);//' } whose `)` is not the one that ends the list
+// A `/` read as a division there ended the parameter list at the `)` in the regex and read the string after it as code, where the token of the call is data. The pages below are TypeScript's: each parses with no diagnostic and holds the
+// text of a navigation call as data — in the string of a type, or in the regex itself — so its token is stray and nothing is rewritten, wherever the scan of a list (genericFunctionTypeFollows) or the reading of the text
+// of a signature (readChildren) meets the regex.
+const COMMENT_CALL = 'navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})';
+const COMMENT_PAGES = [
+ ['a call signature with a default whose regex follows a line comment, and a string that holds a closing tag and a call', `interface I { <T>(a = 1 + // x\n/[)]/); m: '</T>;${COMMENT_CALL};//' }`, 'generic'],
+ ['a matcher: a second default, a line comment that ends in a word, a `)` in the regex', `interface Matcher {\n <T>(value: T, pattern = /\\s/ || // fallback\n /\\)/): boolean;\n hint: '</T>; ${COMMENT_CALL} //';\n}\nexport default function Page() { return null; }\n`, 'generic'],
+ ['a function type in an annotation', `const f: <T>(a?: string, re = 1 && // p\n/[)]/) => T = g;\nconst s = '</T>;${COMMENT_CALL};//';\n`, 'generic'],
+ ["a regex that is the constraint of a function type in a parameter's type", `interface I { <T>(a: <U extends // c\n/x)/>(b: U) => U); m: '</T>;${COMMENT_CALL};//' }`, 'generic'],
+ ['a generic arrow after the end of type arguments and an initializer, with no space', `let v: Array<number>= <T extends X>(a = 1 + // c\n/[)]/) => '</T>;${COMMENT_CALL}//';\n`, 'operator'],
+ ['a call signature with no return type, and a later member whose default holds the closing tag and a call in a regex', `interface I { <T>(x); m(a = 1 + // c\n/[</T>;${COMMENT_CALL}//]/): void }`, 'generic'],
+ ['the same, after a comment that ends in a number, and a line separator', `interface I { <T>(x); m(a = x || // c1\u2028/[</T>;${COMMENT_CALL}//]/): void }`, 'generic'],
+ ['the same, after a comment that ends in a `$`, and a carriage return', `interface I { <T>(a = x ?? // c$\r/[)]/); m: '</T>;${COMMENT_CALL};//' }`, 'generic'],
+];
+test('a `/` after a line comment may begin a regex, as after a block comment: a token in the text of a call after one is data, and the page is refused', (t) => {
+ const ts = loadTypescriptOracle();
+ for (const [what, code, kind] of COMMENT_PAGES) {
+ const tokens = [...code.matchAll(/PAGEREF_detail/g)].map((match) => match.index);
+ assert.strictEqual((earliestAmbiguity(code) || [null, null])[1], kind, `${what}: the guess`);
+ // The build halts on every token, and nothing is rewritten: with no call of its own, and with a real one after the page, which the guess keeps from being trusted.
+ assert.deepStrictEqual(strayPageRefs(code).map((found) => found.start), tokens, `${what}: every token is stray`);
+ const resolved = resolvePageRefs(new Map([['x', { code }]]), new Map([['detail', 'gp-detail']]));
+ assert.strictEqual(resolved.deployment.get('x'), code, `${what}: nothing is rewritten`);
+ const after = `${code}${code.endsWith('\n') ? '' : '\n'}${COMMENT_CALL};\n`;
+ assert.deepStrictEqual(strayPageRefs(after).map((found) => found.start), [...after.matchAll(/PAGEREF_detail/g)].map((match) => match.index), `${what}: the real call after it is refused too`);
+ assert.strictEqual(resolvePageRefs(new Map([['x', { code: after }]]), new Map([['detail', 'gp-detail']])).deployment.get('x'), after, `${what}: and not rewritten`);
+ }
+ // The same text in a list of every kind: after a line comment of every kind a `/` may begin a regex, in the scan of a list and in the reading of the text after it — a block comment, which ends in a `/`, a line comment that
+ // ends in a name, a number, a `$`, a letter beyond ASCII, or in nothing, and a line break of every kind TypeScript has.
+ const GUESS = { generic: false, ambiguity: 'generic' };
+ const gaps = ['/* c */ ', ' /* c */ ', '// c\n', '// x1\n', '// $\n', '// 1\n', '// \u00e9\n', '//\n', '// c\r\n', '// c\r', '// c\u2028', '// c\u2029', '// c\n\n ', '/* c */ // c\n', '// c /* d\n', '// a/b\n'];
+ for (const gap of gaps) {
+ for (const value of [`1 + ${gap}/[)]/`, `x || ${gap}/\\)/`, `a ${gap}/ (c)`, `1 ${gap}/ 2`]) {
+ assert.deepStrictEqual(opensTypeParameters(`<p>(a = ${value})</p>`, 0), GUESS, `the scan of a list: ${JSON.stringify(value)}`);
+ assert.deepStrictEqual(opensTypeParameters(`<p>(a = ${value}) }`, 0), GUESS, `the scan of a list: ${JSON.stringify(`${value}) }`)}`);
+ }
+ // The text after a call signature with no return type is read to its closing tag, with the comments that it found itself: the token before them tells a regex from a division, as it does to a parser. After a name or a number
+ // the `/` divides, whatever the comment of any kind ends in, and holds nothing; after an operator, a keyword or a bracket a regex may begin, and hold the closing tag.
+ for (const word of ['a', '1', '$x']) assert.strictEqual(elementChildren(`<T>(x) ${word} ${gap}/b </T>`, 3, 'T').hideable, false, `the text of a signature, a division: ${JSON.stringify(`${word} ${gap}`)}`);
+ // ... and after a `)` or a `]`, which end a parenthesised expression, a call, an array and an index.
+ for (const operand of ['(a)', 'f(a, (b))', '[1]', 'a[0]', 'a[b[0]]']) assert.strictEqual(elementChildren(`<T>(x) ${operand} ${gap}/b </T>`, 3, 'T').hideable, false, `the text of a signature, a division after a bracket: ${JSON.stringify(`${operand} ${gap}`)}`);
+ for (const operator of ['+', '=', '||', '(', ',', '?', 'return', 'typeof', 'in', "'a'", '[', '&&', '!', '{ a }']) assert.strictEqual(elementChildren(`<T>(x) ${operator} ${gap}/b </T>`, 3, 'T').hideable, true, `the text of a signature, a regex: ${JSON.stringify(`${operator} ${gap}`)}`);
+ }
+ // Where no comment stands between them a `/` after a name or a number on a later line divides, and so does one after a name that stands on a line of its own after a comment, with any line break between them, or on the
+ // same line as a string that holds a `//` (a line comment ends at the line break): nothing is lost there.
+ const ELEMENT = { generic: false, ambiguity: null };
+ for (const text of ['<p>(a = b\n/c)</p>', '<p>(a = 1\r\n/ 2)</p>', '<p>(a = b // c\n d\n/c)</p>', '<p>(a = b + // c\nd\n/c)</p>', '<p>(a = b\n /c)</p>', '<p>(a = b\u2028/c)</p>', '<p>(a = b // c\r d\r/c)</p>', '<p>(a = b // c\u2028 d\u2029/c)</p>',
+ '<p>(a = b + // c\rd\r/c)</p>', '<p>(a = b + // c\u2028d\u2029/c)</p>', '<p>(a = "http://x" + y/c)</p>', '<p>(a = b/c\n/d)</p>']) assert.deepStrictEqual(opensTypeParameters(text, 0), ELEMENT, JSON.stringify(text));
+ assert.strictEqual(elementChildren('<T>(x) a\n /b </T>', 3, 'T').hideable, false);
+ for (const text of ['<T>(x) a // c\n b\n/c </T>', '<T>(x) a + // c\nb\n/c </T>', '<T>(x) a // c\r b\r/c </T>', '<T>(x) a // c\u2028 b\u2029/c </T>', '<T>(x) a/b\n/c </T>']) assert.strictEqual(elementChildren(text, 3, 'T').hideable, false, JSON.stringify(text));
+ // A `//` that is no comment — in a string, which a line may begin inside of — is not told from one: the `/` after the word that ends such a line is a guess too, which is the safe side.
+ assert.deepStrictEqual(opensTypeParameters('<p>(a = "http://x" + y\n/c)</p>', 0), GUESS);
+ // A line that begins before the window is not read, and the answer is the same.
+ assert.deepStrictEqual(opensTypeParameters(`const t = '${'x'.repeat(2100)}'; const e = <p>(a = b\n/c)</p>;`, `const t = '${'x'.repeat(2100)}'; const e = `.length), GUESS);
+ assert.deepStrictEqual(opensTypeParameters(`const t = '${'x'.repeat(1500)}'; const e = <p>(a = b\n/c)</p>;`, `const t = '${'x'.repeat(1500)}'; const e = `.length), ELEMENT);
+ if (!ts) return t.diagnostic('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to check the readings');
+ // The pages are TypeScript's, and the call in each is data: no call is read, though the page has the text of one.
+ const callsRead = (code) => {
+ let found = 0;
+ const visit = (node) => {
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'navigateTo') found += 1;
+ ts.forEachChild(node, visit);
+ };
+ visit(ts.createSourceFile('page.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX));
+ return found;
+ };
+ for (const [what, code] of COMMENT_PAGES) {
+ assertTsParses(ts, code, what);
+ assert.strictEqual(callsRead(code), 0, `${what}: TypeScript reads the text of the call as data`);
+ }
+ // The text where a regex is read after a comment is a regex to TypeScript, and where a division is, a division.
+ // A division after a name, on the next line or after a comment that stands behind an operator, is a division to TypeScript, in the text of an element and in the parameter list of a signature alike.
+ for (const list of ['a = b\n/c', 'a = b + // c\nd\n/c', 'a = b/c\n/d', 'a = "http://x" + y/c', 'a = b // c\n/ d']) {
+ assertTsParses(ts, `declare const a: any, b: any, c: any, d: any, y: any;\nconst e = <p>(${list})</p>;`, `the element with ${JSON.stringify(list)}`);
+ assertTsParses(ts, `interface I { <T>(${list}) }`, `the signature with ${JSON.stringify(list)}`);
+ }
+ for (const [value, kindOfSlash] of [['1 + // x\n/[)]/', 'RegularExpressionLiteral'], ['b // x\n/ 2', 'SlashToken'], ['1 // x\n/ 2', 'SlashToken']]) {
+ const source = ts.createSourceFile('page.tsx', `declare const b: any;\nconst o = { m(a = ${value}) {} };`, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ assert.deepStrictEqual(source.parseDiagnostics.map((d) => d.code), [], JSON.stringify(value));
+ let regexes = 0;
+ const visit = (node) => {
+ if (node.kind === ts.SyntaxKind.RegularExpressionLiteral) regexes += 1;
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ assert.strictEqual(regexes, kindOfSlash === 'RegularExpressionLiteral' ? 1 : 0, `TypeScript reads ${JSON.stringify(value)} with ${kindOfSlash === 'RegularExpressionLiteral' ? 'a regex' : 'a division'}`);
+ }
+});
+
// readChildren in closing mode, through elementChildren: the children of `<T>` read from its `>` to the closing tag of its own. `fails` is a text no element has, `closes` the closing tag found, `hidden` one that
// could be inside a string, a template, a comment or a regex that the text opens, and `unknown` a text this does not read.
test('elementChildren: the text of an element is read to its closing tag; a failure, a hidden closing tag and what is not read are told apart', (t) => {
@@ -3456,16 +3894,106 @@ test('elementChildren: the text of an element is read to its closing tag; a fail
['(x) `a </T>', 'hidden'], ['(x) `a ${b} </T>', 'hidden'], ['(x) `a\\` </T> b`</T>', 'hidden'], ["(x) 'a /* </T> */ b'</T>", 'hidden'], ['(x) // it\'s "a </T>', 'hidden'],
// A comment that no end is in sight for hides the closing tag even after a word, where a lone `/` would divide; so does a template with a `${` that is closed before it.
['(x) a // c </T>', 'hidden'], ['(x) a /* c </T>', 'hidden'], ['(x) 1 // c </T>', 'hidden'], ['(x) a /* c */ b </T>', 'closes'], ['(x) `a ${b} c` </T>', 'hidden'], ['(x) `a ${b} c` d </T>', 'hidden'],
+ // A `/` right after a comment is judged by the token before the comment, which is trivia to a type (slashFollowsAnOperand, with the comments that the text opened): after a word, a number, a `)` or a `]` it divides, whatever the
+ // comment ends in — a word, a number, a `$`, nothing, a line break of every kind — and after anything else a regex may begin. A block comment is one of those comments, and so is a run of them. Where the word stands on
+ // a line of its own, with no `//` before it, a line break between it and the `/` is nothing.
+ ['(x) a // c\n/b </T>', 'closes'], ['(x) 1 // c\n/b </T>', 'closes'], ['(x) a // c\r\n/b </T>', 'closes'], ['(x) a // c\u2028/b </T>', 'closes'], ['(x) a // $\n/b </T>', 'closes'], ['(x) a // c\n\n /b </T>', 'closes'],
+ ['(x) a /* c */ /b </T>', 'closes'], ['(x) a // c\n// d\n/b </T>', 'closes'], ['(x) a /* c */ // d\n/b </T>', 'closes'], ['(x) a // c\n/* d */\n/b </T>', 'closes'], ['(x) a /* c\n */ /b </T>', 'closes'],
+ ['(x) ( /* c */b // d\n/e </T>', 'closes'], ['(x) ( /* c */b /d </T>', 'closes'],
+ ['(x) 1 + // c\n/[</T>]/ </T>', 'hidden'], ['(x) 1 + /* c */ /[</T>]/ </T>', 'hidden'], ['(x) 1 + // c\n// d\n/[</T>]/ </T>', 'hidden'], ['(x) (a) // c\n/b </T>', 'closes'], ["(x) 'a' // c\n/b </T>", 'hidden'],
+ ['(x) [a] // c\n/b </T>', 'closes'], ['(x) f(a, (b)) /* c */ /b </T>', 'closes'], ['(x) a[0] // c\r\n/b </T>', 'closes'], ['(x) (a) // c\n// d\n/b </T>', 'closes'], ['(x) 1 + (a) // c\n/b </T>', 'closes'], ['(x) (a) + // c\n/[</T>]/ </T>', 'hidden'],
+ ['(x) return // c\n/b </T>', 'hidden'], ['(x) a // c\n b\n/c </T>', 'closes'], ['(x) a\n /b </T>', 'closes'], ['(x) a\r\n/b </T>', 'closes'], ['(x) a\u2028/b </T>', 'closes'],
+ // A comment that the text did not open is not told from a string's text: a `//` before the word on its line is a guess, and a word on a line of its own after a comment is a word.
+ ['(x) "http://x" y\n/b </T>', 'hidden'], ['(x) a // c\n b // d\n/e </T>', 'closes'], ['(x) a /* c */ b\n/d </T>', 'closes'],
// A `/` that no regex may start at, a comment or a template that is closed before the closing tag, and a line comment that ends before it, hide nothing: the closing tag is in code.
['(x) a/b</T>', 'closes'], ['(x) 1/2 </T>', 'closes'], ['(x) a / b </T>', 'closes'], ['(x) a\n/b </T>', 'closes'], ['(x) $/y </T>', 'closes'], ['(x) _/y </T>', 'closes'], ['(x) a//b\n</T>', 'closes'],
['(x) `t` </T>', 'closes'], ['(x) `a\\`b` </T>', 'closes'], ['(x) `a` `b` </T>', 'closes'], ['(x) /* c */ </T>', 'closes'], ['(x) /* a */ /* b */ </T>', 'closes'], ['(x) // c\n</T>', 'closes'], ['(x) // c\r\n</T>', 'closes'],
['(x) // c\u2028</T>', 'closes'], ["(x) /* ' */ </T> '", 'closes'], ['(x) // c\n// d\n</T>', 'closes'], ['(x) a/ /* c */ b </T>', 'closes'], ['(x) a/* c */b </T>', 'closes'],
- // A `/` after anything else may begin a regex, which a type holds in a default value or a computed name, and the closing tag may be in it: a `)`, an operator, a keyword, a bracket, a quote, a tag, a letter beyond ASCII.
+ // A `/` after anything else may begin a regex, which a type holds in a default value or a computed name, and the closing tag may be in it: an operator, a keyword, a quote, a tag, a letter beyond ASCII. After a `)` or a `]` it
+ // divides: no regex follows a parenthesised expression, a call, an index or an array, and no type has a `/` after a bracket.
// `implements` is one of the keywords: its heritage clause takes an expression, as `extends` does (`[class C implements /re/ {}]`); a word that only starts like it divides.
- ['(x) = /re/ </T>', 'hidden'], ['(x) (a) /b </T>', 'hidden'], ['(x) return/exchange </T>', 'hidden'], ['(x) [a] /b </T>', 'hidden'], ['(x) , /b </T>', 'hidden'], ['(x) é/y </T>', 'hidden'], ['(x)<b>y</b> /z </T>', 'hidden'],
- ['(x) typeof /b </T>', 'hidden'], ["(x) 'a' /b </T>", 'hidden'], ['(x) /* c */ /b </T>', 'hidden'], ['(x) /b </T>', 'hidden'], ['(x) {y} /b </T>', 'hidden'],
+ ['(x) = /re/ </T>', 'hidden'], ['(x) (a) /b </T>', 'closes'], ['(x) return/exchange </T>', 'hidden'], ['(x) [a] /b </T>', 'closes'], ['(x) , /b </T>', 'hidden'], ['(x) é/y </T>', 'hidden'], ['(x)<b>y</b> /z </T>', 'hidden'],
+ ["(x) 'a' /b </T>", 'hidden'], ['(x) typeof /b </T>', 'hidden'], ['(x) /* c */ /b </T>', 'closes'], ['(x) /b </T>', 'closes'], ['(x) {y} /b </T>', 'hidden'],
['(x) implements /b </T>', 'hidden'], ['(x) extends /b </T>', 'hidden'], ['(x) implementsX /b </T>', 'closes'],
["(x)<b>'y </b> z </T> w'</T>", 'hidden'], ["(x) 'a' 'b </T>\n", 'closes'],
+ // A nested tag is an element's, or something else to a type: the type arguments of a name (`Array<b>`), a comparison (`a<b>c`), the type parameters of a signature (`<b>(y): T`, `<U extends A>(y): T`). Where it is, the
+ // text after its `>` is code, which a string, a template or a comment holds the closing tags in, and the closing tag of the head may be inside one that the text of the nested element opened. A region that the text of a
+ // nested element opened and that is still open at its closing tag is read both ways, the closing tag of the head is hidden where either hides it, and two such regions are taken for hidden.
+ ["(x); m: Array<b> = '</b>' + '</T>'", 'hidden'], ["(x); <b>(y): '</b>'; q: '</T>'", 'hidden'], ["(x); <U extends A>(y): '</U>'; k: '</T>'", 'hidden'], ["(x); m: A<b>; n: '</b>' + '</T>'", 'hidden'], ["(x); m = a<b>c; n: '</b>' + '</T>'", 'hidden'],
+ ["(x); <const U extends A>(y): '</const>'; k: '</T>'", 'hidden'], ["(x); <in out U extends A>(y): '</in>'; k: '</T>'", 'hidden'], ["(x); <const U>(y): '</const>'; k: '</T>'", 'hidden'],
+ ["(x)<b>'y</b> + '</T>'", 'hidden'], ["(x)<>'y</> + '</T>'", 'hidden'], ['(x)<b>`y</b> `</T>', 'hidden'], ['(x)<b>x // y</b> +\n/[</T>]/', 'hidden'], ["(x) <b>x '</b> 'y</T>' ", 'hidden'], ["(x)<b>'y</b> <i>'z</i> w'</T>", 'hidden'],
+ ['(x)<b>see https://x.y</b></T>', 'hidden'], ['(x)<b>x // y</b> </T>', 'hidden'], ["(x)<U extends A>'y</U> + '</T>'", 'hidden'],
+ // One region that crosses the closing tags of several elements is one place, and a string that closes inside the next element, or that no quote closes on its line, holds nothing. Where the region goes on past the closing tag
+ // of the head (`'y</b></T>'`), the type holds the closing tag in it.
+ ["(x)<b>'y</b><i>z</i> w'</T>", 'closes'], ["(x)<b>'y</b> <i>z' </i> w'</T>", 'closes'], ["(x)<b>'y</b> '</T>", 'closes'], ["(x)<b>'y</b><b d=\"1\">z' </b> w'</T>", 'closes'], ["(x)<U extends A>y '</U> z'</T>", 'closes'],
+ ["(x)<b>'y</b></T>'", 'hidden'], ['(x)<b>`y</b></T>`', 'hidden'], ["(x); m: Array<b> = '</b></T>'", 'hidden'],
+ // A tag that no type has — an attribute with a value, an attribute that `extends` does not introduce, a dotted name with an attribute, a fragment — is an element to every reading, and its text is JSX text: a URL, an apostrophe, a back-tick or a
+ // comment opener in it opens nothing, and the elements in it are JSX too. What stands after its closing tag is code to the type that holds the element, and is read as such.
+ ['(x)<a href="x">see https://x.y</a>\n</T>', 'closes'], ['(x)<a href="x">it\'s https://x.y</a> and <b>that\'s</b></T>', 'closes'], ['(x)<a href="x">see https://x.y</a> <i>b</i> </T>', 'closes'], ['(x)<a href="x">`t</a> `u` </T>', 'closes'],
+ ['(x)<a href="x">/* c</a> </T>', 'closes'], ['(x)<a href="x">// c</a> </T>', 'closes'], ['(x), <>x // y</> </T>', 'closes'], ['(x)<b d>see https://x.y</b></T>', 'closes'], ['(x)<A.B x>see https://x.y</A.B></T>', 'closes'],
+ ['(x)<b d="1">x <i>y // z</i> w</b></T>', 'closes'], ['(x)<a href="x">https://x.y</a> <a href="z">https://z</a></T>', 'closes'], ['(x)<a href="x"><b>https://x.y</b></a></T>', 'closes'],
+ ['(x)<b d="1">x // y</b> +\n/[</T>]/', 'hidden'], ["(x)<b d=\"1\">'y</b> + '</T>'", 'hidden'], ['(x)<b d={1}>`y</b> `</T>', 'hidden'], ['(x)<b d="1">x <i>y // z</i> w</b> + // c\n/[</T>]/', 'hidden'],
+ ["(x)<a href=\"x\"><b>'x</b></a> + '</T>'", 'hidden'], ["(x)<b><a href=\"x\">'x</a></b> + '</T>'", 'hidden'],
+ // A region that a type's `<b>` text opens and that goes on past the closing tag of an element no type has is no reading: that closing tag is in code. The one that the element's own text opens ends at it. And a word that is
+ // given a value is no part of a constraint.
+ ['(x)<a href="x"><b>\'y</b></a></T> z\'', 'closes'], ['(x)<a href="x"><b>`y</b></a></T> z`', 'closes'], ['(x)<b><a href="x">\'y</a></b></T> z\'', 'closes'], ['(x)<U extends A="1" B>see https://x.y</U></T>', 'closes'],
+ // A dotted name is no type parameter's, with a constraint or none. A tag that stands inside what the text of the type opens — a string that holds `<i d="1">` and `</i>` — is no element's, and the text after it is no JSX text.
+ ['(x)<A.B extends X>see https://x.y</A.B></T>', 'closes'], ["(x)<b>'x <i d=\"1\">y' + '</i></b></T>'", 'hidden'], ["(x); m: Array<b> = 'x <i d=\"1\">y' + '</i></b></T>'", 'hidden'],
+ // Where the nested `<b>` is code, a tag that stands inside a string is text — a fragment, a tag with an attribute — and its closing tag in the next string closes nothing: the quote that ends a string is not the one that opens
+ // the next, as an element's tags would pair them. The element reading cuts the second string at the closing tag, and the quotes after it pair differently.
+ ["(x); m: Array<b> = '<>' + '</>' + '</b></T>'", 'hidden'], ["(x); m: A<b>; n: A = '</b> <b d> </b>' || '</T>'", 'hidden'], ['(x); m: Array<b> = `</b><a href="x">y</a>` || `</T>`', 'hidden'], ["(x)<b>'a <>b' + '</>' + '</b></T>'", 'hidden'],
+ ["(x); m: Array<b> = '<a href=\"x\">' + '</a>' + '</b></T>'", 'hidden'], ["(x)<b>'a <i d=\"1\">b' + 'c</i> d' </b></T>", 'closes'], ["(x); m: A<b>; n: A = 'x <>' + '</></b>' ?? '</T>'", 'hidden'],
+ ['(x); m(a?: string, b = <i>"q"`a/b\'<i>\'*/y z</i> + <i>`t`/**/</i>\n\n`</i>` || `</T>`): void', 'hidden'],
+ // One region that crosses the closing tags of the elements around the one that opened it is one place (crossedFrom): the closing tags are in a string, and the head's is not.
+ ["(x)<i><b>'y</b></i> w'</T>", 'closes'], ["(x)<i><b>'y</b> z</i> w'</T>", 'closes'],
+ // Two regions that end at one place are two places, told by where they start: two comments on one line, each opened in an element of its own, are two crossings, and the head's closing tag is for the type to place.
+ ["(x); m(a = <b>//</b> - <i>//</i> ?? `\n</T>`)", 'hidden'], ["(x); m(a = <b>x // y</b> + <i>u // v</i> + `\n</T>`)", 'hidden'], ['(x); [<b>x // y</b> + <i>u // v</i> +\n/[</T>]/]: string', 'hidden'],
+ ['(x); m(a = <b>//</b> - <i>//</i> ?? 1 +\n/[</T>]/): void', 'hidden'], ['(x); m(a = <b>/* x</b> + <i>/* y</i> + `\n</T>`)', 'hidden'],
+ // A string, a template or a comment that the text opens where no element of the type's reading is open holds its tags as text, so the closing tag of the next one cuts nothing short, and what stands after it is code.
+ ["(x); m: A = '<b>' + `x</b>` </T>", 'closes'], ['(x); m: A = `<b>` + `x</b>` </T>', 'closes'], ["(x); m: A = '<b>' + /* x</b> */ 1 </T>", 'closes'],
+ // A tag with a word of TypeScript in it that no attribute gives a value — a modifier, an operator, a type's keyword: `<public U>(y): T`, `<in out U>`, `a <b in c> d`, `Array<keyof X>` — may be the type parameters of a signature, a
+ // comparison or the type arguments of a name, which a tag with no such word cannot be, and what follows its `>` is code: a string there holds the closing tag. (`extends` is the one word that a constraint has.)
+ ["(x); <public U>(y): '</public>'; q: '</T>'", 'hidden'], ["(x); <private U>(y): '</private>'; q: '</T>'", 'hidden'], ["(x); <readonly U>(y): '</readonly>'; q: '</T>'", 'hidden'], ["(x); m<static U>(y): '</static>'; q: '</T>'", 'hidden'],
+ ["(x); new <abstract U>(y): '</abstract>'; q: '</T>'", 'hidden'], ["(x); m(p = x <a in b> '</a>' + '</T>')", 'hidden'], ["(x); m(p = x <a instanceof B> '</a>' + '</T>')", 'hidden'], ["(x); m(p = x <A.B as T> '</A.B>' + '</T>')", 'hidden'],
+ ["(x); m(p = x <new b> '</new>' + '</T>')", 'hidden'], ["(x); m(p = x <typeof U> '</typeof>' + '</T>')", 'hidden'], ["(x); m(p = x <void a> '</void>' + '</T>')", 'hidden'], ["(x); m(p = x <delete x> '</delete>' + '</T>')", 'hidden'],
+ ["(x); m(p = x <await a> '</await>' + '</T>')", 'hidden'], ["(x); m(p = x <a satisfies B> '</a>' + '</T>')", 'hidden'], ["(x); m: Array<keyof X> = '</keyof>' + '</T>'", 'hidden'], ["(x); m: Array<readonly X> = '</readonly>' + '</T>'", 'hidden'],
+ ["(x); m: Array<unique symbol> = '</unique>' + '</T>'", 'hidden'], ["(x); m: Array<infer U extends A> = '</infer>' + '</T>'", 'hidden'], ["(x); m: x <asserts readonly> '</asserts>' + '</T>'", 'hidden'],
+ // A word that has a value is an attribute's, and so is a word in the name of an attribute that a dash or a dot joins to a word that is none (`data-in`): the elements read for JSX text, as a tag with an attribute is.
+ ['(x)<button type="button">https://x.y</button></T>', 'closes'], ['(x)<label for="x">it\'s https://x.y</label></T>', 'closes'], ['(x)<Link as="span" href="/x">`t</Link> `u` </T>', 'closes'], ['(x)<a href="x" default="y">see https://x.y</a></T>', 'closes'],
+ ['(x)<button type={kind}>https://x.y</button></T>', 'closes'], ['(x)<a data-in="1">see https://x.y</a></T>', 'closes'], ['(x)<input readonly>see https://x.y</input></T>', 'hidden'], ['(x)<a data-in>see https://x.y</a></T>', 'hidden'],
+ // The words of a tag are split at the dots and the dashes that join them (hasKeywordPart), so a keyword in a dotted name leaves the tag possible code. No type reads `<A.in x>`: the reading is the conservative one, and the row holds it.
+ ['(x)<A.in x>see https://x.y</A.in></T>', 'hidden'],
+ // A line break ends a member of a type (canParseSemicolon, parseTypeMemberSemicolon), so a tag with a line break between a word and its `=` is the members of a type — an initializer that ends at the break, then a member named by the
+ // word, whose own `=` takes an initializer — and no list of attributes: the text after its `>` is code, and a string there holds the closing tag. Any line break stands for it (LF, CR, CRLF), whether the value is a string or a
+ // container, and wherever a type reads a comparison (an initializer, a default value, a computed name). A `get` or a `set` that has a value after a line break is a member as well (isTypeMemberStart takes either for the start of a
+ // member before it looks at what follows). A `=` on the line of its word is no member (TS1131) — so a tag of attributes, each on a line of its own, is an element's, as prettier writes one — and a line break after the `=` is none either.
+ ["(x); m: A = x <a\nhref\n=\"/x\"> '</a>' + '</T>'", 'hidden'], ["(x); m: A = x <a\r\nhref\r\n=\"/x\"> '</a>' + '</T>'", 'hidden'], ["(x); m: A = x <a\rhref\r=\"/x\"> '</a>' + '</T>'", 'hidden'], ["(x); m: A = x <a href\n=\"/x\"> '</a>' + '</T>'", 'hidden'],
+ ["(x); m: A = x <a\nhref\n='/x'> '</a>' + '</T>'", 'hidden'], ["(x); m: A = x <a\nhref\n={y}> '</a>' + '</T>'", 'hidden'], ["(x); m: A = x <a\nhref\n=\"/x\"\n> '</a>' + '</T>'", 'hidden'], ["(x); m: A = x <a\n href\n =\"/x\"\n> '</a>' + '</T>'", 'hidden'],
+ ["(x); m: A = x <a\nb\nc\n=\"/x\"> '</a>' + '</T>'", 'hidden'], ["(x); m: A = x <a\nb\n=\"1\"\nc\n=\"/x\"> '</a>' + '</T>'", 'hidden'], ["(x); m: A = x <A.B\nc\n=\"/x\"> '</A.B>' + '</T>'", 'hidden'],
+ ["(x); m(p = x <a\nhref\n=\"/x\"> '</a>' + '</T>'): void", 'hidden'], ["(x); [x <a\nhref\n=\"/x\"> '</a>' + '</T>']: string", 'hidden'], ["(x); m? = f() <a\nhref\n=\"/x\"> '</a>' + '</T>'", 'hidden'], ["(x); m: A = 1 <a\nhref\n=\"/x\"> '</a>' + '</T>'", 'hidden'],
+ ["(x); m: A = x <a\nget=\"/x\"> '</a>' + '</T>'", 'hidden'], ["(x); m: A = x <a\nset=\"/x\"> '</a>' + '</T>'", 'hidden'], ["(x); m: A = x <a\r\nget='/x'> '</a>' + '</T>'", 'hidden'], ["(x); m: A = x <a\nhref=\"/y\"\nget=\"/x\"> '</a>' + '</T>'", 'hidden'],
+ ['(x)<a\nhref\n="x">see https://x.y</a></T>', 'hidden'], ['(x)<a\nget="x">see https://x.y</a></T>', 'hidden'],
+ ["(x); m: A = x <a get=\"/x\"> '</a>' + '</T>'", 'closes'], ["(x); m: A = x <a\nhref=\"/x\"> '</a>' + '</T>'", 'closes'], ["(x); m: A = x <a\n href=\"/x\"\n target=\"_blank\"\n> '</a>' + '</T>'", 'closes'],
+ ["(x); m: A = x <a\nin-x=\"v\"> '</a>' + '</T>'", 'closes'], ["(x); m: A = x <a\ndata-get=\"v\"> '</a>' + '</T>'", 'closes'], ["(x); m: A = x <a\ngetx=\"v\"> '</a>' + '</T>'", 'closes'],
+ ['(x)<a\n href="x"\n target="_blank"\n>see https://x.y</a></T>', 'closes'], ['(x)<a href="x"\n>see https://x.y</a></T>', 'closes'], ['(x)<a get="x">see https://x.y</a></T>', 'closes'],
+ // U+2028 and U+2029, U+0085 and U+00A0 are no white space of a tag to this reading: a tag that holds one is not read, and the page is refused after a guess.
+ ["(x); m: A = x <a\u2028href\u2028=\"/x\"> '</a>' + '</T>'", 'unknown'], ["(x); m: A = x <a\u0085href\u0085=\"/x\"> '</a>' + '</T>'", 'unknown'], ["(x); m: A = x <a\u00a0href=\"/x\"> '</a>' + '</T>'", 'unknown'],
+ // A fragment is no element to a type where a name, a bracket, a quote or a back-tick stands before it, or a `(` or a back-tick after it: the empty type parameters of a signature (`<>(y): T`, `m<>(y): T`), the empty type
+ // arguments of a name, a call or an expression (`A<>`, `f<>(1)`, `f(x)<>`, `a[0]<>`, `a!<>`, `'s'<>`, `{}<>`), and a tagged template (`x <>\`t\``) are code, and a string after them holds the closing tag. After a `,`, a `;`, an operator or
+ // nothing it is a fragment, for certain, and its text is JSX text — unless a line break stands before it that a line comment may end (below).
+ ["(x); <>(y): '</>'; q: '</T>'", 'hidden'], ["(x); m<>(y): '</>'; q: '</T>'", 'hidden'], ["(x); new <>(y): '</>'; q: '</T>'", 'hidden'], ["(x); m: A<> = '</>' + '</T>'", 'hidden'], ["(x); m(p = f<>(1) + '</>' + '</T>')", 'hidden'],
+ ["(x); m(p = f(x)<> || '</>' + '</T>')", 'hidden'], ["(x); m(p = a[0]<> || '</>' + '</T>')", 'hidden'], ["(x); m(p = a!<> || '</>' + '</T>')", 'hidden'], ["(x); m(p = 's'<> || '</>' + '</T>')", 'hidden'], ["(x); m(p = {}<> || '</>' + '</T>')", 'hidden'],
+ ["(x); m(p = x <>`t` + '</>' + '</T>')", 'hidden'], ['(x)<>x // y</> </T>', 'hidden'], ['(x); <>x // y</> </T>', 'closes'], ['(x), <>x // y</> </T>', 'closes'], ["(x); 'x//y', <>// y</> </T>", 'closes'],
+ // The character before the fragment is the last one of a line comment, whatever it is, where a line break stands between them: `f // note:` and a line break, then `<> || …` is the instantiation expression `f<> || …`, which
+ // opens no element, and a string after it holds the closing tag. A comment ends in any character; a number ends in a `.` (`1.<>`), and a name may end in a character beyond ASCII. After a line break that no line comment can end — no
+ // `//` stands before the character on its line — the character is read as written: an operator there leaves a fragment, whose text is JSX text (the `//` in it opens nothing).
+ ["(x); m(p = f // note:\n<> || '</>' + '</T>')", 'hidden'], ["(x); m(p = f // note.\n<> || '</>' + '</T>')", 'hidden'], ["(x); m(p = f // note,\n<> || '</>' + '</T>')", 'hidden'], ["(x); m(p = f // note -\n<> || '</>' + '</T>')", 'hidden'],
+ ["(x); m(p = f // note =\n<> || '</>' + '</T>')", 'hidden'], ["(x); m(p = f // note (\n<> || '</>' + '</T>')", 'hidden'], ["(x); m(p = f // note:\r<> || '</>' + '</T>')", 'hidden'], ["(x); m(p = f // note:\u2028<> || '</>' + '</T>')", 'hidden'],
+ ["(x); m(p = f // note:\u2029<> || '</>' + '</T>')", 'hidden'], ["(x); m(p = f // note:\n\n <> || '</>' + '</T>')", 'hidden'], ["(x); m(p = f(x) // e.g.\n<> || '</>' + '</T>')", 'hidden'], ["(x); m: A = f // note:\n<> || '</>' + '</T>'", 'hidden'],
+ ["(x); [f // note:\n<> || '</>' + '</T>']: string", 'hidden'], ["(x); m(p = 1 + // note:\n<>x // y</>)</T>", 'hidden'], ["(x); m(p = 1 + // c\n// d:\n<>x // y</>)</T>", 'hidden'], ["(x); m(p = 1.<> || '</>' + '</T>')", 'hidden'],
+ ["(x); m(p = \u00e9<> || '</>' + '</T>')", 'hidden'], ["(x); m(p = f\u00e9<> + '</>' + '</T>')", 'hidden'], ["(x); m(p = f /* c */ <> || '</>' + '</T>')", 'hidden'], ["(x); m(p = f\n<> || '</>' + '</T>')", 'hidden'],
+ ["(x); m(p = 1 +\n<>x // y</>)</T>", 'closes'], ["(x); m(p = a ||\n <>x // y</> || b)</T>", 'closes'], ["(x); m(p = f(\n<>x // y</>))</T>", 'closes'], ["(x); m(p = 1 +\r\n<>x // y</>)</T>", 'closes'],
+ ["(x); m(p = 1 +\u2028<>x // y</>)</T>", 'closes'], ["(x); m(p = 1 +\u0085<>x // y</>)</T>", 'closes'], ["(x); m(p = 1 + // note\n<>x // y</>)</T>", 'hidden'],
// `</` and a comment is a `<` and a comment to a type, the type parameters of the next signature, and TS1003 to an element; with white space between, it is a closing tag to both.
['(x)</* c */T>', 'fails'], ['(x)\n</* c */T>', 'fails'], ['(x)</ /* c */ T>', 'closes'], ['(x)</ T>', 'closes'], ['(x)<b></ /* c */ b></T>', 'closes'], ['(x)<b></* c */b></T>', 'fails'],
// Strings: one that ends right where the closing tag starts holds nothing of it; a quote inside a string is not the start of another; a quote right after a word that is no keyword is an apostrophe or an
@@ -3511,6 +4039,61 @@ test('elementChildren: the text of an element is read to its closing tag; a fail
}
});
+// A nested tag and a fragment that a type reads as code — through line breaks and comments of every kind between the tokens that tell it — leave the closing tag of the head hidden, whatever the text after them holds: a line break ends a
+// member of a type, so `href` and a line break, then `="/x"`, is a member with an initializer; and a line comment may end in any character, so the character before a fragment on the next line says nothing of the operand before the comment.
+// TypeScript says which texts a type reads: for each text in the places where a comparison or an empty list of type arguments stands, a page that parses has the `<` read as code (the closing tags in it are in strings), and the reading
+// must not say that nothing could hide the head's closing tag ('closes'). The tags that no type has — attributes each with its `=` on its own line, as prettier writes them — are read as the element they are.
+test('TypeScript: a tag or a fragment that a type reads through line breaks and comments leaves the closing tag hidden; the attributes of an element, each on a line of its own, do not', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const kindOf = (text) => {
+ const read = elementChildren(`<T>(x)${text}`, 3, 'T');
+ return read === null ? 'unknown' : read.fails !== undefined ? 'fails' : read.hideable ? 'hidden' : 'closes';
+ };
+ const typeReads = (text) => firstDiagnostic(ts, `interface I {\n <T>(x)${text}\n}\n`) === Infinity;
+ const lineBreaks = ['\n', '\r', '\r\n', '\u2028', '\u2029'];
+ // The tags: a line break between a word and its `=`, before a valued `get` or `set`, after a value, in a dotted name, around several words; and the tags whose `=` is on the line of its word.
+ const tags = [];
+ for (const b of lineBreaks) {
+ tags.push(`<a${b}href${b}="/x">`, `<a href${b}="/x">`, `<a${b}href${b}={y}>`, `<a${b}b${b}c${b}="/x">`, `<a${b}b${b}="1"${b}c${b}="/x">`, `<A.B${b}c${b}="/x">`, `<a${b}get="/x">`, `<a${b}set='/x'>`, `<a${b}href="/y"${b}get="/x">`,
+ `<a${b}href${b}="/x"${b}>`, `<a${b}href="/x"${b}target="_blank"${b}>`, `<a href=${b}"/x">`, `<a${b}href=${b}"/x">`, `<a${b}data-get="v">`, `<a${b}getx="v">`, `<a${b}in-x="v">`);
+ }
+ const places = [(tag) => `; m: A = x ${tag} '</a>' + '</T>'`, (tag) => `; m(p = x ${tag} '</a>' + '</T>'): void`, (tag) => `; [x ${tag} '</a>' + '</T>']: string`, (tag) => `; m? = f() ${tag} '</a>' + '</T>'`];
+ let types = 0;
+ for (const tag of tags) {
+ for (const place of places) {
+ const text = place(tag);
+ if (typeReads(text)) {
+ types += 1;
+ assert.notStrictEqual(kindOf(text), 'closes', `a type reads ${JSON.stringify(text)}`);
+ }
+ }
+ }
+ assert.ok(types >= 40, `only ${types} of the tags were read by a type`);
+ // The tags that no type reads, and that no word of TypeScript is in: an element's attributes, whatever line each stands on.
+ for (const b of ['\n', '\r', '\r\n']) {
+ for (const tag of [`<a${b}href="/x"${b}target="_blank"${b}>`, `<a${b}href="/x">`, `<a href="/x"${b}>`, `<a${b}data-get="v">`, `<a${b}getx="v">`, `<a${b}in-x="v">`, `<a${b}b="1"${b}c="/x">`]) {
+ for (const place of places) assert.ok(!typeReads(place(tag)) && kindOf(place(tag)) === 'closes', `an element's attributes: ${JSON.stringify(place(tag))}`);
+ }
+ }
+ // A fragment after an operand, where a line comment of any ending, a line terminator or nothing stands between: where the text parses, the `<>` is an empty list of type arguments and the closing tag may be in the string after it.
+ const printable = [];
+ for (let c = 33; c < 127; c += 1) printable.push(String.fromCharCode(c));
+ const separators = ['', ' ', ...lineBreaks, ' /* c */ ', ' /*\n*/ ', ...printable.map((c) => ` // note${c}\n`), ...lineBreaks.slice(1).flatMap((b) => [' // note:', ' // note.', ' // note x'].map((note) => `${note}${b}`))];
+ let lists = 0;
+ for (const operand of ['f', 'f(x)', 'a[0]', "'s'", '1', '1.', 'x!', 'this', '\u00e9', 'null', '{}']) {
+ for (const separator of separators) {
+ for (const after of [" || '</>' + '</T>'", ", '</>' + '</T>'"]) {
+ const text = `; m(p = ${operand}${separator}<>${after})`;
+ if (!typeReads(text)) continue;
+ lists += 1;
+ assert.notStrictEqual(kindOf(text), 'closes', `a type reads ${JSON.stringify(text)}`);
+ }
+ }
+ }
+ assert.ok(lists >= 600, `only ${lists} of the fragments were read by a type`);
+});
+
// A string in a container is skipped exactly where there is a closing tag to find (containerEndWithStrings), and still stops the container reading where there is an arrow (elementFailsAt): the
// verdicts of the arrow reading are the fuzz's, and none of them changes. The braces that a container holds are counted there too, outside the strings, so an object or a block in one is skipped whole.
test('a container that holds a string or braces is skipped, exactly, when the text is read to its closing tag, and is not read when it is read to an arrow', () => {
@@ -4164,8 +4747,8 @@ test('the closer of a cast is read for certain: a "/" after it divides and a "<"
// ─── The text of an element that starts with a parenthesis: the type that could be read from the same text ────────────────────────────────────────────────
//
-// The text up to the closing tag is scanned as the type would scan it, as code, and what could hide the closing tag is a string, a template or a comment that is open at it, or a regex that may start (slashFollowsAnOperand). Before
-// the first of those, the text must be what a type could hold for its members — a name, a `,` or a `;`, a name and then its own type — or no type holds the closing tag in anything (typeMembersFail).
+// The text up to the closing tag is scanned as the type would scan it, as code, and what could hide the closing tag is a string, a template or a comment that is open at it, or a regex that may start (slashFollowsAnOperand). Up to
+// each of those, the text must be what a type could hold for its members — a name, a `,` or a `;`, a name and then its own type — or no type holds the closing tag in anything (typeMembersFail).
test('typeMembersFail: text that no type can hold as its members leaves no type for a closing tag to be hidden in', () => {
const closes = (text, typeFrom) => {
const read = elementChildren(`<T>${text}`, 3, 'T', null, typeFrom);
@@ -4179,11 +4762,12 @@ test('typeMembersFail: text that no type can hold as its members leaves no type
['(x), a, b c /* </T> */ d</T>', 'closes'], ['(x);\n see https://x.y more\n </T>', 'closes'], ['(x), a_1 $b // c </T>', 'closes'],
// A template or a regex where a member would begin, after a separator or on the next line: no member starts with one (TS1131). After a colon a template is a type, and stays possible.
['(x); `a ${b} </T>', 'closes'], ['(x), `a </T> b`', 'closes'], ['(x)\n `a ${b} </T>', 'closes'], ['(x);\n /re </T>', 'closes'], ['(x), /a </T> b/', 'closes'], ['(x); m: `a ${b} </T>', 'hidden'],
- // A name alone, a modifier, a name on the next line, a colon, a bracket, a character beyond ASCII or anything that is no plain prose leaves both programs possible: a comment, a template or a string that is open at the closing tag hides it.
- ['(x), a // c </T>', 'hidden'], ['(x), a\n b // c </T>', 'hidden'], ['(x), readonly b // c </T>', 'hidden'], ['(x), get b // c </T>', 'hidden'], ['(x), new b // c </T>', 'hidden'], ['(x), public b // c </T>', 'hidden'],
- ['(x), declare b // c </T>', 'hidden'], ['(x), a: b // c </T>', 'hidden'], ['(x), a? b // c </T>', 'hidden'], ['(x), [a] b // c </T>', 'hidden'], ['(x), é b // c </T>', 'hidden'], ['(x), a.b c // c </T>', 'hidden'],
- ["(x), it's // c </T>", 'hidden'], ['(x); // c </T>', 'hidden'], ['(x);\n /* c </T>', 'hidden'], ["(x); 'a </T> b'", 'hidden'], ['(x), = /re/ </T>', 'hidden'], ['(x), a, // c </T>', 'hidden'],
- ['(x), a\n see https://x.y </T>', 'closes'], ['(x),\n a\n b\n // c </T>', 'hidden'], ['(x), 1\n 2 // c </T>', 'hidden'],
+ // A name alone, a modifier, a name on the next line, a colon and a type, or a computed name leaves both programs possible: a comment, a template or a string that is open at the closing tag hides it. A keyword that is
+ // no modifier is a name, and a modifier is one before a `:` too. A bracket after a name, and a `=` where a member would begin, are no member (TS1005, TS1131).
+ ['(x), a // c </T>', 'hidden'], ['(x), a\n b // c </T>', 'hidden'], ['(x), readonly b // c </T>', 'hidden'], ['(x), get b // c </T>', 'hidden'], ['(x), public b // c </T>', 'hidden'],
+ ['(x), declare b // c </T>', 'hidden'], ['(x), a: b // c </T>', 'hidden'], ['(x), [a] b // c </T>', 'closes'], ['(x), é // c </T>', 'hidden'], ['(x); // c </T>', 'hidden'], ['(x);\n /* c </T>', 'hidden'],
+ ["(x); 'a </T> b'", 'hidden'], ['(x), = /re/ </T>', 'closes'], ['(x), a, // c </T>', 'hidden'], ['(x), a? // c </T>', 'hidden'], ['(x), default: // c </T>', 'hidden'], ['(x), type: a // c </T>', 'hidden'],
+ ['(x), a\n see https://x.y </T>', 'closes'], ['(x),\n a\n b\n // c </T>', 'hidden'], ['(x), 1\n 2 // c </T>', 'hidden'], ['(x), new b // c </T>', 'closes'], ['(x), type b // c </T>', 'closes'],
];
for (const [text, expected] of rows) assert.strictEqual(closes(text, 6), expected, JSON.stringify(text));
// Without the position of the type's members there is no type to ask about: the same texts are guesses wherever something could hide the closing tag.
@@ -4198,6 +4782,277 @@ test('typeMembersFail: text that no type can hold as its members leaves no type
assert.strictEqual(closes('(x /* </T> */) a b</T>', 6), 'hidden');
});
+// The claims of the reader of the prose that follows a call signature's `)` (typeMembersFail): for each text after the `)` of `<T>(x)`, and each thing that could hide the closing tag after it — a comment, a regex, a template, a
+// string — the reader says that the closing tag is, or may be, hidden (no claim), or that nothing can hide it: no type has the text for its members up to the probe, which is the claim. TypeScript supports the claim when its
+// parser's first diagnostic for `interface I { <T>(x)TEXT PROBE }` is at or before the closing tag in the probe. A text that ends in a comment, a string or a template that nothing closes is not asked: its diagnostic is at the
+// end of its own literal, which is where the probe's text is.
+const PROSE_HEAD = 'interface I {\n <T>(x)';
+const PROSE_PROBES = ['// c </T>', '/b </T> /', '`b </T>', "'b </T> c'", '"b </T> c"'];
+function firstDiagnostic(ts, code) {
+ try {
+ const diagnostics = ts.createSourceFile('snippet.tsx', code, ts.ScriptTarget.Latest, false, ts.ScriptKind.TSX).parseDiagnostics;
+ return diagnostics.length === 0 ? Infinity : Math.min(...diagnostics.map((d) => d.start));
+ } catch {
+ return -1;
+ }
+}
+function deadClaims(ts, texts) {
+ const stats = { texts: 0, claims: 0, unterminated: 0 };
+ const unsound = [];
+ const seen = new Set();
+ const endsUnterminated = (code) => {
+ const scanner = ts.createScanner(ts.ScriptTarget.Latest, false, ts.LanguageVariant.JSX, code);
+ for (let token = scanner.scan(); token !== ts.SyntaxKind.EndOfFileToken; token = scanner.scan()) if (scanner.isUnterminated()) return true;
+ return false;
+ };
+ for (const text of texts) {
+ if (seen.has(text)) continue;
+ seen.add(text);
+ // A text that opens a comment and does not close it, or that closes one that its first character opened, is not the text this asks about.
+ if (/\/\/[^\n]*$/.test(text) || /\/\*(?:(?!\*\/)[^])*$/.test(text) || /[/*]$/.test(text)) continue;
+ if (endsUnterminated(`${PROSE_HEAD}${text}`)) {
+ stats.unterminated += 1;
+ continue;
+ }
+ stats.texts += 1;
+ for (const probe of PROSE_PROBES) {
+ const read = elementChildren(`<T>(x)${text}${probe}`, 3, 'T', null, 6);
+ if (read === null || read.fails !== undefined || read.hideable) continue;
+ stats.claims += 1;
+ const code = `${PROSE_HEAD}${text}${probe}\n}\n`;
+ // At the `<` of the closing tag at the latest: after a name a `/` divides, so the closing tag is code, and `</` is one token to TypeScript's scanner in TSX that nothing in a type or an expression after an operand can have.
+ // Any diagnostic before it, or at it, means that the probe hides nothing.
+ if (firstDiagnostic(ts, code) > PROSE_HEAD.length + text.length + probe.indexOf('</T>')) unsound.push(JSON.stringify(code));
+ }
+ }
+ return { stats, unsound };
+}
+
+// The prose after a call signature's `)` is read as the members of a type, through the comments in it and across line breaks, from where the last question left off, up to the first thing that no type has (typeMembersFail).
+// Each row is the text after `(x)`, ending in what could hide the closing tag — a comment that holds it (`// c </T>`), a regex, a template, a string — and says whether it could be hidden there ('hidden') or not ('closes'):
+// the claims are TypeScript's, which the sweep in the test after this one asks for every one of, and the table of keywords is TypeScript's own (isModifierKind).
+test('typeMembersFail: prose is read as the members of a type through comments and line breaks, up to the first thing that no type has', (t) => {
+ const closes = (text) => {
+ const read = elementChildren(`<T>(x)${text}`, 3, 'T', null, 6);
+ return read === null ? 'unknown' : read.fails !== undefined ? 'fails' : read.hideable ? 'hidden' : 'closes';
+ };
+ const rows = [
+ // A name and a colon, then a type that a later line may give: a comment is trivia, and a type may begin on the next line. A `/` where the type must be is TS1110.
+ [';\n https: // c </T>', 'hidden'], [';\n https://x.y\n /b </T>', 'closes'], [',\n https://x.y\n /b </T>', 'closes'], ['\n https://x.y\n /b </T>', 'closes'], ['; https://x.y\n/b </T>', 'closes'],
+ [';\n Docs: https://x.y\n /b </T>', 'closes'], [';\n Docs: https://x.y </T>', 'closes'], [';\n a: // c\n /b </T>', 'closes'], [';\n a:\n /b </T>', 'closes'], [';\n a: // c\n b // d </T>', 'hidden'],
+ [';\n a: // c\n b\n /d </T>', 'closes'], [';\n a: b: c // d </T>', 'closes'], [';\n a:: b // c </T>', 'closes'], [';\n a: b\n c // d </T>', 'hidden'], [';\n a: b\n | c // d </T>', 'hidden'],
+ // A name and a note: the line break after a name ends its member, and a `/` on the next line is where a member begins (TS1131).
+ [';\n b // c\n /d </T>', 'closes'], [';\n b /* c */ // d\n /e </T>', 'closes'], [';\n b // c\n // d\n /e </T>', 'closes'], [';\n b /* c\n */ /d </T>', 'closes'], [';\n b\n // c </T>', 'hidden'],
+ // Comments of every kind are trivia, and a line break in a block comment is a line break.
+ [' /* c */ ; a /* d */ b // e </T>', 'closes'], [';\n a /* c\n */ b // d </T>', 'hidden'], [';\n a /* c */ b // d </T>', 'closes'], [';\n a: /* c\n */ b // d </T>', 'hidden'], [';\n a // c\n : b // d </T>', 'hidden'],
+ // A line break does not end a member before a `:` or an operator that goes on a type: `m` and a line break, then `: T`; `m: A` and a line break, then `| B`. A line break before `extends` ends the type (no conditional
+ // type goes on over one), so `extends` is the name of the next member. Where a `:` begins the next line the type must follow, and a `/` there is TS1110; after a type a `:` is TS1005, and `&` and `|` that begin a line
+ // go on a type but not on a name.
+ [';\n m\n : T // c </T>', 'hidden'], [';\n m\n : /b </T>', 'closes'], [';\n m: A\n | B // c </T>', 'hidden'], [';\n m: A\n & B // c </T>', 'hidden'], [';\n m: A\n extends B ? C : D // c </T>', 'closes'], [';\n m: A\n .B // c </T>', 'hidden'],
+ [';\n m: A\n : B // c </T>', 'closes'], [';\n m: A\n || B // c </T>', 'closes'], [';\n m: A\n ? B // c </T>', 'closes'], [';\n m\n & B // c </T>', 'closes'], [';\n m\n | B // c </T>', 'closes'], [';\n m(y)\n & B // c </T>', 'closes'],
+ [';\n (y)\n &"x" // c\n /b </T>', 'closes'], [";\n 'm'\n || // c\n /b </T>", 'closes'], [';\n m\n !\n /b </T>', 'closes'], [';\n m\n @ // c </T>', 'closes'], [';\n m\n ? : T // c </T>', 'hidden'], [';\n a:\n || // c </T>', 'closes'],
+ [';\n a: | B // c </T>', 'hidden'], [';\n in @ // c </T>', 'closes'], [';\n readonly . // c </T>', 'closes'], [';\n readonly \\u0061b // c </T>', 'hidden'], [';\n m @x // c </T>', 'closes'],
+ // A word written with an escape (`\u0061`) is one name, so a name before it, with white space between, is followed by a second name, which TypeScript rejects. The reading takes the escape for no word and says nothing of
+ // what follows it (an escape may go on the name before it, `a\u0061b`, and the word it spells may be a keyword).
+ [';\n m \\u0061 // c </T>', 'hidden'],
+ // A keyword where a member begins is its name, unless it may be a modifier, which a `:` after it makes a name too; after a colon a keyword is the word of a type.
+ [';\n type // c\n /d </T>', 'closes'], [';\n new // c\n /d </T>', 'closes'], [';\n return: https://x.y\n /d </T>', 'closes'], [';\n default: https://x.y\n /d </T>', 'closes'], [';\n in: https://x.y\n /d </T>', 'closes'],
+ [';\n default : https://x.y\n /d </T>', 'closes'], [';\n in\t: https://x.y\n /d </T>', 'closes'], [';\n in\n : https://x.y\n /d </T>', 'closes'], [';\n in\n : T // c </T>', 'hidden'], [';\n typeof\r\n :https://x.y\n / x </T>', 'closes'],
+ [';\n readonly https://x.y\n /d </T>', 'closes'], [';\n in // c\n /d </T>', 'closes'], [';\n m: keyof T // c </T>', 'hidden'], [';\n m: typeof x // c </T>', 'hidden'], [';\n m: new T // c </T>', 'hidden'],
+ [';\n type b // c </T>', 'closes'], [';\n new b // c </T>', 'closes'], [';\n readonly b // c </T>', 'hidden'], [';\n get b // c </T>', 'hidden'], [';\n static b // c </T>', 'hidden'],
+ [';\n https://x.y\n as: https://z\n /b </T>', 'closes'], [';\n a: void // c </T>', 'hidden'], [';\n a: void b // c </T>', 'closes'], [';\n a: type b // c </T>', 'closes'], [';\n a: unique symbol // c </T>', 'hidden'],
+ [';\n a: readonly b // c </T>', 'hidden'], [';\n a: import b // c </T>', 'hidden'],
+ // A sign, an operator or a closing bracket where a member begins is TS1131, and after a name on its line TS1005; so is a `.` after a name, unless the name is a number, and a quote after a name (a name and a string).
+ // `&` and `|` begin no member only after a name: a line break puts them at the start of a line that goes on a type.
+ [';\n - // c </T>', 'closes'], [';\n * // c </T>', 'closes'], [';\n ) // c </T>', 'closes'], [';\n a-b // c </T>', 'closes'], [';\n a. // c </T>', 'closes'], [';\n e.g. // c </T>', 'closes'], [';\n a & b // c </T>', 'closes'],
+ [';\n a | b // c </T>', 'closes'], [";\n it's // c </T>", 'closes'], [';\n 5% // c </T>', 'closes'], [';\n 1.5 // c </T>', 'hidden'], [';\n | // c </T>', 'closes'], [';\n a? // c </T>', 'hidden'], [';\n a?: https://x.y\n /b </T>', 'closes'],
+ [';\n + // c </T>', 'closes'], [';\n % // c </T>', 'closes'], [';\n ^ // c </T>', 'closes'], [';\n ~ // c </T>', 'closes'], [';\n ] // c </T>', 'closes'], [';\n a+b // c </T>', 'closes'], [';\n a*b // c </T>', 'closes'], [';\n a^b // c </T>', 'closes'],
+ [';\n a~b // c </T>', 'closes'], [';\n a] // c </T>', 'closes'], [';\n a)b // c </T>', 'closes'], [';\n a"b // c </T>', 'closes'], [';\n & // c </T>', 'closes'], [';\n 9.5 // c </T>', 'hidden'], [';\n 0.5 // c </T>', 'hidden'],
+ [';\n a? b // c </T>', 'closes'], [';\n a!\n // c </T>', 'closes'], [';\n (a) // c </T>', 'hidden'], [";\n 'a' // c </T>", 'hidden'], [';\n [a] // c </T>', 'hidden'], [';\n a = 1 // c </T>', 'closes'],
+ // A name, a number, a string or a signature with a `=` right after it on its line is no member (TS1131; TS1005 after a signature): the parser takes a name for a member's only where `?`, `:`, `(`, `<`, `,` or the end of its
+ // line follows it. The initializer that a property signature may have (the checker rejects it, the parser does not) comes after a `?`, a type, a computed name, `get` or `set` (a name there), or a line break.
+ [";\n 'a' = 1 // c </T>", 'closes'], [';\n 1.5 = 1 // c </T>', 'closes'], [';\n m(y) = 1 // c </T>', 'closes'], [';\n m(a = 1) = 1 // c </T>', 'closes'], [';\n new = 1 // c </T>', 'closes'], [';\n m? = 1 // c </T>', 'hidden'], [';\n [m] = 1 // c </T>', 'hidden'],
+ [';\n get = 1 // c </T>', 'hidden'], [';\n m\n = 1 // c </T>', 'hidden'], [';\n m: A = 1 // c </T>', 'hidden'], [';\n x = // c\n /b </T>', 'closes'], [';\n x = b + // c\n /b </T>', 'closes'], [';\n x = [ // c\n /b </T>', 'closes'],
+ [';\n m? = // c\n /b </T>', 'hidden'], [';\n m: A = // c\n /b </T>', 'hidden'], [';\n [x] = // c\n /b </T>', 'hidden'], [';\n m\n = // c\n /b </T>', 'hidden'], [';\n get = // c\n /b </T>', 'hidden'],
+ // A parameter list that is not closed on its line: a name or a keyword and a `(` start one, whose first parameter is read as a head's is (parameterListMayStart, parameterSyntaxFails), so a `/` after the comment that follows the
+ // `(` is TS1138, and prose in it — two names, a number, a string, an operator — is no list at all. A default or a type that goes on after a comment may hold a regex, and the closing tag may be in it.
+ [';\n foo( // note\n /docs </T>', 'closes'], [',\n f(\n /docs </T>', 'closes'], [';\n a( // c\n /b </T>', 'closes'], [';\n if ( // c\n /b </T>', 'closes'], [';\n see foo( // c\n /b </T>', 'closes'], [';\n Total (x y // c\n /b </T>', 'closes'],
+ [';\n m(1) // c\n /b </T>', 'closes'], [";\n m('a') // c\n /b </T>", 'closes'], [';\n m(see docs) // c </T>', 'closes'], [';\n m(a b) // c </T>', 'closes'], [';\n m(Note: <a href="/help">see</a>) // c </T>', 'closes'], [';\n ( // c\n /b </T>', 'closes'],
+ [';\n new ( // c\n /b </T>', 'closes'], [';\n readonly ( // c\n /b </T>', 'closes'], [';\n (a // c\n /b </T>', 'closes'], [';\n m(a = // c\n /b </T>', 'hidden'], [';\n m(a: // c\n /b </T>', 'hidden'], [';\n m(a) // c </T>', 'hidden'],
+ [';\n m(a, b?: c) // c </T>', 'hidden'], [';\n m(... // c\n /b </T>', 'hidden'], [';\n [ // c\n /b </T>', 'hidden'], [';\n [a] // c\n /b </T>', 'closes'], [';\n a: b = // c\n /b </T>', 'hidden'],
+ // A `[`, a name and a `,` or a `:` are an index signature for certain (isUnambiguouslyIndexSignature), and no parameter or type starts with a `/` (TS1138, TS1110). A keyword or a number there is a computed name with a comma
+ // expression (`[this, /x/]`), which a regex may follow, and a name alone divides.
+ [';\n [ a, // c\n /b </T>', 'closes'], [';\n [ k: // c\n /b </T>', 'closes'], [';\n [a,\n // c\n /b </T>', 'closes'], [';\n [a, /b </T>', 'closes'], [';\n readonly [ a, // c\n /b </T>', 'closes'], [';\n m: A\n [ a, // c\n /b </T>', 'closes'],
+ [';\n [ this, // c\n /b </T>', 'hidden'], [';\n [ 1, // c\n /b </T>', 'hidden'], [';\n [ a // c\n /b </T>', 'closes'],
+ // ... except after `get` or `set`: parseTypeMember tries parseContextualModifier(get) before isIndexSignature, and canFollowGetOrSetKeyword takes any `[`, on any line, so `get [a, /x/]()` is an accessor whose computed name is a comma
+ // expression with a regex in it, which holds the closing tag. After any other word it is the index signature that no `/` follows.
+ [';\n get [a, /[</T>]/](): string', 'hidden'], [';\n set [a, /[</T>]/](v)', 'hidden'], [';\n get\n [a, /[</T>]/](): string', 'hidden'], [';\n get /* c */ [a, /[</T>]/](): string', 'hidden'], [';\n get // c\n [a, // note\n /[</T>]/](): string', 'hidden'],
+ [';\n static get [a, /[</T>]/](): string', 'hidden'], [';\n readonly get [a, /[</T>]/](): string', 'hidden'], [';\n get\u2028[a, /[</T>]/](): string', 'hidden'], [';\n get [a: // c\n /[</T>]/](): string', 'hidden'],
+ [';\n readonly [a, /[</T>]/]: string', 'closes'], [';\n static [a, /[</T>]/]: string', 'closes'], [';\n [a, /[</T>]/]: string', 'closes'], [';\n get: A\n [a, /[</T>]/]: string', 'closes'], [';\n get(): A\n [a, /[</T>]/]: string', 'closes'],
+ [';\n get;\n [a, /[</T>]/]: string', 'closes'],
+ // The `(` after `typeof import`, or `import`, is the import type's, which has no line-break rule (isStartOfTypeOfImportType, parseImportType): on a line of its own it is no signature's parameter list, whose first token a string is not, so
+ // the text is no type's only where a name and a `(` stand. The type goes on as any type does: a qualified name, a union, an array. A type query on a name (`typeof A.import`, `typeof a`) is a type that ends, and a `(` on the next line starts
+ // a call signature.
+ [';\n m: typeof import\n(\'./m\') // c </T>', 'hidden'], [';\n m: typeof import /* c */\n(\'./m\') // c </T>', 'hidden'], [';\n m: typeof /* c */ import\n(\'./m\') // c </T>', 'hidden'], [';\n m: typeof\nimport\n(\'./m\') // c </T>', 'hidden'],
+ [';\n m: typeof\r\nimport // c\r\n(\'./m\') // c </T>', 'hidden'], [';\n m: typeof\rimport\r(\'./m\') // c </T>', 'hidden'], [';\n m: typeof\u2028import\u2029(\'./m\') // c </T>', 'hidden'], [';\n m: typeof\u0085import\u0085(\'./m\') // c </T>', 'hidden'],
+ [';\n m: keyof typeof import\n(\'./m\') // c </T>', 'hidden'], [';\n m: readonly typeof import\n(\'./m\')[] // c </T>', 'hidden'], [';\n m: A | typeof import\n(\'./m\') // c </T>', 'hidden'], [';\n m(): typeof import\n(\'./m\').X // c </T>', 'hidden'],
+ [';\n m: typeof import\n(\'</T>\') ', 'hidden'], [';\n m: typeof import\n(`./m`) // c </T>', 'hidden'], [';\n m: import\n(\'./m\') // c </T>', 'hidden'], [';\n m: typeof import(\'./m\') // c </T>', 'hidden'],
+ [';\n m: typeof A.import\n(\'x\') // c </T>', 'closes'], [';\n m: typeof a\n(\'x\') // c </T>', 'closes'], [';\n m: typeof importer\n(\'x\') // c </T>', 'closes'], [';\n m: typeof import_\n(\'x\') // c </T>', 'closes'],
+ [';\n m: typeof import\u00e9\n(\'x\') // c </T>', 'closes'], [';\n m: A\n(\'x\') // c </T>', 'closes'],
+ // After a `:` or a type, a `[` opens a tuple or an indexed access, whose first token is a type, and a `/` that begins no comment is none (TS1110): `Total: [ // note` and a line break, then `/docs`. After a line break that follows a name or a
+ // type, a `[` begins a member (a computed name or an index signature), and a regex may follow it.
+ [';\n Total: [ // c\n /b </T>', 'closes'], [';\n m: A[ // c\n /b </T>', 'closes'], [';\n m: [ /* c */ /b </T>', 'closes'], [';\n m: A | [ // c\n /b </T>', 'closes'], [';\n m: keyof [ // c\n /b </T>', 'hidden'],
+ [';\n m\n [ // c\n /b </T>', 'hidden'], [';\n m: A\n [ // c\n /b </T>', 'hidden'], [';\n [ // c\n /b </T>', 'hidden'], [';\n m: [ // c\n a, /b </T>', 'hidden'],
+ // Where a type must be, a `,` or a `;` is TS1110, and so are a sign, a `=` and a closing bracket; a member's type may begin on a line of its own: `a:` and a line break, then `-1`, is a member. A `-` is not told from the
+ // sign of a number, and a `.` from the start of one.
+ [';\n a:\n - // c </T>', 'hidden'], [';\n a:, b c // d </T>', 'closes'], [';\n a: ; b c // d </T>', 'closes'], [';\n a: = 1 // c </T>', 'closes'], [';\n a: + // c </T>', 'closes'], [';\n a: ) // c </T>', 'closes'],
+ [';\n a: -1 // c </T>', 'hidden'], [';\n a: .5 // c </T>', 'hidden'], [';\n a: * // c </T>', 'hidden'], [';\n a: ? // c </T>', 'hidden'], [';\n a: | // c </T>', 'hidden'], [';\n a: || // c </T>', 'closes'],
+ // A type goes on with a `.`, a `|` or a `&`, on its line or the next, and what follows must be a type; a keyword after a type is TS1005 unless it is `extends` (a conditional type) or `is` (a type predicate); a keyword
+ // that an operator type takes (`keyof`, `typeof`, `unique`) leaves a type to follow.
+ [';\n a: A.B // c </T>', 'hidden'], [';\n a: A. // c\n /b </T>', 'closes'], [';\n a: A | B // c </T>', 'hidden'], [';\n a: A | // c\n /b </T>', 'closes'], [';\n a: A & // c\n /b </T>', 'closes'], [';\n a: A\n & // c\n /b </T>', 'closes'],
+ [';\n a: A.B, // c\n /b </T>', 'closes'], [';\n a: A | B; // c\n /b </T>', 'closes'], [';\n a: A default // c </T>', 'closes'], [';\n a: A in // c </T>', 'closes'], [';\n a: A extends // c </T>', 'hidden'], [';\n a: A is // c </T>', 'hidden'],
+ [';\n a: keyof A // c </T>', 'hidden'], [';\n a: keyof // c\n /b </T>', 'closes'], [';\n a: typeof x.y | z, // c\n /b </T>', 'closes'], [';\n a: unique symbol, // c\n /b </T>', 'closes'], [';\n a: keyof typeof x, // c\n /b </T>', 'closes'],
+ // A word right after a block comment is no part of it.
+ [';\n ( /* c */b /d </T>', 'closes'], [';\n ( /* c */b // d </T>', 'hidden'],
+ // A character beyond ASCII is part of a name or no token at all (TS1127): a name, and then a second name. White space beyond ASCII ends a name.
+ [';\n caf\u00e9 // c </T>', 'hidden'], [';\n caf\u00e9 au lait // c </T>', 'closes'], [';\n \u65e5\u672c\u8a9e https://x.y\n /b </T>', 'closes'], [';\n \u2014 // c </T>', 'hidden'], [';\n a \u2014 // c </T>', 'closes'],
+ [';\n a\u00a0b // c </T>', 'closes'], [';\n a\u200bb // c </T>', 'closes'], [';\n a\ufeffb // c </T>', 'closes'], [';\n a\u2028b // c </T>', 'hidden'], [';\n a\u0085b // c </T>', 'closes'],
+ // The openers: a regex where no type has one, after a name, a colon or a type; a template where a member begins and after a name, and a type after a colon; a string after a name, and a name or a type elsewhere.
+ [';\n /b </T>', 'closes'], [';\n a: /b </T>', 'closes'], [';\n a: b ; /c </T>', 'closes'], [';\n `a </T>`', 'closes'], [';\n a `b </T>`', 'closes'], [';\n a: `b </T>`', 'hidden'], [';\n a: b `c </T>`', 'hidden'],
+ [";\n 'a </T> b'", 'hidden'], [";\n a 'b </T> c'", 'closes'], [";\n a: 'b </T> c'", 'hidden'], [";\n a: b 'c </T> d'", 'hidden'], [';\n type `a </T>`', 'closes'], [';\n readonly `a </T>`', 'closes'],
+ // A number is a name, as the scanner reads one (scanNumber): digits, a fraction, and an exponent whose `e` takes a sign — ONE token, a valid name for a member, so `1e-5: …` is a member and a type may hold the closing tag in what
+ // follows it. A sign that no digit follows is TS1124, and a hex literal has no exponent (`0x1e+5` is a name, a sign and a number). Two numbers, or a number and a word, are two names.
+ [';\n 1e-5 // c </T>', 'hidden'], [';\n 1e+5: // c </T>', 'hidden'], [';\n 1E-5?: // c </T>', 'hidden'], [';\n 1_0e+1(): // c </T>', 'hidden'], [';\n .5e-3 // c </T>', 'hidden'], [';\n 1_0E-1_0 // c </T>', 'hidden'],
+ [';\n 1e-5: A | B // c </T>', 'hidden'], [', 1e+5(): `a </T>`', 'hidden'], [';\n 1e-5\n 2e-5 // c </T>', 'hidden'], [';\n 1e5x // c </T>', 'hidden'], [';\n 1e-5 b // c </T>', 'closes'], [';\n 1e+x // c </T>', 'closes'],
+ [';\n 1e+ // c </T>', 'closes'], [';\n 1e- // c </T>', 'closes'], [';\n 0x1e+5 // c </T>', 'closes'], [';\n 1e+5.5 // c </T>', 'closes'], [';\n 1e+5 https://x.y\n /b </T>', 'closes'], [';\n 1e-5 2 // c </T>', 'closes'],
+ // An initializer's first operand — a name, a number or a string — and a second one on its line are TS1005, wherever the keyword before them is none (a keyword may be an operator); on the next line the second is a member's name.
+ [';\n a: A = 1 b // c </T>', 'closes'], [";\n a: A = 1 'b' // c </T>", 'closes'], [';\n a: A = b c // c </T>', 'closes'], [';\n a: A = b.c d // c </T>', 'hidden'], [';\n a: A = 1 in // c </T>', 'hidden'], [';\n a: A = 1 as // c </T>', 'hidden'],
+ [';\n a: A = 1 // c </T>', 'hidden'], [';\n a: A = 1\n b // c </T>', 'hidden'], [';\n a? = 1 b // c </T>', 'closes'], [';\n [a] = 1 b // c </T>', 'closes'], [';\n a: A = 1 https://x.y\n /b </T>', 'closes'],
+ // The text of a nested element is JSX text to a type that reads the element, which has no string, template or comment in it, and code to a reading that does not: what it opens ends with the element, and what stands after
+ // the closing tag is read again — a quote, a back-tick or a regex there may hold the closing tag of the head. A `//` in the text does not decide a `/` on the next line by the word before it.
+ ['; m(a = <b>x // y</b> +\n /[ </T>', 'hidden'], ['; [<b>x // y</b> +\n /[ </T>', 'hidden'], ['; m(a = <>x // y</> ||\n // more\n /[ </T>', 'hidden'], ['; m(a = <b>x /* y</b> +\n /[ </T>', 'hidden'],
+ ["; m(a = <b>'x</b> + '</T>'", 'hidden'], ['; m(a = <b>`x</b> + `</T>`', 'hidden'], ['; m(a = <b>x // y</b> + `\n</T>`', 'hidden'], ['; m(a = <b>"x</b> + "</T>"', 'hidden'], ["; m(a = <b><i>'x</i></b> + '</T>'", 'hidden'],
+ // A string, a template or a regex that holds the text of an element is one token: the closing tag inside it closes nothing, and the quote that ends it is no opener, so the string after it still hides the closing tag.
+ ["; m(a = '<b>c</b>' + '</T>')", 'hidden'], ['; m(a = `<b>c</b>` + `</T>`)', 'hidden'], ["; [`<b>x</b>` + '</T>']: string", 'hidden'], ["; m(a = '<b>c</b> d <i>e</i>' + '</T>')", 'hidden'],
+ // ... and the tags in two of them — `<b>` in one, `</b>` in the next — are no element's: they open and close in the element reading and in no other, so what stands between and after the literals is read as code.
+ ["; m(a = 'a <b>' + /* c */ `</b>` && `</T>`)", 'hidden'], ["; m(a = /* <b> */ `</b>` = `\n</T>`)", 'hidden'], ["; m: A = f('<b>') == 'c</b>', '</T>'", 'hidden'], ["; m(a = 'a <b>' instanceof\n // more\n `</b>` - `</T>`)", 'hidden'],
+ ["; m(a = '<>' + /* c */ `</>` && `</T>`)", 'hidden'], ["; m: A = <b>`</b> in\n // more\n <b>`</b> && `</T>`", 'hidden'], ["; m(a = <>//</> - <i><i/>https://x.y///* c */https://x.y</i> ?? `\n</T>`)", 'hidden'],
+ // The members of a type after a line break or an unclosed string: an initializer goes on after a name or a type on the next line, `?` is an optional mark after a name, and a quote with no closing quote on its line is TS1002.
+ [';\n m\n ? https://x.y // c </T>', 'closes'], [';\n m: A\n = 1 b // c </T>', 'closes'], [';\n m\n = 1 b // c </T>', 'closes'], [";\n 'a b // c </T>", 'closes'], ["; 'a // c </T>", 'closes'], [';\n a: . // c </T>', 'closes'], [';\n a: ...b // c </T>', 'closes'],
+ ];
+ for (const [text, expected] of rows) assert.strictEqual(closes(text), expected, JSON.stringify(text));
+ // The reading goes on from where it stopped: a run of comments and of lines is read once, in the window, and a name read before a comment is the name read after it.
+ const lines = `;\n${' b // c\n'.repeat(150)} /d </T>`;
+ assert.strictEqual(closes(lines), 'closes');
+ assert.strictEqual(closes(`;\n${' a: // c\n b\n'.repeat(100)} c // d </T>`), 'hidden');
+ assert.strictEqual(closes(`;\n${' a: // c\n b\n'.repeat(100)} c d // d </T>`), 'closes');
+ // The lexer's tables are what the family of elements, the lines it does not read and the hidden ones are: every element of the family is certain, the rest are a guess (helpers/angle-frames.js).
+ const ELEMENT = { generic: false, ambiguity: null };
+ const GUESS = { generic: false, ambiguity: 'generic' };
+ const wrong = [];
+ for (const element of proseElements()) if (opensTypeParameters(element, 0).ambiguity !== ELEMENT.ambiguity) wrong.push(JSON.stringify(element));
+ for (const element of proseElements({ lines: PROSE_SHAPED_LINES })) if (opensTypeParameters(element, 0).ambiguity !== ELEMENT.ambiguity) wrong.push(JSON.stringify(element));
+ for (const element of PROSE_HIDING_ELEMENTS) if (opensTypeParameters(element, 0).ambiguity !== GUESS.ambiguity) wrong.push(JSON.stringify(element));
+ assert.deepStrictEqual(wrong.slice(0, 5), [], 'a text of the family that is guessed at, or one that is not guessed at where it must be');
+ // The keywords, where a member begins: one that TypeScript's parser may take for a modifier (and `get` and `set`) may be followed by a name, and any other is a name that no name follows. (The oracle's own list is checked below.)
+ const modifiers = new Set(['abstract', 'accessor', 'async', 'const', 'declare', 'default', 'export', 'in', 'out', 'override', 'private', 'protected', 'public', 'readonly', 'static', 'get', 'set']);
+ const contextual = ['of', 'await', 'yield', 'let', 'as', 'satisfies', 'type', 'from', 'keyof', 'infer', 'is', 'asserts', 'using', 'module', 'namespace', 'global', 'unique', 'implements', 'interface', 'package'];
+ for (const word of [...RESERVED_WORDS, ...contextual, ...modifiers]) assert.strictEqual(closes(`;\n ${word} b // c </T>`), modifiers.has(word) ? 'hidden' : 'closes', `${word} and a name`);
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.diagnostic('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to check the claims');
+ // The keywords are TypeScript's: where a member begins, one that its parser takes for a modifier — and `get` and `set` — may be followed by a name, and any other is a name that no name follows.
+ if (typeof ts.isModifierKind !== 'function') return t.diagnostic('the oracle has no isModifierKind: the keywords are not checked against it');
+ let keywords = 0;
+ for (let kind = ts.SyntaxKind.FirstKeyword; kind <= ts.SyntaxKind.LastKeyword; kind += 1) {
+ const word = ts.tokenToString(kind);
+ const modifier = ts.isModifierKind(kind) || word === 'get' || word === 'set';
+ keywords += 1;
+ assert.strictEqual(closes(`;\n ${word} b // c </T>`), modifier ? 'hidden' : 'closes', `${word} and a name`);
+ assert.strictEqual(closes(`;\n ${word}: https://x.y\n /b </T>`), 'closes', `${word} and a colon`);
+ if (!modifier) assert.ok(firstDiagnostic(ts, `${PROSE_HEAD};\n ${word} b // c </T>\n}\n`) <= `${PROSE_HEAD};\n ${word} `.length, `TypeScript rejects ${word} and a name`);
+ // A word beside an initializer's operand on its line is TS1005 unless it may continue the expression, which a keyword may (`1 in b`, `1 as T`, `1 satisfies T`, `1 instanceof B`): every keyword is left alone, and only a
+ // word that is none is an error. The table of keywords is TypeScript's, every one of them.
+ assert.strictEqual(closes(`;\n a: A = 1 ${word} // c </T>`), 'hidden', `a: A = 1 and ${word}`);
+ assert.strictEqual(closes(`;\n a: A = b ${word} // c </T>`), 'hidden', `a: A = b and ${word}`);
+ }
+ assert.ok(keywords > 80, `${keywords} keywords`);
+ for (const word of ['b', 'x1', '$y', '_z', 'caf\u00e9', 'async1', 'Type', 'IN', 'Of', 'asy', 'ofs']) {
+ assert.strictEqual(closes(`;\n a = 1 ${word} // c </T>`), 'closes', `a = 1 and ${word}`);
+ assert.strictEqual(closes(`;\n a = 'b' ${word} // c </T>`), 'closes', `a = 'b' and ${word}`);
+ assert.strictEqual(closes(`;\n a = b ${word} // c </T>`), 'closes', `a = b and ${word}`);
+ }
+});
+
+// A word after a `.` is a name, whatever it spells (`A.new`, `A.unique`: parseRightSideOfDot takes identifier names), and so is one after `typeof`, which takes an entity name, and `infer`, which takes an identifier (`infer
+// keyof`); `keyof`, `readonly` and `unique` take a type, which `new` is the name of there (`keyof new`) and which they themselves may begin. A unicode escape is part of a name (`a\u0061b` is ONE identifier), and a hex,
+// octal or binary literal ends at its last digit: `0x1Fin` is `0x1F` and `in`, which the scanner reads with no diagnostic (a word right after a decimal literal is TS1351). Each row is the text after the `)` of `<T>(x)`, up
+// to and including what holds the closing tag: 'hidden' where a type may hold it, 'closes' where no type has the text. TypeScript says which: where a type is valid up to the closing tag its parser reports nothing before it.
+test('typeMembersFail: a word after a `.` or an operator word, an escape in a name and a literal that ends before its word are read as TypeScript reads them', (t) => {
+ const closes = (text) => {
+ const read = elementChildren(`<T>(x)${text}`, 3, 'T', null, 6);
+ return read === null ? 'unknown' : read.fails !== undefined ? 'fails' : read.hideable ? 'hidden' : 'closes';
+ };
+ const hidden = [
+ // After a `.`, `typeof` and `infer`, every word is a name: the `,` or `;` after it ends a member, and the type goes on.
+ ';\n a: A.unique; // c </T>', ';\n a: A.new, // c </T>', ';\n a: A.keyof; // c </T>', ';\n a: A.infer, // c </T>', ';\n a: A.readonly; // c </T>', ';\n a: A.typeof, // c </T>', ';\n a: A.B.in; // c </T>',
+ ';\n a: A | A.unique; // c </T>', ';\n a: typeof A.keyof; // c </T>', ';\n a: typeof new; // c </T>', ';\n a: typeof unique, // c </T>', ';\n a: infer keyof, // c </T>', ';\n a: infer infer; // c </T>', ';\n a: infer unique, // c </T>',
+ // After `keyof`, `readonly` and `unique` a type follows, which a keyword is the name of, or another of those words begins.
+ ';\n a: keyof new, // c </T>', ';\n a: keyof typeof new; // c </T>', ';\n a: readonly new; // c </T>', ';\n a: keyof readonly A[], // c </T>', ';\n a: keyof unique symbol, // c </T>', ';\n a: unique keyof A; // c </T>',
+ ';\n a: readonly keyof A[]; // c </T>',
+ // A name with an escape in it is one name: the escape goes on the name before it, and the name goes on with what follows.
+ ';\n a\\u0061b // c </T>', ';\n a\\u0061b: A; // c </T>', ';\n a: A\\u0061b; // c </T>', ';\n a: A.b\\u0061; // c </T>', ';\n a: \\u0061; // c </T>',
+ // A hex, binary or octal literal ends at its last digit, and a word right after it is a second token — an operator, where it is one: a string or a regex after it begins one.
+ ";\n a: A = 0x1Fin 'b </T> c'", ";\n a: A = 0b1in 'b </T> c'", ";\n a: A = 0o7in 'b </T> c'", ";\n a: A = 0x1Finstanceof 'b </T> c'", ";\n a: A = 0x1Fin'b </T> c'", ';\n a: A = 0x1Fin\n /[</T>]/', ';\n a: A = 0x1Fin /re </T>/',
+ ";\n a: A = 0x1Fnin 'b </T> c'", ";\n a: A = 0x1Fin 0x1F in 'b </T> c'", ";\n a: A = 0xFFin'x' // c </T>", ';\n a: A = 0x1F in\n /[</T>]/',
+ ];
+ const dead = [
+ // A word that no operand has after it, and no type begins with: TS1110, TS1005.
+ ';\n a: keyof readonly, // c </T>', ';\n a: keyof unique, // c </T>', ';\n a: unique, // c </T>', ';\n a: keyof, // c </T>', ';\n a: new, // c </T>',
+ // A word right after a decimal literal, and one that is no operator after a hex literal: two operands side by side, or an `as` and a regex where a type must be.
+ ";\n a: A = 1in 'b </T> c'", ";\n a: A = 1.5in 'b </T> c'", ';\n a: A = 1in\n /[</T>]/', ';\n a: A = 1\n /[</T>]/', ";\n a: A = 0x1Fb 'b </T> c'", ";\n a: A = 0x1F 'b </T> c'", ";\n a: A = 0x1Fn 'b </T> c'", ";\n a: A = 0B1IN 'b </T> c'",
+ ';\n a: A = 0x1Fx // c </T>', ';\n a: A = 0x1Fas\n /[</T>]/', ';\n a: A = 0x1F\n /[</T>]/',
+ ];
+ for (const text of hidden) assert.strictEqual(closes(text), 'hidden', JSON.stringify(text));
+ for (const text of dead) assert.strictEqual(closes(text), 'closes', JSON.stringify(text));
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.diagnostic('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to check the readings');
+ for (const text of hidden) assert.ok(firstDiagnostic(ts, `${PROSE_HEAD}${text}\n}\n`) > PROSE_HEAD.length + text.indexOf('</T>'), `TypeScript parses ${JSON.stringify(text)} as a type up to the closing tag`);
+ for (const text of dead) assert.ok(firstDiagnostic(ts, `${PROSE_HEAD}${text}\n}\n`) <= PROSE_HEAD.length + text.indexOf('</T>'), `TypeScript rejects ${JSON.stringify(text)} at or before the closing tag`);
+});
+
+// The claims are made over every text of up to three tokens of the pieces of a member and what TypeScript rejects there (numbers of every spelling, brackets, strings, tags, operators), over seeded draws of more, over runs of
+// valid members that are mutated at one or two places — the texts that are nearest to a type, where a rule that says too much is wrong — and over every keyword of TypeScript where a word may stand, after a `.` or an
+// operator word (`A.new`, `keyof new`, `infer keyof`), and right after a number (`0x1Fin`); over an import type with a line terminator, a space or a comment between its tokens, over `get`, `set` and every other modifier before a
+// computed name that holds a comma and a regex, and over a `[` after a `:` or a type, whose first token is a `/`.
+test('typeMembersFail, sweep (TypeScript parser): every text read as no type\'s members is rejected by TypeScript at or before what could hide the closing tag', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip('no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it');
+ const keywords = [];
+ for (let kind = ts.SyntaxKind.FirstKeyword; kind <= ts.SyntaxKind.LastKeyword; kind += 1) keywords.push(ts.tokenToString(kind));
+ const sweeps = [
+ ['every text of up to three of the first tokens', tokenTexts(BASE_TOKENS, 3), 20000],
+ ['every text of up to two of all the tokens', tokenTexts(ALL_TOKENS, 2), 10000],
+ ['seeded draws of four to seven of all the tokens', drawnTexts(ALL_TOKENS, 20261104, 40000), 30000],
+ ['runs of valid members, mutated', memberTexts(20261105, 60000), 20000],
+ ['every keyword in each place where a word may stand', keywordTexts(keywords), 30000],
+ ['every keyword after each keyword that a type or a member may start with', keywordPairTexts(keywords), 8000],
+ ['every keyword after a `.`, `typeof`, `infer`, `keyof`, `readonly` and `unique`, with what may follow', wordTexts(keywords), 8000],
+ ['a number of every spelling and a word, a quote or a `/` right after it', numberWordTexts(keywords), 2000],
+ ['an import type with trivia between its tokens, and a type query before a `(` on the next line', importTypeTexts(), 1500],
+ ['seeded draws of an import type in each place a type stands', drawnImportTypeTexts(20261301, 20000), 14000],
+ ['`get`, `set` and every other modifier before a computed name that holds a comma or a colon and a regex', accessorNameTexts(), 3000],
+ ['seeded draws of a modifier, a computed name and a regex', drawnAccessorNameTexts(20261302, 20000), 8000],
+ ['a `[` after a `:`, a type or an operator type, then trivia and a `/`', tupleTexts(), 2000],
+ ['a `/` after an operand that ends in a bracket, or in none, behind a comment of every kind', bracketTexts(), 800],
+ ];
+ for (const [what, texts, least] of sweeps) {
+ const { stats, unsound } = deadClaims(ts, texts);
+ t.diagnostic(`${what}: ${stats.texts} texts (${stats.unterminated} end in a literal that nothing closes), ${stats.claims} claims that a type cannot have them, ${unsound.length} that TypeScript does not support`);
+ assert.deepStrictEqual(unsound.slice(0, 5), [], `${what}: a text read as no type's members that TypeScript parses as them, or whose first diagnostic is after the thing that opens`);
+ assert.ok(stats.claims >= least, `${what}: only ${stats.claims} claims were made, so the sweep proves little`);
+ }
+});
+
// What a closing tag that a string, a template or a comment in the parameter list holds is, in `interface I { <T>(x: "</T>") }`: a call signature, and `const e = <T>(x: "</T>;` is an element: both parse with no diagnostic. So a
// closing tag in the parameter list is a guess, and one that no string, template or comment holds is an element for certain, as it is after the parameter list.
test('a parameter list that holds its own closing tag in a string, a template or a comment is a guess; the same list with no closing tag in it, and after it, is an element for certain', (t) => {
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.js
new file mode 100644
index 000000000..0dfc9f3c0
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/table-columns-in-create.test.js
@@ -0,0 +1,1999 @@
+'use strict';
+
+// A new table is created exactly as the previous release created it — one request that carries only its primary name attribute —
+// and its ordinary columns then follow in ONE atomic change set (an OData `$batch`) instead of one request per column. These tests
+// run the real vendored SDK over a stub transport and count requests, and prove that every column the change set carries is
+// byte-for-byte the body the per-column path posts, that a change set the platform refuses (or the transport cannot send) falls back
+// to that per-column path with a warning, and that the primary name attribute's request is the previous release's on every path and
+// under both behaviours the platform has been measured to have. `inlineColumns: false` is the one-request-per-column path, the
+// oracle throughout.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/execute-batch-operations-using-web-api#change-sets
+
+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 { makeRunner, provisionDataModel, BuildHalt } = require('../lib/entity-provision.js');
+const { hash } = require('./helpers/read-probe.js');
+
+const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
+const ORG = 'https://contoso.crm.dynamics.com';
+const API = `${ORG}/api/data/v9.0`;
+
+const tempDirs = [];
+test.after(() => {
+ for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true });
+});
+
+const clone = (value) => JSON.parse(JSON.stringify(value));
+const hex = (n, width) => n.toString(16).padStart(width, '0');
+// A column's MetadataId is a function of the table and column, so both paths hand back the same id for it.
+const attributeId = (table, schema) => `${hex(hash(`${table}.${schema}`), 8)}-0000-4000-8000-${hex(hash(`${schema}.${table}`), 12)}`;
+const tableId = (schema) => `${hex(hash(`table.${schema}`), 8)}-0000-4000-8000-${hex(hash(`${schema}.table`), 12)}`;
+
+// --- a stub of the Dataverse metadata endpoints a table create touches -----------------------------
+
+// What Dataverse answers when a request would create an attribute twice: error 0x80060304,
+// "Attribute {0} already exists for entity {1}." — and it refuses the WHOLE request, creating nothing.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/web-service-error-codes
+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 columns a column creates beside itself: a Money column its base-currency twin, a choice or a Boolean its `<name>name`
+// shadow, a Customer lookup its three shadows `<name>name`, `<name>yominame` and `<name>idtype` (measured), a File column the
+// `<name>_name` that holds the file's name, an Image column its `<name>id`, `<name>_timestamp` and `<name>_url`, and a rollup
+// column its `<name>_date` and `<name>_state` (all three documented on Microsoft Learn: Use file column data, Use image column
+// data, Define rollup columns). A Money column that is a rollup has both its own and the rollup's.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/file-column-data#file-name-column
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/image-column-data#download-url
+// See: https://learn.microsoft.com/en-us/power-apps/maker/data-platform/define-rollup-fields
+const companions = (body) => {
+ const name = String(body.SchemaName).toLowerCase();
+ const type = String(body['@odata.type'] || '');
+ const found = [];
+ if (/MoneyAttributeMetadata$/.test(type)) found.push(`${name}_base`);
+ if (/(?:Picklist|MultiSelectPicklist|Boolean)AttributeMetadata$/.test(type)) found.push(`${name}name`);
+ if (/LookupAttributeMetadata$/.test(type)) found.push(`${name}name`, `${name}yominame`, `${name}idtype`);
+ if (/FileAttributeMetadata$/.test(type)) found.push(`${name}_name`);
+ if (/ImageAttributeMetadata$/.test(type)) found.push(`${name}id`, `${name}_timestamp`, `${name}_url`);
+ // SourceType 2 is a rollup column, whatever its data type (0 simple, 1 calculated).
+ if (body.SourceType === 2) found.push(`${name}_date`, `${name}_state`);
+ return found;
+};
+
+// The operations of the change set in a `$batch` request, as the SDK's createColumns renders it: one embedded HTTP request per
+// operation, each POSTing a column to the table's `Attributes` collection, with the solution header on EACH operation (the one on
+// the outer request is ignored by the platform) —
+// --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='new_ticket')/Attributes HTTP/1.1
+// Content-Type: application/json;type=entry
+// MSCRM.SolutionUniqueName: TableColumns
+//
+// {"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",...}
+// --changeset_<id>--
+// --batch_<id>--
+const parseChangeSet = (text) => {
+ const boundary = /^Content-Type:\s*multipart\/mixed;\s*boundary=(\S+)/im.exec(text)[1];
+ return text.split(`--${boundary}`).slice(1).filter((segment) => !segment.startsWith('--')).map((segment) => {
+ const mimeEnd = segment.indexOf('\r\n\r\n');
+ const mime = segment.slice(0, mimeEnd);
+ const http = segment.slice(mimeEnd + 4);
+ const headEnd = http.indexOf('\r\n\r\n');
+ const head = http.slice(0, headEnd).split('\r\n');
+ const [, method, url] = /^(\w+) (\S+) HTTP\/1\.1$/.exec(head[0]);
+ const headers = Object.fromEntries(head.slice(1).map((line) => [line.slice(0, line.indexOf(':')).trim(), line.slice(line.indexOf(':') + 1).trim()]));
+ const payload = http.slice(headEnd + 4).replace(/\r\n$/, '');
+ return { contentId: /^Content-ID:\s*(\S+)/im.exec(mime)[1], method, path: decodeURIComponent(url.replace(API, '')), headers, body: payload ? JSON.parse(payload) : undefined };
+ });
+};
+// What the platform answers a change set with: its own envelope, announcing its own boundary, and one part per operation it
+// answers (a refused change set answers only the operation that failed), correlated by Content-ID.
+const changeSetAnswer = (parts) => [
+ '--batchresponse_x',
+ 'Content-Type: multipart/mixed; boundary=changesetresponse_x',
+ '',
+ ...parts.flatMap((part) => [
+ '--changesetresponse_x',
+ 'Content-Type: application/http',
+ 'Content-Transfer-Encoding: binary',
+ `Content-ID: ${part.contentId}`,
+ '',
+ `HTTP/1.1 ${part.status} ${part.status === 204 ? 'No Content' : 'Bad Request'}`,
+ 'OData-Version: 4.0',
+ ...(part.body ? ['Content-Type: application/json; odata.metadata=minimal', '', JSON.stringify(part.body)] : []),
+ '',
+ ]),
+ '--changesetresponse_x--',
+ '--batchresponse_x--',
+ '',
+].join('\r\n');
+
+function fakeDataverse({
+ createCommitsThenFails = null, // (body) => response, sent AFTER the table was created: the answer to the create that made it is lost
+ batchFails = null, // (operations) => response | falsy, for a change set the platform REFUSES (nothing in it is created); a falsy answer lets it through
+ batchCommitsThenFails = null, // (operations) => response, sent AFTER a change set was committed: its answer is lost or unreadable
+ noPostRaw = false, // a transport that cannot send the body of a change set verbatim (no `postRaw`)
+ dropInline = [], // columns of a change set that the platform accepts and does not list afterwards
+ attributeReads = null, // (n, columns) => response | undefined; overrides the read of a table's columns by id
+ tableReadBack = null, // (table) => response | undefined; overrides the read the SDK makes of a table it just created
+ lookupLag = 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
+ lengthRead = null, // (n) => response | undefined; overrides the typed read of a text column's MaxLength
+ updateFails = null, // (body) => response, for the PUT of a typed column
+ extraCompanions = null, // (body) => names the platform makes beside a column that nothing in the build lists
+} = {}) {
+ const log = [];
+ const refusals = [];
+ const tables = new Map();
+ const optionSets = new Map();
+ let attributeReadCount = 0;
+ let lengthReadCount = 0;
+ const reply = (status, body, headers = {}) => ({ status, headers, body });
+ const refuse = (path, response) => { refusals.push({ path, message: response.body && response.body.error && response.body.error.message }); return response; };
+ const created = (location) => reply(204, null, { 'odata-entityid': `${API}/${location}` });
+ const columnRow = (table, body) => ({ MetadataId: attributeId(table.logical, body.SchemaName), LogicalName: String(body.SchemaName).toLowerCase() });
+ const companionsOf = (body) => [...companions(body), ...(extraCompanions ? extraCompanions(body) : [])];
+ const addColumn = (table, body) => {
+ table.columns.set(String(body.SchemaName).toLowerCase(), { body, row: columnRow(table, body) });
+ for (const name of companionsOf(body)) table.reserved.add(name);
+ };
+ // The first name in `bodies` (taken in order, each with its companions) that the table already has, else null.
+ const firstTaken = (table, bodies) => {
+ const taken = new Set([...table.reserved, ...table.columns.keys()]);
+ for (const body of bodies) {
+ for (const name of [String(body.SchemaName).toLowerCase(), ...companionsOf(body)]) {
+ if (taken.has(name)) return name;
+ taken.add(name);
+ }
+ }
+ return null;
+ };
+ const relative = (url) => decodeURIComponent(String(url).replace(API, ''));
+
+ const httpClient = {
+ get: async (url) => {
+ const p = relative(url);
+ log.push({ method: 'GET', path: p });
+ let m;
+ if ((m = /^\/EntityDefinitions\(LogicalName='([^']+)'\)\?\$select=LogicalName,EntitySetName$/.exec(p))) {
+ const t = tables.get(m[1]);
+ if (t && t.lagReads > 0) { t.lagReads -= 1; return reply(404, { error: { message: `no table ${m[1]} yet` } }); }
+ return t ? reply(200, { LogicalName: t.logical, EntitySetName: `${t.logical}s` }) : reply(404, { error: { message: `no table ${m[1]}` } });
+ }
+ if ((m = /^\/EntityDefinitions\(([0-9a-f-]{36})\)\?\$select=LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute$/.exec(p))) {
+ const t = [...tables.values()].find((x) => x.id === m[1]);
+ const override = t && tableReadBack && tableReadBack(t);
+ if (override) return override;
+ return t ? reply(200, { LogicalName: t.logical, EntitySetName: `${t.logical}s`, PrimaryIdAttribute: `${t.logical}id`, PrimaryNameAttribute: t.primaryName }) : reply(404, { error: { message: 'no such table id' } });
+ }
+ if ((m = /^\/EntityDefinitions\(([0-9a-f-]{36})\)\/Attributes\?\$select=MetadataId,LogicalName$/.exec(p))) {
+ attributeReadCount += 1;
+ const t = [...tables.values()].find((x) => x.id === m[1]);
+ const rows = t ? [...t.columns.values()].map((c) => c.row) : [];
+ const override = attributeReads && attributeReads(attributeReadCount, rows);
+ return override || (t ? reply(200, { value: rows }) : reply(404, { error: { message: 'no such table id' } }));
+ }
+ // The same read of a table found by NAME (a table whose create answer never reached the build has no id to read by).
+ if ((m = /^\/EntityDefinitions\(LogicalName='([^']+)'\)\/Attributes\?\$select=MetadataId,LogicalName$/.exec(p))) {
+ attributeReadCount += 1;
+ const t = tables.get(m[1]);
+ const rows = t ? [...t.columns.values()].map((c) => c.row) : [];
+ const override = attributeReads && attributeReads(attributeReadCount, rows);
+ return override || (t ? reply(200, { value: rows }) : reply(404, { error: { message: 'no such table' } }));
+ }
+ if ((m = /^\/EntityDefinitions\(LogicalName='([^']+)'\)\/Attributes\?\$select=LogicalName,RequiredLevel$/.exec(p))) {
+ const t = tables.get(m[1]);
+ return t ? reply(200, { value: [...t.columns.values()].map((c) => ({ LogicalName: c.row.LogicalName, RequiredLevel: c.body.RequiredLevel })) }) : reply(404, { error: { message: 'no such table' } });
+ }
+ // The read of a text column's length: one typed request that selects MaxLength and nothing else.
+ if ((m = /^\/EntityDefinitions\(LogicalName='([^']+)'\)\/Attributes\(LogicalName='([^']+)'\)\/Microsoft\.Dynamics\.CRM\.StringAttributeMetadata\?\$select=MaxLength$/.exec(p))) {
+ lengthReadCount += 1;
+ const override = lengthRead && lengthRead(lengthReadCount);
+ if (override) return override;
+ const t = tables.get(m[1]);
+ const column = t && t.columns.get(m[2]);
+ if (!column) return reply(404, { error: { message: `no column ${m[2]}` } });
+ return reply(200, { MaxLength: m[2] === t.primaryName ? t.primaryLength : column.body.MaxLength, MetadataId: column.row.MetadataId });
+ }
+ // The two reads of the SDK's updateColumn: the column's id and type by name, then its whole typed definition by id.
+ if ((m = /^\/EntityDefinitions\(LogicalName='([^']+)'\)\/Attributes\(LogicalName='([^']+)'\)\?\$select=MetadataId,AttributeType$/.exec(p))) {
+ const t = tables.get(m[1]);
+ const column = t && t.columns.get(m[2]);
+ return column ? reply(200, { MetadataId: column.row.MetadataId, AttributeType: 'String' }) : reply(404, { error: { message: `no column ${m[2]}` } });
+ }
+ if ((m = /^\/EntityDefinitions\(LogicalName='([^']+)'\)\/Attributes\(([0-9a-f-]{36})\)\/Microsoft\.Dynamics\.CRM\.StringAttributeMetadata$/.exec(p))) {
+ const t = tables.get(m[1]);
+ const column = t && [...t.columns.values()].find((c) => c.row.MetadataId === m[2]);
+ if (!column) return reply(404, { error: { message: `no column ${m[2]}` } });
+ const isPrimary = column.row.LogicalName === t.primaryName;
+ return reply(200, { ...clone(column.body), ...column.row, ...(isPrimary ? { MaxLength: t.primaryLength } : {}) });
+ }
+ // The probe the SDK's createGlobalOptionSet makes by name before it creates the option set.
+ if ((m = /^\/GlobalOptionSetDefinitions\(Name='([^']+)'\)\?\$select=MetadataId$/.exec(p))) {
+ return optionSets.has(m[1]) ? reply(200, { MetadataId: optionSets.get(m[1]) }) : reply(404, { error: { message: `no option set ${m[1]}` } });
+ }
+ throw new Error(`unexpected GET ${p}`);
+ },
+ post: async (url, body, options) => {
+ const p = relative(url);
+ log.push({ method: 'POST', path: p, body: clone(body), headers: (options && options.headers) || {} });
+ let m;
+ if (p === '/EntityDefinitions') {
+ // The build creates a table exactly as the previous release did: with its primary name attribute and nothing else. A request
+ // that carries columns is a regression, so the stub refuses to model one.
+ if (body.Attributes.length !== 1) throw new Error(`the table request carries ${body.Attributes.length - 1} column(s) beside the primary name attribute`);
+ const logical = String(body.SchemaName).toLowerCase();
+ if (tables.has(logical)) return refuse(p, reply(400, { error: { message: `Entities already exist: ${body.SchemaName}` } }));
+ const table = {
+ id: tableId(body.SchemaName), logical, primaryName: String(body.Attributes[0].SchemaName).toLowerCase(), columns: new Map(),
+ reserved: new Set([`${logical}id`, ...SYSTEM_COLUMNS]), lagReads: lookupLag,
+ // 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,
+ };
+ const collision = firstTaken(table, body.Attributes);
+ if (collision) return refuse(p, duplicateAttribute(collision, logical));
+ tables.set(logical, table);
+ addColumn(table, body.Attributes[0]);
+ if (createCommitsThenFails) return refuse(p, createCommitsThenFails(body));
+ return created(`EntityDefinitions(${table.id})`);
+ }
+ if ((m = /^\/EntityDefinitions\(LogicalName='([^']+)'\)\/Attributes$/.exec(p))) {
+ const t = tables.get(m[1]);
+ if (!t) return reply(404, { error: { message: `no table ${m[1]}` } });
+ const collision = firstTaken(t, [body]);
+ if (collision) return refuse(p, duplicateAttribute(collision, t.logical));
+ addColumn(t, body);
+ return created(`EntityDefinitions(LogicalName='${m[1]}')/Attributes(${attributeId(t.logical, body.SchemaName)})`);
+ }
+ if (p === '/CreateCustomerRelationships') {
+ const t = tables.get(body.OneToManyRelationships[0].ReferencingEntity);
+ if (t) {
+ const collision = firstTaken(t, [body.Lookup]);
+ if (collision) return refuse(p, duplicateAttribute(collision, t.logical));
+ addColumn(t, body.Lookup);
+ }
+ return reply(200, {});
+ }
+ if (p === '/GlobalOptionSetDefinitions') {
+ const id = attributeId('globalchoice', body.Name);
+ optionSets.set(body.Name, id);
+ return created(`GlobalOptionSetDefinitions(${id})`);
+ }
+ throw new Error(`unexpected POST ${p}`);
+ },
+ patch: async (url) => { throw new Error(`unexpected PATCH ${relative(url)}`); },
+ // The documented update of a column: a PUT of its whole typed definition, with MSCRM.MergeLabels so the labels already
+ // stored are kept — what the SDK's updateColumn sends.
+ put: async (url, body, options) => {
+ const p = relative(url);
+ log.push({ method: 'PUT', path: p, body: clone(body), headers: (options && options.headers) || {} });
+ const m = /^\/EntityDefinitions\(LogicalName='([^']+)'\)\/Attributes\(([0-9a-f-]{36})\)$/.exec(p);
+ if (!m) throw new Error(`unexpected PUT ${p}`);
+ if (updateFails) return refuse(p, updateFails(body));
+ const t = tables.get(m[1]);
+ const column = t && [...t.columns.values()].find((c) => c.row.MetadataId === m[2]);
+ if (!column) return reply(404, { error: { message: `no column ${m[2]}` } });
+ if (column.row.LogicalName === t.primaryName) t.primaryLength = body.MaxLength;
+ else column.body = { ...column.body, MaxLength: body.MaxLength };
+ return reply(204, null);
+ },
+ delete: async (url) => { throw new Error(`unexpected DELETE ${relative(url)}`); },
+ };
+ // An OData `$batch` of ONE change set, as the SDK's createColumns sends it (see parseChangeSet). All or nothing: an operation the
+ // platform refuses rolls the others back, and the answer is that operation's own, with its own status — the platform answers the
+ // first failure of a batch with the error of that request and processes no more.
+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/execute-batch-operations-using-web-api#handling-errors
+ if (!noPostRaw) {
+ httpClient.postRaw = async (url, text, options) => {
+ const p = relative(url);
+ if (p !== '/$batch') throw new Error(`unexpected raw POST ${p}`);
+ const operations = parseChangeSet(text);
+ log.push({ method: 'POST', path: p, headers: (options && options.headers) || {}, operations: clone(operations) });
+ if (batchFails) {
+ const answer = batchFails(operations);
+ // A falsy answer lets this change set through: a test that refuses the first sends only.
+ if (answer) {
+ refusals.push({ path: p, message: typeof answer.body === 'string' ? answer.body : answer.body && answer.body.error && answer.body.error.message });
+ return answer;
+ }
+ }
+ const staged = new Map();
+ for (const op of operations) {
+ const m = /^\/EntityDefinitions\(LogicalName='([^']+)'\)\/Attributes$/.exec(op.path);
+ const t = m && tables.get(m[1]);
+ let failure = null;
+ if (op.method !== 'POST' || !m) failure = reply(400, { error: { message: `unexpected operation ${op.method} ${op.path}` } });
+ else if (!t) failure = reply(404, { error: { message: `no table ${m[1]}` } });
+ else {
+ if (!staged.has(t)) staged.set(t, { columns: new Map(t.columns), reserved: new Set(t.reserved) });
+ const collision = firstTaken(t, [op.body]);
+ if (collision) failure = duplicateAttribute(collision, t.logical);
+ else if (!dropInline.includes(op.body.SchemaName)) addColumn(t, op.body);
+ }
+ if (failure) {
+ for (const [t2, saved] of staged) { t2.columns = saved.columns; t2.reserved = saved.reserved; }
+ refusals.push({ path: p, message: failure.body.error.message });
+ return reply(failure.status, changeSetAnswer([{ contentId: op.contentId, status: failure.status, body: failure.body }]));
+ }
+ }
+ if (batchCommitsThenFails) {
+ const answer = batchCommitsThenFails(operations);
+ refusals.push({ path: p, message: typeof answer.body === 'string' ? answer.body : answer.body && answer.body.error && answer.body.error.message });
+ return answer;
+ }
+ return reply(200, changeSetAnswer(operations.map((op) => ({ contentId: op.contentId, status: 204 }))));
+ };
+ }
+ return { httpClient, log, refusals, tables, attributeReadCount: () => attributeReadCount, lengthReadCount: () => lengthReadCount };
+}
+
+async function realSdk(httpClient, { solutionUniqueName, bundle = BUNDLE } = {}) {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(bundle);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'table-columns-in-create-'));
+ tempDirs.push(dir);
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: ORG, httpClient, ...(solutionUniqueName ? { solutionUniqueName } : {}) });
+ await sdk.initWorkspace();
+ return sdk;
+}
+
+// The two behaviours the platform has been measured to have for the length asked of a primary name column in a create that carries
+// only that column (see DEFAULT_PRIMARY_NAME_LENGTH): one environment keeps it, another makes a plain text column 850 characters
+// long whatever was asked. The stub's default is the second; every default and every length the spec asks for is run under both.
+const HONOURING = { keepsAskedLength: true };
+const OVERRIDING = {};
+
+async function provisionOver(spec, { dataverse = {}, sdkOptions = {}, capture = false, ...options } = {}) {
+ const dv = fakeDataverse(dataverse);
+ const sdk = await realSdk(dv.httpClient, sdkOptions);
+ const events = [];
+ const warnings = [];
+ const runner = makeRunner({ emit: (event) => events.push(event), total: 99 });
+ // `capture` answers a build that stops with what it had done so far, instead of throwing: { error, events, warnings, dv }.
+ let error;
+ const result = await provisionDataModel({
+ sdk, provision: sdk, runner, spec, apply: true, preResolvedLanguageCode: 1033,
+ provisionedLanguages: async () => [1033, 3082], sleep: async () => {}, warn: (m) => warnings.push(m), ...options,
+ }).catch((err) => { if (!capture) throw err; error = err; });
+ return { result, error, events, warnings, dv };
+}
+
+const posts = (run) => run.dv.log.filter((r) => r.method === 'POST');
+const gets = (run) => run.dv.log.filter((r) => r.method === 'GET');
+const puts = (run) => run.dv.log.filter((r) => r.method === 'PUT');
+const columnPosts = (run) => posts(run).filter((r) => /\/Attributes$/.test(r.path));
+const tablePosts = (run) => posts(run).filter((r) => r.path === '/EntityDefinitions');
+// The change sets sent ($batch), and the columns they carry — each operation's body — in the order sent.
+const batchPosts = (run) => posts(run).filter((r) => r.path === '/$batch');
+const batchColumns = (run) => batchPosts(run).flatMap((r) => r.operations.map((o) => o.body));
+const inlineNames = (run) => batchColumns(run).map((a) => a.SchemaName);
+// The typed read of a text column's length, and the narrated "primary column length" steps (run or skipped).
+const lengthReads = (run) => gets(run).filter((r) => /\/Microsoft\.Dynamics\.CRM\.StringAttributeMetadata\?\$select=MaxLength$/.test(r.path));
+const lengthEvents = (run) => run.events.filter((e) => e.status !== 'start' && /^primary column length /.test(e.label));
+
+// --- the spec: every ordinary type and property, plus the columns that must keep the per-column path ---
+
+const ORDINARY = [
+ { schemaName: 'new_title', displayName: { 1033: 'Title', 3082: 'Título' }, type: 'Text', maxLength: 200, required: true, description: 'Short title of the ticket' },
+ { schemaName: 'new_email', displayName: 'Email', type: 'Text', format: 'Email', maxLength: 120 },
+ { schemaName: 'new_notes', displayName: 'Notes', type: 'Memo', maxLength: 4000, description: 'Free text' },
+ { schemaName: 'new_count', displayName: 'Count', type: 'Integer', minValue: 0, maxValue: 99, required: 'recommended' },
+ { schemaName: 'new_minutes', displayName: 'Minutes', type: 'Integer', integerFormat: 'Duration' },
+ { schemaName: 'new_big', displayName: 'Big Number', type: 'BigInt' },
+ { schemaName: 'new_ratio', displayName: 'Ratio', type: 'Decimal', precision: 3, minValue: 0, maxValue: 10 },
+ { schemaName: 'new_score', displayName: 'Score', type: 'Double', precision: 2 },
+ { schemaName: 'new_cost', displayName: 'Cost', type: 'Money', precision: 2, minValue: 0 },
+ { schemaName: 'new_due', displayName: 'Due', type: 'DateTime', dateFormat: 'DateOnly' },
+ { schemaName: 'new_flag', displayName: 'Flag', type: 'Boolean', trueLabel: 'Yes', falseLabel: 'No', defaultValue: false },
+ { schemaName: 'new_priority', displayName: { 1033: 'Priority', 3082: 'Prioridad' }, type: 'Choice', options: ['Low', 'High'] },
+ { schemaName: 'new_tags', displayName: 'Tags', type: 'MultiChoice', options: [{ 1033: 'Alpha', 3082: 'Alfa' }, 'Beta'] },
+ { schemaName: 'new_ticketno', displayName: 'Ticket No', type: 'AutoNumber', autoNumberFormat: 'T-{SEQNUM:5}' },
+ { schemaName: 'new_locked', displayName: 'Locked', type: 'Text', isValidForUpdate: false, isValidForCreate: true, isValidForRead: true },
+];
+const PER_COLUMN = [
+ { schemaName: 'new_account', displayName: 'Account', type: 'Customer' },
+ { schemaName: 'new_attachment', displayName: 'Attachment', type: 'File', maxSizeKb: 1024 },
+ { schemaName: 'new_calc', displayName: 'Calculated', type: 'Integer', source: 'Calculated', formula: '<xml />' },
+];
+
+function ticketSpec(columns = [...ORDINARY, ...PER_COLUMN]) {
+ return {
+ solution: { uniqueName: 'TableColumns', publisherPrefix: 'new' },
+ entities: [
+ {
+ schemaName: 'new_ticket', displayName: { 1033: 'Ticket', 3082: 'Entrada' }, pluralName: { 1033: 'Tickets', 3082: 'Entradas' },
+ description: 'Support tickets', primaryAttribute: { schemaName: 'new_name', displayName: 'Name' }, columns,
+ },
+ {
+ schemaName: 'new_note', displayName: 'Note', primaryAttribute: { schemaName: 'new_notename', displayName: 'Name' },
+ columns: [{ schemaName: 'new_a', type: 'Text' }, { schemaName: 'new_b', type: 'Text' }, { schemaName: 'new_c', type: 'Integer' }],
+ },
+ ],
+ relationships: [],
+ };
+}
+
+// One table with the given columns: the smallest spec that exercises a create.
+function oneTable(columns, primaryAttribute = { schemaName: 'new_name', displayName: 'Name' }) {
+ return {
+ solution: { uniqueName: 'TableColumns', publisherPrefix: 'new' },
+ relationships: [],
+ entities: [{ schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute, columns }],
+ };
+}
+
+test('a new table is created with only its primary name attribute and its ordinary columns follow in ONE change set instead of one request each, with the same results and events', async () => {
+ const before = await provisionOver(ticketSpec(), { inlineColumns: false });
+ const after = await provisionOver(ticketSpec());
+
+ // Requests. Before: a request per column (every ordinary one + file + calculated + the second table's three), and the
+ // Customer action.
+ const perColumnRequests = ORDINARY.length + 2 + 3;
+ assert.strictEqual(tablePosts(before).length, 2);
+ assert.strictEqual(columnPosts(before).length, perColumnRequests, 'one metadata request per column');
+ assert.strictEqual(posts(before).length, 2 + perColumnRequests + 1, 'two tables, the per-column requests, and the Customer action');
+ // After: each table is created by the request it always was — its primary name attribute and nothing else — and its ordinary
+ // columns follow in one change set; only the two that need their own request remain, and the Customer action.
+ assert.deepStrictEqual(tablePosts(after).map((r) => r.body.Attributes.length), [1, 1], 'no table request carries a column');
+ assert.deepStrictEqual(tablePosts(after).map((r) => r.body), tablePosts(before).map((r) => r.body), 'and the table requests are the ones the per-column path sends');
+ assert.deepStrictEqual(batchPosts(after).map((r) => r.operations.length), [ORDINARY.length, 3], 'one change set per table');
+ assert.deepStrictEqual(columnPosts(after).map((r) => r.body.SchemaName), ['new_attachment', 'new_calc'], 'File and Calculated keep the per-column path');
+ assert.strictEqual(posts(after).filter((r) => r.path === '/CreateCustomerRelationships').length, 1, 'Customer keeps its own action');
+ assert.strictEqual(posts(after).length, 2 + 2 + 2 + 1, 'two tables, two change sets, file + calculated, and the Customer action');
+ assert.strictEqual(gets(after).length, gets(before).length + 2, 'plus one read of each new table\'s columns, which also returns their ids');
+
+ // Results and the event stream are what the per-column path produced.
+ assert.deepStrictEqual(after.result, before.result);
+ assert.deepStrictEqual(after.events, before.events);
+ assert.deepStrictEqual(after.warnings, []);
+ assert.deepStrictEqual(after.dv.refusals, [], 'the platform refused nothing');
+ assert.strictEqual(after.result.columns.new_ticket.length, ORDINARY.length + 1 /* customer */ + 2 /* file, calculated */);
+});
+
+test('each column\'s body in the change set equals the body the per-column path posts, to the same URL and with the solution header', async () => {
+ const sdkOptions = { solutionUniqueName: 'TableColumns' };
+ const before = await provisionOver(ticketSpec(), { inlineColumns: false, sdkOptions });
+ const after = await provisionOver(ticketSpec(), { sdkOptions });
+
+ const perColumn = new Map(columnPosts(before).map((r) => [r.body.SchemaName, r]));
+ const [change] = batchPosts(after);
+ const inline = change.operations.map((o) => o.body);
+ assert.deepStrictEqual(inline.map((a) => a.SchemaName), ORDINARY.map((c) => c.schemaName), 'the ordinary columns, in spec order');
+ for (const operation of change.operations) {
+ const own = perColumn.get(operation.body.SchemaName);
+ assert.deepStrictEqual(operation.body, own.body, `${operation.body.SchemaName}: the same attribute JSON as its own request`);
+ assert.strictEqual(operation.method, 'POST');
+ assert.strictEqual(operation.path, own.path, `${operation.body.SchemaName}: to the table's Attributes collection, as its own request`);
+ // The header on the outer `$batch` request is ignored by the platform, so a column of the change set would land outside the
+ // solution without it on each operation.
+ assert.strictEqual(own.headers['MSCRM.SolutionUniqueName'], 'TableColumns', 'the per-column request files the column in the solution');
+ assert.strictEqual(operation.headers['MSCRM.SolutionUniqueName'], 'TableColumns', `${operation.body.SchemaName}: and so does its operation in the change set`);
+ }
+ // The properties a column can carry, present and carried through: localized labels at their LCIDs, required level,
+ // description, type-specific metadata (a text format, a whole-number format, a big integer), choice options,
+ // defaults and the IsValidFor* flags.
+ const byName = new Map(inline.map((a) => [a.SchemaName, a]));
+ assert.deepStrictEqual(byName.get('new_title').DisplayName.LocalizedLabels.map((l) => [l.LanguageCode, l.Label]), [[1033, 'Title'], [3082, 'Título']]);
+ assert.strictEqual(byName.get('new_title').RequiredLevel.Value, 'ApplicationRequired');
+ assert.strictEqual(byName.get('new_title').Description.LocalizedLabels[0].Label, 'Short title of the ticket');
+ assert.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_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');
+ assert.strictEqual(byName.get('new_big')['@odata.type'], 'Microsoft.Dynamics.CRM.BigIntAttributeMetadata');
+ assert.deepStrictEqual(byName.get('new_priority').OptionSet.Options.map((o) => o.Value), [100000000, 100000001]);
+ assert.strictEqual(byName.get('new_tags').OptionSet.Options[0].Label.LocalizedLabels.length, 2, 'a localized option keeps both languages');
+ assert.strictEqual(byName.get('new_flag').DefaultValue, false);
+ assert.strictEqual(byName.get('new_ticketno').AutoNumberFormat, 'T-{SEQNUM:5}');
+ assert.strictEqual(byName.get('new_locked').IsValidForUpdate, false);
+ assert.strictEqual(byName.get('new_locked').IsValidForCreate, true);
+ assert.strictEqual(byName.get('new_locked').IsValidForRead, true);
+ // And the table's own request — the primary name attribute included — is exactly what the per-column path sends.
+ assert.deepStrictEqual(tablePosts(after)[0].body, tablePosts(before)[0].body, 'the table request is the same body with or without a change set after it');
+});
+
+test('only ordinary columns go in the change set — Customer, File, Image, Calculated, Rollup and global-choice columns do not, and no more than 25 do', async () => {
+ const ineligible = [
+ { schemaName: 'new_account', type: 'Customer' }, { schemaName: 'new_file', type: 'File' }, { schemaName: 'new_image', type: 'Image' },
+ { schemaName: 'new_calc', type: 'Integer', source: 'Calculated', formula: '<xml />' }, { schemaName: 'new_roll', type: 'Integer', source: 'Rollup', formula: '<xml />' },
+ ];
+ const created = [];
+ const together = [];
+ const sdk = {
+ createColumns: async (logical, options) => { together.push([logical, options]); },
+ createTable: async (o) => { created.push(o); return { logicalName: o.schemaName.toLowerCase(), entitySetName: 'x', metadataId: tableId(o.schemaName) }; },
+ createColumn: async (l, o) => ({ logicalName: o.schemaName.toLowerCase(), metadataId: attributeId(l, o.schemaName) }),
+ createCustomerColumn: async (l, o) => ({ logicalName: o.schemaName.toLowerCase(), metadataId: '' }),
+ createGlobalOptionSet: async (o) => ({ metadataId: tableId(o.name) }),
+ };
+ const many = Array.from({ length: 30 }, (_, n) => ({ schemaName: `new_t${String(n).padStart(2, '0')}`, type: 'Text' }));
+ const globalBound = { schemaName: 'new_global', type: 'Choice', globalChoice: 'new_shared' };
+ const spec = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, globalChoices: [{ name: 'new_shared', options: ['A'] }], relationships: [], entities: [
+ { schemaName: 'new_t', displayName: 'T', primaryAttribute: { schemaName: 'new_n' }, columns: [...ineligible.slice(0, 3), globalBound, ...many, ...ineligible.slice(3)] },
+ ] };
+ const column = [];
+ sdk.createColumn = async (l, o) => { column.push(o.schemaName); return { logicalName: o.schemaName.toLowerCase(), metadataId: attributeId(l, o.schemaName) }; };
+ const provision = { findTables: async () => [], findColumns: async () => [], dataverse: { get: async (url) => {
+ if (/Attributes\?\$select=MetadataId,LogicalName$/.test(url)) return { status: 200, body: { value: many.slice(0, 25).map((c) => ({ LogicalName: c.schemaName, MetadataId: attributeId('new_t', c.schemaName) })) } };
+ return { status: 404, body: null };
+ } } };
+ await provisionDataModel({ sdk, provision, runner: makeRunner({ emit: () => {}, total: 99 }), spec, apply: true, preResolvedLanguageCode: 1033, sleep: async () => {} });
+ assert.strictEqual(created.length, 1);
+ assert.ok(!('columns' in created[0]), 'the table request carries no column');
+ assert.strictEqual(together.length, 1, 'one change set');
+ assert.strictEqual(together[0][0], 'new_t', 'for the new table');
+ assert.deepStrictEqual(together[0][1].map((c) => c.schemaName), many.slice(0, 25).map((c) => c.schemaName), 'the first 25 ordinary columns, in order');
+ assert.deepStrictEqual(column.sort(), ['new_calc', 'new_file', 'new_global', 'new_image', 'new_roll', ...many.slice(25).map((c) => c.schemaName)].sort(), 'everything else is created by its own request');
+});
+
+test('a table that already exists, an SDK without createColumns, or inlineColumns:false keeps the per-column path untouched', async () => {
+ const spec = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, relationships: [], entities: [
+ { schemaName: 'new_t', displayName: 'T', primaryAttribute: { schemaName: 'new_n' }, columns: [{ schemaName: 'new_a', type: 'Text' }, { schemaName: 'new_b', type: 'Integer' }] },
+ ] };
+ const run = async ({ withCreateColumns, existing = false, inlineColumns }) => {
+ const seen = { createTable: [], createColumn: [], createColumns: [], reads: [] };
+ const sdk = {
+ createTable: async (o) => { seen.createTable.push(o); return { logicalName: 'new_t', entitySetName: 'new_ts', metadataId: tableId('new_t') }; },
+ createColumn: async (l, o) => { seen.createColumn.push(o.schemaName); return { logicalName: o.schemaName.toLowerCase(), metadataId: attributeId(l, o.schemaName) }; },
+ ...(withCreateColumns ? { createColumns: async (l, options) => { seen.createColumns.push(options); } } : {}),
+ };
+ const provision = {
+ findTables: async () => (existing ? [{ logicalName: 'new_t', entitySetName: 'new_ts' }] : []),
+ findColumns: async () => [],
+ dataverse: { get: async (url) => {
+ seen.reads.push(url);
+ if (/\?\$select=LogicalName,EntitySetName$/.test(url)) return existing ? { status: 200, body: { LogicalName: 'new_t', EntitySetName: 'new_ts' } } : { status: 404, body: null };
+ return { status: 200, body: { value: [] } };
+ } },
+ };
+ await provisionDataModel({ sdk, provision, runner: makeRunner({ emit: () => {}, total: 99 }), spec, apply: true, preResolvedLanguageCode: 1033, sleep: async () => {}, inlineColumns });
+ return seen;
+ };
+ for (const [label, options] of [['no createColumns on the SDK', { withCreateColumns: false }], ['inlineColumns:false', { withCreateColumns: true, inlineColumns: false }]]) {
+ const seen = await run(options);
+ assert.ok(!('columns' in seen.createTable[0]), `${label}: createTable carries no columns`);
+ assert.deepStrictEqual(seen.createColumns, [], `${label}: no change set`);
+ assert.deepStrictEqual(seen.createColumn, ['new_a', 'new_b'], `${label}: one createColumn each`);
+ assert.ok(!seen.reads.some((u) => /MetadataId,LogicalName/.test(u)), `${label}: no read of the new columns`);
+ }
+ const existing = await run({ withCreateColumns: true, existing: true });
+ assert.strictEqual(existing.createTable.length, 0);
+ assert.deepStrictEqual(existing.createColumns, [], 'a table that exists is given no change set');
+ assert.deepStrictEqual(existing.createColumn, ['new_a', 'new_b'], 'a table that exists gets its missing columns one by one');
+ assert.ok(!existing.reads.some((u) => /MetadataId,LogicalName/.test(u)));
+});
+
+// --- when the change set cannot be trusted, the per-column path takes over -------------------------------
+
+// A change set the platform refuses is rolled back as a whole, so nothing was created and the build goes on as it always did: one
+// request per column. It costs one refused request and a warning that says why.
+test('a change set the platform refuses creates nothing — the build falls back to one request per column and still completes, with a warning that says why', async () => {
+ const refuse = () => ({ status: 400, headers: {}, body: '{"error":{"code":"0x80048d19","message":"The attribute metadata is not valid for this table"}}' });
+ const before = await provisionOver(ticketSpec(), { inlineColumns: false });
+ const after = await provisionOver(ticketSpec(), { dataverse: { batchFails: refuse } });
+ assert.deepStrictEqual(after.result, before.result, 'the same data model');
+ assert.deepStrictEqual(after.events, before.events, 'and the same steps');
+ assert.deepStrictEqual(tablePosts(after).map((r) => r.body), tablePosts(before).map((r) => r.body), 'the tables are created as ever, once each');
+ assert.strictEqual(batchPosts(after).length, 2, 'one refused change set per table');
+ assert.strictEqual(columnPosts(after).length, columnPosts(before).length, 'the columns were then created one by one');
+ assert.deepStrictEqual(after.dv.tables.get('new_ticket').columns.size, before.dv.tables.get('new_ticket').columns.size);
+ assert.strictEqual(after.warnings.length, 2);
+ assert.match(after.warnings[0], new RegExp(`^could not create the ${ORDINARY.length} ordinary column\\(s\\) of table new_ticket in one request \\(HTTP 400: The attribute metadata is not valid for this table\\) — creating them one by one$`));
+});
+
+// The platform refusing to START a change set (HTTP 429) is not a defect of the request — the table's customization lock is held, or a
+// service protection limit was reached — so the warning says the table was throttled instead of "could not create".
+const TABLE_LOCKED_BODY = '{"error":{"code":"0x80072322","message":"Cannot start the requested operation [Publish] because there is another [EntityCustomization] running at this moment."}}';
+const LOCKED_REASON = 'HTTP 429: Cannot start the requested operation [Publish] because there is another [EntityCustomization] running at this moment.';
+
+test('a change set refused because the table is locked (HTTP 429) falls back to one request per column, each of which retries its own 429s — with a warning that says the table was throttled, not that the request failed', async () => {
+ const locked = () => ({ status: 429, headers: {}, body: TABLE_LOCKED_BODY });
+ const spec = oneTable([{ schemaName: 'new_a', type: 'Text' }, { schemaName: 'new_b', type: 'Text' }]);
+ const before = await provisionOver(spec, { inlineColumns: false });
+ const after = await provisionOver(spec, { dataverse: { batchFails: locked } });
+ assert.strictEqual(batchPosts(after).length, 1, 'a transport that does not retry sends the change set once (the plugin\'s HTTP client sends it again: see below)');
+ assert.deepStrictEqual(after.result, before.result);
+ assert.deepStrictEqual(after.events, before.events);
+ assert.deepStrictEqual(after.warnings, [`table new_ticket was throttled (${LOCKED_REASON}), so its 2 ordinary column(s) are created one by one instead of in one request`]);
+});
+
+test('a 429 reported by the operations inside a change set is the same throttling: the same warning', async () => {
+ // A complete answer that reports every operation of the change set as refused with a 429, under an outer status that is a success.
+ const refusedInside = (operations) => ({ status: 200, headers: {}, body: changeSetAnswer(operations.map((op) => ({ contentId: op.contentId, status: 429, body: JSON.parse(TABLE_LOCKED_BODY) }))) });
+ const run = await provisionOver(oneTable([textColumn('new_a'), textColumn('new_b')]), { dataverse: { batchFails: refusedInside } });
+ assert.deepStrictEqual(run.warnings, [`table new_ticket was throttled (HTTP 429 from ${API}/$batch: atomic write of 2 column(s) on 'new_ticket' was rolled back: the change set reported HTTP 429), so its 2 ordinary column(s) are created one by one instead of in one request`]);
+ assert.ok(run.result.columns.new_ticket.some((c) => c.schemaName === 'new_b'), 'and the columns were created one by one');
+});
+
+test('only a 429 is reported as throttling: any other refusal keeps the "could not create ... in one request" warning', async () => {
+ for (const status of [400, 409, 500, 503]) {
+ const run = await provisionOver(oneTable([textColumn('new_a')]), { dataverse: { batchFails: () => ({ status, headers: {}, body: '{"error":{"message":"refused"}}' }) } });
+ assert.deepStrictEqual(run.warnings, [`could not create the 1 ordinary column(s) of table new_ticket in one request (HTTP ${status}: refused) — creating them one by one`], String(status));
+ }
+});
+
+test('an SDK whose transport cannot send a change set (no postRaw) falls back to one request per column, with a warning that says so — nothing is sent', async () => {
+ const before = await provisionOver(ticketSpec(), { inlineColumns: false });
+ const after = await provisionOver(ticketSpec(), { dataverse: { noPostRaw: true } });
+ assert.deepStrictEqual(batchPosts(after), [], 'no change set was sent');
+ assert.deepStrictEqual(after.result, before.result);
+ assert.deepStrictEqual(after.events, before.events);
+ assert.strictEqual(columnPosts(after).length, columnPosts(before).length);
+ assert.strictEqual(after.warnings.length, 2);
+ assert.match(after.warnings[0], /^could not create the 15 ordinary column\(s\) of table new_ticket in one request \(createColumns writes 15 columns on 'new_ticket' 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\.\) — creating them one by one$/);
+});
+
+// A change set whose answer was lost or could not be read — a transport failure, a server error, or a success status over a body that
+// is not a change-set answer — may have committed. The table is read before anything is assumed: when it has every column the change
+// set committed, and each column is answered as it would have been had the answer arrived — created, with its id — instead of being
+// asked for again and skipped as existing.
+test('a change set that was committed but whose answer was lost or unreadable is recognised by reading the table: every column is narrated as created, with its id, and none is asked for twice', async () => {
+ for (const [what, lost, reason] of [
+ ['an unreadable answer under a success status', () => ({ status: 200, headers: {}, body: 'this is not a batch answer' }), /^HTTP 200 from \S+\/\$batch: atomic write of 15 column\(s\) on 'new_ticket' cannot be confirmed/],
+ ['a server error', () => ({ status: 502, headers: {}, body: null }), /^HTTP 502 from \S+\/\$batch/],
+ ['a transport failure', () => { throw new Error('socket hang up'); }, /^Transport failure reaching \S+\/\$batch: socket hang up$/],
+ ]) {
+ const before = await provisionOver(ticketSpec(), { inlineColumns: false });
+ const after = await provisionOver(ticketSpec(), { dataverse: { batchCommitsThenFails: lost } });
+ assert.strictEqual(batchPosts(after).length, 2, `${what}: each change set was sent once`);
+ assert.deepStrictEqual([...after.dv.tables.get('new_ticket').columns.keys()].sort(), [...before.dv.tables.get('new_ticket').columns.keys()].sort(), `${what}: the table has the very columns the per-column build makes`);
+ assert.deepStrictEqual(after.result, before.result, `${what}: the result is the per-column build's, ids included`);
+ assert.deepStrictEqual(after.events, before.events, `${what}: and so are the steps — created, not skipped as existing`);
+ assert.deepStrictEqual(after.dv.refusals.filter((r) => /already exists/.test(r.message)), [], `${what}: no column was asked for twice`);
+ assert.deepStrictEqual(columnPosts(after).map((r) => r.body.SchemaName), ['new_attachment', 'new_calc'], `${what}: only the columns that take their own request were posted`);
+ assert.strictEqual(after.warnings.length, 2, `${what}: one warning for each change set`);
+ const prefix = 'the answer to the request that creates the 15 ordinary column(s) of table new_ticket was lost or could not be read (';
+ const suffix = '), but the table has every one of them';
+ assert.ok(after.warnings[0].startsWith(prefix) && after.warnings[0].endsWith(suffix), `${what}: ${after.warnings[0]}`);
+ assert.match(after.warnings[0].slice(prefix.length, -suffix.length), reason, `${what}: and the warning says why`);
+ assert.strictEqual(after.dv.attributeReadCount(), 2, `${what}: the table was read once for each change set`);
+ }
+});
+
+// What the read finds decides: nothing, or only part of it, is a refusal and takes the per-column path as it always did.
+test('after a lost answer the per-column path takes over unless the table has EVERY column — a server error that created nothing, a platform that left a column out, a name the platform makes itself', async () => {
+ const unavailable = () => ({ status: 503, headers: {}, body: '{"error":{"message":"The service is unavailable"}}' });
+ const spec = oneTable([textColumn('new_a'), { schemaName: 'new_b', type: 'Integer' }]);
+ const baseline = await provisionOver(spec, { inlineColumns: false });
+ // Nothing was created: the answer was a gateway error that never reached the platform.
+ const refused = await provisionOver(spec, { dataverse: { batchFails: unavailable } });
+ assert.strictEqual(refused.dv.attributeReadCount(), 1, 'the table was read once, with no second attempt');
+ assert.deepStrictEqual(refused.result, baseline.result);
+ assert.deepStrictEqual(refused.events, baseline.events);
+ assert.deepStrictEqual(refused.warnings, ['could not create the 2 ordinary column(s) of table new_ticket in one request (HTTP 503: The service is unavailable) — creating them one by one']);
+ // The platform committed the change set and then did not list one of its columns: the rest are skipped as existing.
+ const partial = await provisionOver(spec, { dataverse: { batchCommitsThenFails: () => ({ status: 502, headers: {}, body: null }), dropInline: ['new_b'] } });
+ assert.deepStrictEqual([...partial.dv.tables.get('new_ticket').columns.keys()].sort(), [...baseline.dv.tables.get('new_ticket').columns.keys()].sort(), 'the table still ends up with both columns');
+ assert.deepStrictEqual(partial.events.filter((e) => e.status === 'skip').map((e) => e.label), ['column new_ticket.new_a (Text) (exists)'], 'the column that is there was not created twice');
+ assert.match(partial.warnings[0], /^could not create the 2 ordinary column\(s\) of table new_ticket in one request \(HTTP 502/);
+ // A column the platform makes itself is there whatever the change set did, so it does not show that the change set committed.
+ const platformMade = oneTable([{ schemaName: 'createdon', displayName: 'Created', type: 'DateTime' }, textColumn('new_a')]);
+ const doomed = await provisionOver(platformMade, { dataverse: { batchFails: unavailable } });
+ const doomedBaseline = await provisionOver(platformMade, { inlineColumns: false });
+ assert.deepStrictEqual(doomed.result, doomedBaseline.result);
+ assert.deepStrictEqual(doomed.events, doomedBaseline.events, 'createdon is a skip, as one by one');
+ assert.match(doomed.warnings[0], /^could not create the 2 ordinary column\(s\)/);
+});
+
+test('only an answer that leaves the outcome unknown is followed by a read of the table: a refusal (any 4xx) and a request the SDK never sent are not', async () => {
+ const spec = oneTable([textColumn('new_a'), textColumn('new_b')]);
+ for (const [what, dataverse, reads] of [
+ ['HTTP 400', { batchFails: () => ({ status: 400, headers: {}, body: '{"error":{"message":"refused"}}' }) }, 0],
+ ['HTTP 409', { batchFails: () => ({ status: 409, headers: {}, body: '{"error":{"message":"refused"}}' }) }, 0],
+ ['HTTP 429', { batchFails: () => ({ status: 429, headers: {}, body: TABLE_LOCKED_BODY }) }, 0],
+ ['no postRaw on the transport (the SDK refuses before sending)', { noPostRaw: true }, 0],
+ ['HTTP 500', { batchFails: () => ({ status: 500, headers: {}, body: '{"error":{"message":"refused"}}' }) }, 1],
+ ['HTTP 503', { batchFails: () => ({ status: 503, headers: {}, body: '{"error":{"message":"refused"}}' }) }, 1],
+ ]) {
+ const run = await provisionOver(spec, { dataverse });
+ assert.strictEqual(run.dv.attributeReadCount(), reads, what);
+ }
+});
+
+// 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) {
+ const { createAzHttpClient } = require('../lib/sdk-http-client.js');
+ const sent = [];
+ const slept = [];
+ const request = async ({ url, method, headers, body }) => {
+ sent.push({ url, method, headers, body });
+ let res;
+ if (method === 'GET') res = await dv.httpClient.get(url);
+ else if (/\/\$batch$/.test(url)) res = await dv.httpClient.postRaw(url, body, { headers });
+ else if (method === 'POST') res = await dv.httpClient.post(url, JSON.parse(body), { headers });
+ else if (method === 'PUT') res = await dv.httpClient.put(url, JSON.parse(body), { headers });
+ 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 });
+ return { httpClient, sent, slept };
+}
+
+test('through the plugin\'s own HTTP client the change set goes out once, as a multipart `$batch`, and the build completes with what the per-column build makes', async () => {
+ const dv = fakeDataverse();
+ const { httpClient, sent } = throughAzHttpClient(dv);
+ assert.strictEqual(typeof httpClient.postRaw, 'function', 'the client can send the body of a change set verbatim');
+ const sdk = await realSdk(httpClient, { solutionUniqueName: 'TableColumns' });
+ assert.strictEqual(sdk.dataverse.supportsAtomicBatch, true, 'so the SDK reports that it can send an atomic change set');
+ const events = [];
+ const warnings = [];
+ const spec = oneTable([textColumn('new_a'), { schemaName: 'new_b', type: 'Integer' }, { schemaName: 'new_file', type: 'File' }]);
+ const result = await provisionDataModel({ sdk, provision: sdk, runner: makeRunner({ emit: (e) => events.push(e), total: 99 }), spec, apply: true, preResolvedLanguageCode: 1033, provisionedLanguages: async () => [1033], sleep: async () => {}, warn: (m) => warnings.push(m) });
+ const batches = sent.filter((s) => /\/\$batch$/.test(s.url));
+ assert.strictEqual(batches.length, 1, 'one change set');
+ assert.strictEqual(batches[0].method, 'POST');
+ assert.match(batches[0].headers['Content-Type'], /^multipart\/mixed;boundary=batch_/, 'announcing the batch boundary, which the SDK chose');
+ assert.strictEqual(typeof batches[0].body, 'string', 'and its body is the multipart text, not JSON');
+ assert.ok(batches[0].headers.Authorization, 'authorized like every other request');
+ assert.deepStrictEqual(parseChangeSet(batches[0].body).map((o) => [o.method, o.path, o.body.SchemaName, o.headers['MSCRM.SolutionUniqueName']]), [
+ ['POST', "/EntityDefinitions(LogicalName='new_ticket')/Attributes", 'new_a', 'TableColumns'],
+ ['POST', "/EntityDefinitions(LogicalName='new_ticket')/Attributes", 'new_b', 'TableColumns'],
+ ]);
+ assert.deepStrictEqual(warnings, []);
+ const baseline = await provisionOver(spec, { inlineColumns: false });
+ assert.deepStrictEqual(result, baseline.result);
+ assert.deepStrictEqual(events, baseline.events);
+});
+
+test('a change set the platform answers with a transient error (503) is sent once — it may have committed behind that answer, so the HTTP client does not send it again — and the build falls back to one request per column', async () => {
+ const dv = fakeDataverse({ batchFails: () => ({ status: 503, headers: {}, body: '{"error":{"message":"The service is unavailable"}}' }) });
+ const { httpClient, sent } = throughAzHttpClient(dv);
+ const sdk = await realSdk(httpClient);
+ const warnings = [];
+ await provisionDataModel({ sdk, provision: sdk, runner: makeRunner({ emit: () => {}, total: 9 }), spec: oneTable([textColumn('new_a'), textColumn('new_b')]), apply: true, preResolvedLanguageCode: 1033, provisionedLanguages: async () => [1033], sleep: async () => {}, warn: (m) => warnings.push(m) });
+ assert.strictEqual(sent.filter((s) => /\/\$batch$/.test(s.url)).length, 1, 'one attempt: a change set that may have committed behind a lost answer is not re-sent');
+ assert.strictEqual(sent.filter((s) => /\/Attributes$/.test(s.url) && s.method === 'POST').length, 2, 'then each column by its own request');
+ assert.match(warnings[0], /^could not create the 2 ordinary column\(s\) of table new_ticket in one request \(HTTP 503: The service is unavailable\) — creating them one by one$/);
+});
+
+// The table was created a moment ago, and its customization lock can still be held when the change set arrives. The platform then
+// refuses to START the change set (HTTP 429), which proves nothing in it ran, so the plugin's HTTP client sends it again — on the
+// schedule of any other throttled write, honouring Retry-After — and the build goes on as if the first send had been accepted.
+test('a change set refused with HTTP 429 (the table is still locked) is sent again by the plugin\'s HTTP client, honouring Retry-After — and the build goes on with it: no per-column request, no warning', async () => {
+ let refused = 0;
+ const dv = fakeDataverse({ batchFails: () => (++refused <= 2 ? { status: 429, headers: { 'retry-after': '3' }, body: TABLE_LOCKED_BODY } : null) });
+ const { httpClient, sent, slept } = throughAzHttpClient(dv);
+ const sdk = await realSdk(httpClient, { solutionUniqueName: 'TableColumns' });
+ const events = [];
+ const warnings = [];
+ const spec = oneTable([textColumn('new_a'), { schemaName: 'new_b', type: 'Integer' }]);
+ const result = await provisionDataModel({ sdk, provision: sdk, runner: makeRunner({ emit: (e) => events.push(e), total: 99 }), spec, apply: true, preResolvedLanguageCode: 1033, provisionedLanguages: async () => [1033], sleep: async () => {}, warn: (m) => warnings.push(m) });
+ const batches = sent.filter((s) => /\/\$batch$/.test(s.url));
+ assert.strictEqual(batches.length, 3, 'refused twice, then accepted');
+ assert.ok(batches.every((b) => b.body === batches[0].body), 'the same change set, byte for byte, each time');
+ assert.deepStrictEqual(slept, [3000, 3000], 'after the wait the platform asked for, which is longer than the backoff');
+ assert.deepStrictEqual(sent.filter((s) => /\/Attributes$/.test(s.url) && s.method === 'POST'), [], 'so no column needed a request of its own');
+ assert.deepStrictEqual(warnings, []);
+ const baseline = await provisionOver(spec, { inlineColumns: false });
+ assert.deepStrictEqual(result, baseline.result, 'with the result the per-column build gives');
+ assert.deepStrictEqual(events, baseline.events, 'and its steps');
+});
+
+test('a table still locked after the HTTP client has spent its attempts: the change set was sent six times, then the columns are created one by one, and the warning says the table was throttled', async () => {
+ const dv = fakeDataverse({ batchFails: () => ({ status: 429, headers: {}, body: TABLE_LOCKED_BODY }) });
+ const { httpClient, sent, slept } = throughAzHttpClient(dv);
+ 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 }), 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, like any other throttled write');
+ assert.deepStrictEqual(slept, [1000, 2000, 4000, 8000, 8000]);
+ assert.strictEqual(sent.filter((s) => /\/Attributes$/.test(s.url) && s.method === 'POST').length, 2, 'then each column 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);
+});
+
+// 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.
+test('a column whose options cannot be built fails in its own step exactly as one by one — the change set is abandoned with a warning, never sent', async () => {
+ const spec = oneTable([textColumn('new_a'), { schemaName: 'new_bad', displayName: 'Bad', type: 'Choice', options: 'not a list' }, textColumn('new_c')]);
+ const baseline = await provisionOver(spec, { inlineColumns: false, capture: true });
+ const run = await provisionOver(spec, { capture: true });
+ assert.ok(baseline.error instanceof BuildHalt, 'one by one, the build stops at that column');
+ assert.ok(run.error instanceof BuildHalt);
+ assert.strictEqual(run.error.message, baseline.error.message, 'with the same message');
+ assert.deepStrictEqual(run.events, baseline.events, 'after the same steps');
+ assert.deepStrictEqual(batchPosts(run), [], 'no change set was sent');
+ assert.match(run.warnings[0], /^could not create the 3 ordinary column\(s\) of table new_ticket in one request \(.*is not a function.*\) — creating them one by one$/);
+});
+
+// Dataverse refuses a change set that would create an attribute twice, as a whole, with 0x80060304. Each way a spec can ask
+// for that is a column that must stay OUT of the change set and take the one-by-one path, where the same collision is
+// one column's own "already exists" — a skip, which is how the build has always treated it.
+
+// What the platform makes of the primary-name collisions, `<table>id` and money twins is modelled by the stub; this runs a spec
+// through both paths and checks the new one asks the platform for nothing it would refuse.
+async function collisionRun(columns, primaryAttribute) {
+ const spec = oneTable(columns, primaryAttribute);
+ const run = await provisionOver(spec);
+ const baseline = await provisionOver(spec, { inlineColumns: false });
+ assert.deepStrictEqual(run.warnings, [], 'no fallback was needed, so nothing is warned');
+ assert.deepStrictEqual(run.dv.refusals.filter((r) => r.path === '/$batch'), [], 'the platform refused no change set');
+ assert.strictEqual(tablePosts(run).length, 1, 'ONE table request, which carries no column');
+ assert.strictEqual(batchPosts(run).length, 1, 'ONE change set, with the columns that can go in it');
+ assert.deepStrictEqual(run.result.columns, baseline.result.columns, 'the same columns, with the same ids, as the one-by-one build');
+ return { run, baseline, inline: inlineNames(run), skipped: run.events.filter((e) => e.status === 'skip').map((e) => e.label) };
+}
+
+test('a column that repeats the primary name column stays out of the change set and is skipped as already existing', async () => {
+ const { inline, skipped, baseline } = await collisionRun([
+ { schemaName: 'new_name', displayName: 'Name again', type: 'Text' },
+ { schemaName: 'new_a', type: 'Text' },
+ ]);
+ assert.deepStrictEqual(inline, ['new_a']);
+ assert.deepStrictEqual(skipped, ['column new_ticket.new_name (Text) (exists)']);
+ assert.deepStrictEqual(baseline.events.filter((e) => e.status === 'skip').map((e) => e.label), skipped, 'the one-by-one build skips it the same way');
+});
+
+test('two columns whose names differ only by case: the first goes in the change set, the second is skipped as already existing', async () => {
+ const { inline, skipped } = await collisionRun([
+ { schemaName: 'new_Code', displayName: 'Code', type: 'Text' },
+ { schemaName: 'new_code', displayName: 'Code (lower case)', type: 'Integer' },
+ { schemaName: 'new_a', type: 'Text' },
+ ]);
+ assert.deepStrictEqual(inline, ['new_Code', 'new_a']);
+ assert.deepStrictEqual(skipped, ['column new_ticket.new_code (Integer) (exists)']);
+});
+
+test('a column named <table>id (the table\'s own key) stays out of the change set and is skipped as already existing', async () => {
+ const { inline, skipped } = await collisionRun([
+ { schemaName: 'new_ticketid', displayName: 'Ticket Id', type: 'Text' },
+ { schemaName: 'new_a', type: 'Text' },
+ ]);
+ assert.deepStrictEqual(inline, ['new_a']);
+ assert.deepStrictEqual(skipped, ['column new_ticket.new_ticketid (Text) (exists)']);
+});
+
+test('a Money column and its <money>_base twin: the twin stays out of the change set and is skipped as already existing when it comes second; when it comes first the twin is kept and the Money column is the skip — as one by one', async () => {
+ for (const [what, columns, inline, skipped] of [
+ ['the Money column first', [{ schemaName: 'new_cost', type: 'Money' }, { schemaName: 'new_cost_base', type: 'Money' }, { schemaName: 'new_a', type: 'Text' }], ['new_cost', 'new_a'], 'column new_ticket.new_cost_base (Money) (exists)'],
+ ['the twin first', [{ schemaName: 'new_cost_base', type: 'Money' }, { schemaName: 'new_cost', type: 'Money' }, { schemaName: 'new_a', type: 'Text' }], ['new_a'], 'column new_ticket.new_cost (Money) (exists)'],
+ ]) {
+ const spec = oneTable(columns);
+ const run = await provisionOver(spec);
+ const baseline = await provisionOver(spec, { inlineColumns: false });
+ assert.deepStrictEqual(run.warnings, [], what);
+ assert.deepStrictEqual(run.dv.refusals.filter((r) => r.path === '/$batch'), [], `${what}: the platform refused no change set`);
+ assert.strictEqual(tablePosts(run).length, 1, what);
+ assert.deepStrictEqual(inlineNames(run), inline, `${what}: the twin is never in the change set, and the owner is not when the twin comes first`);
+ assert.deepStrictEqual(run.events.filter((e) => e.status === 'skip').map((e) => e.label), [skipped], `${what}: the column that comes second is the one skipped`);
+ assert.deepStrictEqual(run.result.columns, baseline.result.columns, `${what}: the same columns, with the same ids, as the one-by-one build`);
+ assert.deepStrictEqual(run.events, baseline.events, `${what}: and the same steps`);
+ }
+});
+
+test('a Money twin is reserved even when its Money column takes the one-by-one path (a Calculated Money column), so that column is not refused for it', async () => {
+ const run = await provisionOver(oneTable([
+ { schemaName: 'new_total', displayName: 'Total', type: 'Money', source: 'Calculated', formula: '<xml />' },
+ { schemaName: 'new_total_base', displayName: 'Total (base)', type: 'Text' },
+ { schemaName: 'new_a', type: 'Text' },
+ ]));
+ assert.deepStrictEqual(run.warnings, []);
+ assert.deepStrictEqual(inlineNames(run), ['new_a'], 'neither the calculated column nor the name its twin will take is in the change set');
+ assert.ok(run.result.columns.new_ticket.some((c) => c.schemaName === 'new_total'), 'the Money column is created by its own request, before anything holds its twin\'s name');
+ assert.deepStrictEqual(run.events.filter((e) => e.status === 'skip').map((e) => e.label), ['column new_ticket.new_total_base (Text) (exists)']);
+});
+
+// A Choice, a MultiChoice and a Boolean column create a `<name>name` shadow beside themselves, as a Money column creates
+// `<name>_base`; a Customer column creates three, a File column one, an Image column three and a rollup column two (see
+// `companions` above). A column of such a name, put in the change set ahead of the one-by-one columns, would leave the owner —
+// created later, and then meeting its own companion's name — refused with "already exists", which the build reads as a skip: the
+// owner would vanish from the table without a word. The first four owners go in the change set themselves; the rest (a
+// global-choice binding, Customer, File, Image, a rollup) are created by their own request, after it.
+const SHADOW_OWNERS = [
+ ['a Choice with options of its own', { schemaName: 'new_category', displayName: 'Category', type: 'Choice', options: ['A', 'B'] }, ['new_categoryname']],
+ ['a Choice bound to a global option set', { schemaName: 'new_category', displayName: 'Category', type: 'Choice', globalChoice: 'new_cat' }, ['new_categoryname']],
+ ['a MultiChoice', { schemaName: 'new_category', displayName: 'Category', type: 'MultiChoice', options: ['A', 'B'] }, ['new_categoryname']],
+ ['a Boolean', { schemaName: 'new_category', displayName: 'Category', type: 'Boolean' }, ['new_categoryname']],
+ ['a Customer', { schemaName: 'new_category', displayName: 'Category', type: 'Customer' }, ['new_categoryname', 'new_categoryyominame', 'new_categoryidtype']],
+ ['a File', { schemaName: 'new_category', displayName: 'Category', type: 'File' }, ['new_category_name']],
+ ['an Image', { schemaName: 'new_category', displayName: 'Category', type: 'Image' }, ['new_categoryid', 'new_category_timestamp', 'new_category_url']],
+ ['a rollup column', { schemaName: 'new_category', displayName: 'Category', type: 'Integer', source: 'Rollup', formula: '<xml />' }, ['new_category_date', 'new_category_state']],
+];
+// The owners that go in the change set themselves.
+const RIDES_IN_REQUEST = (owner) => ['Choice', 'MultiChoice', 'Boolean'].includes(owner.type) && !owner.globalChoice;
+const withGlobalChoice = (spec) => ({ ...spec, globalChoices: [{ name: 'new_cat', options: ['A', 'B'] }] });
+const textColumn = (schemaName) => ({ schemaName, displayName: schemaName, type: 'Text' });
+
+test('a column named like what a Choice, MultiChoice, Boolean, Customer, File, Image or rollup column creates beside itself stays out of the change set — the owner is created, the other column is skipped as already existing', async (t) => {
+ for (const [what, owner, shadows] of SHADOW_OWNERS) {
+ await t.test(what, async () => {
+ const spec = withGlobalChoice(oneTable([owner, ...shadows.map(textColumn), { schemaName: 'new_a', type: 'Text' }]));
+ const run = await provisionOver(spec);
+ const baseline = await provisionOver(spec, { inlineColumns: false });
+ assert.deepStrictEqual(run.dv.refusals.filter((r) => r.path === '/$batch'), [], 'the platform refused no change set');
+ assert.deepStrictEqual(run.warnings, [], 'no fallback was needed');
+ assert.strictEqual(tablePosts(run).length, 1);
+ const inline = inlineNames(run);
+ for (const shadow of shadows) assert.ok(!inline.includes(shadow), `${shadow} is never in the change set`);
+ assert.ok(run.result.columns.new_ticket.some((c) => c.schemaName === 'new_category'), 'the owning column is created');
+ assert.deepStrictEqual(run.result.columns, baseline.result.columns, 'the same columns, with the same ids, as the one-by-one build');
+ assert.deepStrictEqual(run.events, baseline.events, 'and the same steps');
+ assert.deepStrictEqual(run.events.filter((e) => e.status === 'skip').map((e) => e.label), shadows.map((s) => `column new_ticket.${s} (Text) (exists)`));
+ });
+ }
+});
+
+test('a Choice bound to a global option set, then a Text column named like its shadow: the choice is created and the text column is skipped — as one by one', async () => {
+ const spec = withGlobalChoice(oneTable([
+ { schemaName: 'new_category', displayName: 'Category', type: 'Choice', globalChoice: 'new_cat' },
+ { schemaName: 'new_categoryname', displayName: 'Category name', type: 'Text' },
+ ]));
+ const run = await provisionOver(spec);
+ const baseline = await provisionOver(spec, { inlineColumns: false });
+ assert.deepStrictEqual(baseline.result.columns.new_ticket.map((c) => c.schemaName), ['new_category'], 'one by one, the choice is created and the platform\'s own name is a skip');
+ assert.deepStrictEqual(run.result.columns, baseline.result.columns);
+ assert.deepStrictEqual(run.events, baseline.events);
+ assert.deepStrictEqual(run.events.filter((e) => e.status === 'skip').map((e) => e.label), ['column new_ticket.new_categoryname (Text) (exists)']);
+});
+
+// One by one, the first column to name something creates it and the next is skipped as already existing, so where a twin is listed
+// BEFORE the column that makes it as a companion, the twin is kept and the OWNER is the one skipped. The change set runs before
+// every per-column create, so an owner in it would be made first and the twin skipped instead — the other column of the pair gone.
+// An owner stays out of the change set when an earlier column holds one of its companion names, and is made in spec order.
+test('a twin listed BEFORE an owner that goes in the change set keeps the owner out of it: the column listed first is kept, exactly as one by one', async (t) => {
+ for (const [what, owner, shadows] of SHADOW_OWNERS.filter(([, o]) => RIDES_IN_REQUEST(o))) {
+ await t.test(what, async () => {
+ const spec = oneTable([...shadows.map(textColumn), owner, { schemaName: 'new_a', type: 'Text' }]);
+ const run = await provisionOver(spec);
+ const baseline = await provisionOver(spec, { inlineColumns: false });
+ assert.deepStrictEqual(run.dv.refusals.filter((r) => r.path === '/$batch'), [], 'the platform refused no change set');
+ assert.deepStrictEqual(run.warnings, []);
+ assert.deepStrictEqual(inlineNames(run), ['new_a'], 'neither the twin nor its owner is in the change set');
+ assert.deepStrictEqual(run.result.columns.new_ticket.map((c) => c.schemaName), [...shadows, 'new_a'], 'the twin is created; the owner, made after it, finds its shadow taken');
+ assert.deepStrictEqual(run.events.filter((e) => e.status === 'skip').map((e) => e.label), [`column new_ticket.new_category (${owner.type}) (exists)`], 'and is the skip');
+ assert.deepStrictEqual(run.result.columns, baseline.result.columns, 'the same columns, with the same ids, as the one-by-one build');
+ assert.deepStrictEqual(run.events, baseline.events, 'and the same steps');
+ });
+ }
+});
+
+// The same, with the twin a column that has its own request — the shapes where the platform's answer to the owner is a skip.
+test('a File, Image, Customer or Calculated column named like the companion of a Choice, Boolean, MultiChoice or Money column that follows it: the column listed first is kept, as one by one', async (t) => {
+ for (const [what, twin, owner] of [
+ ['a File before a Choice', { schemaName: 'new_categoryname', displayName: 'Category name', type: 'File' }, { schemaName: 'new_category', displayName: 'Category', type: 'Choice', options: ['A', 'B'] }],
+ ['an Image before a Boolean', { schemaName: 'new_flagname', displayName: 'Flag name', type: 'Image' }, { schemaName: 'new_flag', displayName: 'Flag', type: 'Boolean' }],
+ ['a Customer before a MultiChoice', { schemaName: 'new_tagsname', displayName: 'Tags name', type: 'Customer' }, { schemaName: 'new_tags', displayName: 'Tags', type: 'MultiChoice', options: ['A', 'B'] }],
+ ['a Calculated Money before a Money', { schemaName: 'new_cost_base', displayName: 'Cost base', type: 'Money', source: 'Calculated', formula: '<xml />' }, { schemaName: 'new_cost', displayName: 'Cost', type: 'Money' }],
+ ]) {
+ await t.test(what, async () => {
+ const spec = oneTable([twin, owner, textColumn('new_a')]);
+ const run = await provisionOver(spec);
+ const baseline = await provisionOver(spec, { inlineColumns: false });
+ assert.deepStrictEqual(run.dv.refusals.filter((r) => r.path === '/$batch'), [], 'the platform refused no change set');
+ assert.deepStrictEqual(run.warnings, []);
+ assert.deepStrictEqual(inlineNames(run), ['new_a'], 'the owner is not in the change set');
+ assert.deepStrictEqual(run.result.columns.new_ticket.map((c) => c.schemaName), [twin.schemaName, 'new_a'], 'the column listed first is created');
+ assert.deepStrictEqual(run.events.filter((e) => e.status === 'skip').map((e) => e.label), [`column new_ticket.${owner.schemaName} (${owner.type}) (exists)`], 'and the owner is the skip');
+ assert.deepStrictEqual(run.result.columns, baseline.result.columns, 'the same columns, with the same ids, as the one-by-one build');
+ assert.deepStrictEqual(run.events, baseline.events, 'and the same steps');
+ });
+ }
+});
+
+// The platform may make more beside a column than the build lists, and the names are named after the column, so an earlier column
+// whose name EXTENDS a column's name keeps that column out as well — whatever its type. The stub here makes a companion of its own,
+// `<name>_receipt`, beside a column of the type under test, that no list in the build mentions.
+test('a column stays out of the change set when an earlier column is named like something the platform makes beside it that nothing lists — whatever its type', async (t) => {
+ for (const [what, owner, typePattern] of [
+ ['a Money column', { schemaName: 'new_cost', displayName: 'Cost', type: 'Money' }, /MoneyAttributeMetadata$/],
+ ['a DateTime column', { schemaName: 'new_cost', displayName: 'Cost', type: 'DateTime' }, /DateTimeAttributeMetadata$/],
+ ['a Text column', { schemaName: 'new_cost', displayName: 'Cost', type: 'Text' }, /StringAttributeMetadata$/],
+ ]) {
+ await t.test(what, async () => {
+ const unlisted = (body) => (typePattern.test(String(body['@odata.type'])) ? [`${String(body.SchemaName).toLowerCase()}_receipt`] : []);
+ const spec = oneTable([
+ { schemaName: 'new_cost_receipt', displayName: 'Receipt', type: 'File' },
+ owner,
+ textColumn('new_a'),
+ ]);
+ const run = await provisionOver(spec, { dataverse: { extraCompanions: unlisted } });
+ const baseline = await provisionOver(spec, { inlineColumns: false, dataverse: { extraCompanions: unlisted } });
+ assert.deepStrictEqual(run.dv.refusals.filter((r) => r.path === '/$batch'), [], 'the platform refused no change set');
+ assert.deepStrictEqual(run.warnings, []);
+ assert.ok(!inlineNames(run).includes('new_cost'), 'the column is made after the File column listed before it');
+ assert.deepStrictEqual(run.result.columns.new_ticket.map((c) => c.schemaName), ['new_cost_receipt', 'new_a'], 'the File column listed first is kept');
+ assert.deepStrictEqual(run.events.filter((e) => e.status === 'skip').map((e) => e.label), [`column new_ticket.new_cost (${owner.type}) (exists)`]);
+ assert.deepStrictEqual(run.result.columns, baseline.result.columns);
+ assert.deepStrictEqual(run.events, baseline.events);
+ });
+ }
+});
+
+// A column kept out of the change set by that rule is made by its own request like any other owner, so a LATER column whose name
+// extends its own stays out too: made after it, that column finds what the platform made beside the owner and is skipped, as one by
+// one. Here the platform makes `<name>_utc` beside a DateTime column — something nothing in the build lists — and `new_due_long` before
+// `new_due` keeps the DateTime column out, so the `new_due_utc` that follows must stay out too: in the change set it would be created
+// first and the DateTime column, made after it, would be refused as "already existing" and vanish from the table.
+test('a column kept out of the change set because an earlier column extends its name keeps out a LATER column that extends its own — the owner is created, as one by one', async () => {
+ const unlisted = (body) => (/DateTimeAttributeMetadata$/.test(String(body['@odata.type'])) ? [`${String(body.SchemaName).toLowerCase()}_utc`] : []);
+ const spec = oneTable([textColumn('new_due_long'), { schemaName: 'new_due', displayName: 'Due', type: 'DateTime' }, textColumn('new_due_utc')]);
+ const run = await provisionOver(spec, { dataverse: { extraCompanions: unlisted } });
+ const baseline = await provisionOver(spec, { inlineColumns: false, dataverse: { extraCompanions: unlisted } });
+ assert.deepStrictEqual(baseline.result.columns.new_ticket.map((c) => c.schemaName), ['new_due_long', 'new_due'], 'one by one the DateTime column is created and the Text column named like its companion is the skip');
+ assert.deepStrictEqual(inlineNames(run), ['new_due_long'], 'only the first column goes in the change set: it is made before anything that extends its name');
+ assert.deepStrictEqual(run.dv.refusals.filter((r) => r.path === '/$batch'), [], 'the platform refused no change set');
+ assert.deepStrictEqual(run.warnings, []);
+ assert.deepStrictEqual(run.events.filter((e) => e.status === 'skip').map((e) => e.label), ['column new_ticket.new_due_utc (Text) (exists)']);
+ assert.deepStrictEqual(run.result.columns, baseline.result.columns, 'the same columns, with the same ids, as the one-by-one build');
+ assert.deepStrictEqual(run.events, baseline.events, 'and the same steps');
+ assert.deepStrictEqual([...run.dv.tables.get('new_ticket').columns.keys()].sort(), [...baseline.dv.tables.get('new_ticket').columns.keys()].sort());
+});
+
+// The cost of that rule is one request where an earlier column merely starts like a later one's name; the earlier column still goes
+// in the change set, because it is made before the later one either way.
+test('a column named like the start of an earlier column\'s name is made after it, by its own request — one request for it, and the earlier column still goes in the change set', async () => {
+ const spec = oneTable([textColumn('new_title_long'), textColumn('new_title'), { schemaName: 'new_count_total', type: 'Integer' }, { schemaName: 'new_count', type: 'Integer' }, textColumn('new_other')]);
+ const run = await provisionOver(spec);
+ const baseline = await provisionOver(spec, { inlineColumns: false });
+ assert.deepStrictEqual(inlineNames(run), ['new_title_long', 'new_count_total', 'new_other']);
+ assert.deepStrictEqual(columnPosts(run).map((r) => r.body.SchemaName), ['new_title', 'new_count']);
+ assert.deepStrictEqual(run.warnings, []);
+ assert.deepStrictEqual(run.result.columns, baseline.result.columns, 'and the table has every column, with the same ids, as one by one');
+ assert.deepStrictEqual(run.events, baseline.events);
+ // In the usual order, the shorter name first, nothing is kept out.
+ const usual = await provisionOver(oneTable([textColumn('new_title'), textColumn('new_title_long'), { schemaName: 'new_count', type: 'Integer' }, { schemaName: 'new_count_total', type: 'Integer' }]));
+ assert.deepStrictEqual(inlineNames(usual), ['new_title', 'new_title_long', 'new_count', 'new_count_total']);
+});
+
+// A column made by its own request is made AFTER the change set, and where its twin is listed ahead of it the one-by-one
+// build made the twin first and lost the owner. That order is the spec's, and is kept as it was: the twin stays out of the
+// change set, so the build does exactly what it did one column at a time.
+test('a twin listed BEFORE an owner that is created by its own request is made in spec order, exactly as one by one', async (t) => {
+ for (const [what, owner, shadows] of SHADOW_OWNERS.filter(([, o]) => !RIDES_IN_REQUEST(o))) {
+ await t.test(what, async () => {
+ const spec = withGlobalChoice(oneTable([...shadows.map(textColumn), owner, { schemaName: 'new_a', type: 'Text' }]));
+ const run = await provisionOver(spec);
+ const baseline = await provisionOver(spec, { inlineColumns: false });
+ assert.deepStrictEqual(run.dv.refusals.filter((r) => r.path === '/$batch'), [], 'the platform refused no change set');
+ assert.deepStrictEqual(run.warnings, []);
+ assert.deepStrictEqual(inlineNames(run), ['new_a'], 'only the column that cannot be a companion is in the change set');
+ assert.deepStrictEqual(run.result.columns, baseline.result.columns, 'the same columns, with the same ids, as the one-by-one build');
+ assert.deepStrictEqual(run.events, baseline.events, 'and the same steps');
+ });
+ }
+});
+
+// The build does not try to know every column the platform makes beside another: the names it makes are named after the column
+// they extend, so ANY longer name stays out of the change set while its owner is made by its own request. This stub's
+// File column makes a companion of its own, `<name>_receipt`, that no list in the build mentions.
+test('a column whose name extends the name of a column made by its own request stays out of the change set — whatever the platform makes beside that column', async () => {
+ const unlisted = (body) => (/FileAttributeMetadata$/.test(String(body['@odata.type'])) ? [`${String(body.SchemaName).toLowerCase()}_receipt`] : []);
+ const spec = oneTable([
+ { schemaName: 'new_contract', displayName: 'Contract', type: 'File' },
+ textColumn('new_contract_receipt'),
+ textColumn('new_a'),
+ ]);
+ const run = await provisionOver(spec, { dataverse: { extraCompanions: unlisted } });
+ const baseline = await provisionOver(spec, { inlineColumns: false, dataverse: { extraCompanions: unlisted } });
+ assert.deepStrictEqual(run.dv.refusals.filter((r) => r.path === '/$batch'), [], 'the platform refused no change set');
+ assert.deepStrictEqual(run.warnings, []);
+ assert.deepStrictEqual(inlineNames(run), ['new_a']);
+ assert.ok(run.result.columns.new_ticket.some((c) => c.schemaName === 'new_contract'), 'the File column is created');
+ assert.deepStrictEqual(run.result.columns, baseline.result.columns);
+ assert.deepStrictEqual(run.events, baseline.events);
+ assert.deepStrictEqual(run.events.filter((e) => e.status === 'skip').map((e) => e.label), ['column new_ticket.new_contract_receipt (Text) (exists)']);
+});
+
+test('only a LONGER name stays out for it: a column that shares the start of an owner\'s name rides in the change set when its name is the shorter, or does not start with it', async () => {
+ const spec = oneTable([
+ textColumn('new_attach'),
+ { schemaName: 'new_attachment', displayName: 'Attachment', type: 'File' },
+ textColumn('new_other'),
+ textColumn('old_new_attachment'),
+ textColumn('new_attachments'),
+ ]);
+ const run = await provisionOver(spec);
+ const baseline = await provisionOver(spec, { inlineColumns: false });
+ assert.deepStrictEqual(inlineNames(run), ['new_attach', 'new_other', 'old_new_attachment'], 'the shorter name, the unrelated one and one that only contains the owner\'s name go; the extension of the File column\'s name does not');
+ assert.deepStrictEqual(run.warnings, []);
+ assert.deepStrictEqual(run.result.columns, baseline.result.columns, 'and the table has every column, as one by one');
+ assert.deepStrictEqual(run.events, baseline.events);
+});
+
+test('the names compare without regard to case: Dataverse lower-cases logical names, so a twin in any case spelling stays out', async () => {
+ const spec = oneTable([
+ { schemaName: 'New_Contract', displayName: 'Contract', type: 'File' },
+ textColumn('NEW_CONTRACT_NAME'),
+ textColumn('new_a'),
+ ]);
+ const run = await provisionOver(spec);
+ const baseline = await provisionOver(spec, { inlineColumns: false });
+ assert.deepStrictEqual(run.dv.refusals.filter((r) => r.path === '/$batch'), [], 'the platform refused no change set');
+ assert.deepStrictEqual(inlineNames(run), ['new_a']);
+ assert.ok(run.result.columns.new_ticket.some((c) => c.schemaName === 'New_Contract'), 'the File column is created');
+ assert.deepStrictEqual(run.result.columns, baseline.result.columns);
+ assert.deepStrictEqual(run.events, baseline.events);
+});
+
+// The change set — and every read and write that follows the table's create — addresses the table by its LOGICAL name: the lower-case
+// form Dataverse keeps of the schema name the spec spells. A table whose schema name has capitals is where the two differ.
+test('a table whose schema name has capitals is addressed by its lower-case logical name: the change set, the reads and the name column\'s length', async () => {
+ const spec = {
+ solution: { uniqueName: 'TableColumns', publisherPrefix: 'new' },
+ relationships: [],
+ entities: [{ schemaName: 'new_Ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_Name', displayName: 'Name', maxLength: 120 }, columns: [textColumn('new_a'), { schemaName: 'new_B', type: 'Integer' }] }],
+ };
+ const run = await provisionOver(spec);
+ const baseline = await provisionOver(spec, { inlineColumns: false });
+ assert.deepStrictEqual(run.warnings, []);
+ assert.deepStrictEqual(batchPosts(run).map((r) => r.operations.map((o) => o.path)), [["/EntityDefinitions(LogicalName='new_ticket')/Attributes", "/EntityDefinitions(LogicalName='new_ticket')/Attributes"]], 'the change set targets new_ticket');
+ assert.deepStrictEqual(inlineNames(run), ['new_a', 'new_B'], 'with the columns as the spec spells them');
+ assert.strictEqual(run.dv.tables.get('new_ticket').primaryLength, 120, 'the length was read and set by logical names too');
+ assert.deepStrictEqual(lengthEvents(run).map((e) => [e.status, e.label]), [['ok', 'primary column length new_Ticket.new_Name -> 120']]);
+ assert.deepStrictEqual(run.result, baseline.result);
+ assert.deepStrictEqual(run.events, baseline.events);
+});
+
+// The rules that decide which columns may go in the change set are a list of cases; this holds the build to the one-request-per-column
+// build's answer over specs that mix every kind of column and every kind of name collision — a companion's name, an extension of a
+// name, a repeat in another case — in any order: the table, its columns, their ids and the steps narrated must be the same whichever
+// way the columns were made. A change set the platform refuses is accepted only where the stub makes a companion the build cannot
+// know (`extraCompanions`), and the fallback then still gives that answer.
+test('generated specs: the table, its columns, their ids and the steps are those of the per-column build, whatever the order and the names', async () => {
+ let state = 20260501;
+ const random = () => { state = (Math.imul(state, 1664525) + 1013904223) >>> 0; return state / 2 ** 32; };
+ const pick = (list) => list[Math.floor(random() * list.length)];
+ const STEMS = ['new_a', 'new_b', 'new_cat'];
+ const SUFFIXES = ['', '', '', 'name', '_base', '_name', 'id', '_url', '_timestamp', 'yominame', 'idtype', '_date', '_state', '_x', 'NAME', '2'];
+ const TYPES = [
+ { type: 'Text' }, { type: 'Text' }, { type: 'Integer' }, { type: 'Memo' }, { type: 'Money' }, { type: 'Choice', options: ['A'] }, { type: 'Boolean' },
+ { type: 'MultiChoice', options: ['A'] }, { type: 'DateTime' }, { type: 'File' }, { type: 'Image' }, { type: 'Customer' },
+ { type: 'Integer', source: 'Calculated', formula: '<xml />' }, { type: 'Integer', source: 'Rollup', formula: '<xml />' },
+ { type: 'Money', source: 'Calculated', formula: '<xml />' }, { type: 'Choice', globalChoice: 'new_gc' },
+ ];
+ // Beside a column of these types the stub's platform also makes `<name>_utc` or `<name>_x`, which nothing in the build lists.
+ const UNLISTED = [undefined, undefined, [/MoneyAttributeMetadata$/, '_utc'], [/DateTimeAttributeMetadata$/, '_utc'], [/StringAttributeMetadata$/, '_x']];
+ let withChangeSet = 0;
+ for (let n = 0; n < 60; n += 1) {
+ const columns = Array.from({ length: 2 + Math.floor(random() * 7) }, (_, i) => ({ ...pick(TYPES), schemaName: `${pick(STEMS)}${pick(SUFFIXES)}`, displayName: `c${i}` }));
+ const unlisted = pick(UNLISTED);
+ const dataverse = unlisted ? { extraCompanions: (body) => (unlisted[0].test(String(body['@odata.type'])) ? [`${String(body.SchemaName).toLowerCase()}${unlisted[1]}`] : []) } : {};
+ const spec = { ...oneTable(columns), globalChoices: [{ name: 'new_gc', options: ['A', 'B'] }] };
+ const label = `${unlisted ? `(platform also makes <name>${unlisted[1]} for ${unlisted[0]}) ` : ''}${columns.map((c) => `${c.schemaName}:${c.type}${c.source ? `:${c.source}` : ''}${c.globalChoice ? ':global' : ''}`).join(' ')}`;
+ const baseline = await provisionOver(clone(spec), { inlineColumns: false, dataverse });
+ const run = await provisionOver(clone(spec), { dataverse });
+ assert.deepStrictEqual(run.result.columns, baseline.result.columns, label);
+ assert.deepStrictEqual(run.events, baseline.events, label);
+ assert.deepStrictEqual([...run.dv.tables.get('new_ticket').columns.keys()].sort(), [...baseline.dv.tables.get('new_ticket').columns.keys()].sort(), label);
+ if (!unlisted) assert.deepStrictEqual(run.dv.refusals.filter((r) => r.path === '/$batch'), [], `${label}: the platform refused a change set the build could have foreseen`);
+ if (batchPosts(run).length) withChangeSet += 1;
+ }
+ assert.ok(withChangeSet > 30, `most generated specs (${withChangeSet} of 60) have columns that go in a change set`);
+});
+
+test('a collision the change set could not foresee (a column named like a column the platform makes) is refused as a whole — the build falls back to one request per column, completes, and warns with the platform\'s own reason', async () => {
+ const columns = [{ schemaName: 'createdon', displayName: 'Created', type: 'DateTime' }, { schemaName: 'new_a', type: 'Text' }];
+ const spec = oneTable(columns);
+ const run = await provisionOver(spec);
+ const baseline = await provisionOver(spec, { inlineColumns: false });
+ assert.strictEqual(tablePosts(run).length, 1, 'the table is created once, as ever');
+ assert.strictEqual(batchPosts(run).length, 1, 'and the change set was sent once');
+ const refusals = run.dv.refusals.filter((r) => r.path === '/$batch');
+ assert.strictEqual(refusals.length, 1);
+ assert.match(refusals[0].message, /^Attribute createdon already exists for entity new_ticket\.$/, 'the documented 0x80060304 answer');
+ assert.strictEqual(run.dv.tables.get('new_ticket').columns.size, baseline.dv.tables.get('new_ticket').columns.size, 'and it created nothing: the refused change set was rolled back as a whole');
+ assert.strictEqual(run.warnings.length, 1);
+ assert.strictEqual(run.warnings[0], 'could not create the 2 ordinary column(s) of table new_ticket in one request (HTTP 400: Attribute createdon already exists for entity new_ticket.) — creating them one by one');
+ assert.deepStrictEqual(run.result.columns, baseline.result.columns, 'then each column was created one by one — the platform\'s own `createdon` is a skip');
+ assert.deepStrictEqual(run.events.filter((e) => e.status === 'skip').map((e) => e.label), ['column new_ticket.createdon (DateTime) (exists)']);
+ assert.deepStrictEqual(run.events, baseline.events);
+});
+
+// --- a table that WAS created is never created again -------------------------------------------------
+
+// The table is created exactly as it was, so what a failure of that create (or of the read the SDK makes of the new table
+// afterwards) does is what it always did: the build stops. The re-run that follows finds the table and creates its columns.
+test('a table created whose read-back then fails stops the build as it always did — no column is created — and the re-run completes the table one column at a time', async () => {
+ const unreadable = () => ({ status: 500, headers: {}, body: { error: { message: 'An unexpected error occurred.' } } });
+ const dv = fakeDataverse({ tableReadBack: unreadable });
+ const sdk = await realSdk(dv.httpClient);
+ const events = [];
+ const base = { sdk, provision: sdk, spec: oneTable([{ schemaName: 'new_a', type: 'Text' }, { schemaName: 'new_b', type: 'Integer' }]), apply: true, preResolvedLanguageCode: 1033, provisionedLanguages: async () => [1033], sleep: async () => {}, warn: () => {} };
+ await assert.rejects(provisionDataModel({ ...base, runner: makeRunner({ emit: (e) => events.push(e), total: 9 }) }), (err) => err instanceof BuildHalt && err.recoverable === true && /HTTP 500/.test(err.message));
+ assert.strictEqual(dv.log.filter((r) => r.method === 'POST').length, 1, 'the table was created once, and nothing else was sent');
+ // The read-back works again.
+ const healthy = fakeDataverse();
+ healthy.tables.set('new_ticket', dv.tables.get('new_ticket'));
+ const rerunSdk = await realSdk(healthy.httpClient);
+ const rerun = [];
+ await provisionDataModel({ ...base, sdk: rerunSdk, provision: rerunSdk, runner: makeRunner({ emit: (e) => rerun.push(e), total: 9 }) });
+ assert.strictEqual(healthy.log.filter((r) => r.method === 'POST' && r.path === '/EntityDefinitions').length, 0, 'the table is not created again');
+ assert.strictEqual(healthy.log.filter((r) => r.method === 'POST' && r.path === '/$batch').length, 0, 'and a table that exists is given no change set');
+ assert.deepStrictEqual(rerun.filter((e) => e.status === 'ok').map((e) => e.label), ['column new_ticket.new_a (Text)', 'column new_ticket.new_b (Integer)'], 'its columns are created one by one');
+ assert.deepStrictEqual(rerun.filter((e) => e.status === 'skip').map((e) => e.label), ['table new_ticket (exists — reuse)']);
+});
+
+// The answer to the table's create can be lost although the table was made. The build then FINDS the table, as it always did,
+// and — since nothing shows what the table holds, or that this build made it — gives it no change set: each column is created by
+// its own request, where one that is already there is a skip.
+test('a lost answer to the table\'s create (the table exists afterwards) is recovered as ever: no change set, each column created one by one, and no warning about columns created together', async () => {
+ const lost = () => ({ status: 400, headers: {}, body: { error: { message: 'Entities already exist: new_ticket' } } });
+ const baseline = await provisionOver(ticketSpec(), { inlineColumns: false, dataverse: { createCommitsThenFails: lost } });
+ const run = await provisionOver(ticketSpec(), { dataverse: { createCommitsThenFails: lost } });
+ assert.strictEqual(tablePosts(run).length, 2, 'one create per table, as ever');
+ assert.deepStrictEqual(batchPosts(run), [], 'a table found after its create is given no change set');
+ assert.deepStrictEqual(run.dv.log.filter((r) => /Attributes\?\$select=MetadataId,LogicalName/.test(r.path)), [], 'and its columns are not read back: none was created together');
+ assert.strictEqual(columnPosts(run).length, columnPosts(baseline).length, 'every column is created by its own request');
+ assert.deepStrictEqual(run.result, baseline.result);
+ assert.deepStrictEqual(run.events, baseline.events);
+ assert.deepStrictEqual(run.warnings, [], 'and nothing says that columns were created with the table');
+});
+
+test('TABLE_METADATA_NOT_VISIBLE (the table was created but cannot be read yet) is never answered with a second create', async () => {
+ const { creates, warnings, error } = await notVisibleRun(oneTable([{ schemaName: 'new_a', type: 'Text' }]));
+ assert.ok(error instanceof BuildHalt && /TABLE_METADATA_NOT_VISIBLE|WAS CREATED/.test(error.message) && error.recoverable === true);
+ assert.strictEqual(creates.length, 1, 'the create is not repeated, whatever columns the spec has');
+ assert.ok(!('columns' in creates[0]), 'and carries none');
+ assert.deepStrictEqual(warnings, [], 'and with no length asked there is nothing more to say');
+});
+
+// The SDK's TABLE_METADATA_NOT_VISIBLE says the table WAS created and could not be read back, so the build stops. A table created with
+// only its name column can come out with a name column of 850 characters whatever length the spec asks for, on some environments, and
+// a re-run leaves an existing table's name column as it is — so the build says so before it stops.
+async function notVisibleRun(spec) {
+ const creates = [];
+ const warnings = [];
+ const notVisible = Object.assign(new Error('Table WAS CREATED but its metadata was still not readable. Do NOT re-run the create'), { code: 'TABLE_METADATA_NOT_VISIBLE' });
+ const sdk = {
+ createColumns: async () => { throw new Error('no change set is sent for a table that could not be read'); },
+ createTable: async (o) => { creates.push(o); throw notVisible; },
+ createColumn: async () => { throw new Error('no column is created for a table that could not be read'); },
+ };
+ const provision = { findTables: async () => [], findColumns: async () => [], dataverse: { get: async () => ({ status: 404, body: null }) } };
+ const error = await provisionDataModel({ sdk, provision, runner: makeRunner({ emit: () => {}, total: 9 }), spec, apply: true, preResolvedLanguageCode: 1033, sleep: async () => {}, warn: (m) => warnings.push(m) })
+ .then(() => null, (err) => err);
+ return { creates, warnings, error };
+}
+
+test('TABLE_METADATA_NOT_VISIBLE out of the create, with a length asked, says the length may not have been applied on some environments — and the build still stops, once', async () => {
+ const { creates, warnings, error } = await notVisibleRun(oneTable([], asksFor(120)));
+ assert.ok(error instanceof BuildHalt && error.recoverable === true && /WAS CREATED/.test(error.message), 'the halt is the one it always was');
+ assert.strictEqual(creates.length, 1);
+ assert.strictEqual(warnings.length, 1);
+ assert.strictEqual(warnings[0], 'table new_ticket was created, but its metadata could not be read back yet, so the build stops here — the spec asks for a primary name column length of 120, which may not have been applied (some environments make a name column created this way 850 characters long), and a re-run leaves an existing table\'s name column as it is: after the re-run, check new_name in Maker and set its length there if it matters');
+ // Whatever columns the spec has, the table is created alone, so the warning is the same.
+ const withColumns = await notVisibleRun(oneTable([{ schemaName: 'new_a', type: 'Text' }], asksFor(120)));
+ assert.strictEqual(withColumns.creates.length, 1);
+ assert.deepStrictEqual(withColumns.warnings, warnings);
+ // Asking for the default length is asking: 100 is not what some environments make of it.
+ const hundred = await notVisibleRun(oneTable([], asksFor(100)));
+ assert.match(hundred.warnings[0], /length of 100, which may not have been applied/);
+});
+
+test('TABLE_METADATA_NOT_VISIBLE out of a create whose name column is auto-numbered, whose spec asks for no length, or whose length is the longest there is, makes no length warning', async () => {
+ const numbered = await notVisibleRun(oneTable([], asksFor(120, { autoNumberFormat: 'WO-{SEQNUM:5}' })));
+ assert.deepStrictEqual(numbered.warnings, [], 'the platform keeps the length asked of an auto-numbered name column');
+ const none = await notVisibleRun(oneTable([], { schemaName: 'new_name', displayName: 'Name' }));
+ assert.deepStrictEqual(none.warnings, []);
+ const longest = await notVisibleRun(oneTable([], asksFor(850)));
+ assert.deepStrictEqual(longest.warnings, [], 'a name column of 850 characters is what it comes out as either way');
+ assert.ok(longest.error instanceof BuildHalt, 'the build still stops');
+});
+
+// The order of a new table's steps is the previous release's — the table, quick create, then the columns: the ordinary ones together
+// in one change set, then those that take their own request, one by one in spec order. The name column's length, which the previous
+// release never set, is the one step added to that order, and it comes LAST, after every labelled create of the phase (see the
+// next tests).
+//
+// These order tests use doubles that record every write in order; they care what comes before what, not what is on the wire.
+function orderDoubles({ failOn, existing = [] } = {}) {
+ const calls = [];
+ // Records a write, then refuses it when the test says so: the call was made, and failed.
+ const record = (label) => { calls.push(label); if (failOn && failOn(label)) throw new Error(`refused: ${label}`); };
+ const sdk = {
+ createTable: async (o) => { record(`createTable ${o.schemaName}`); return { logicalName: o.schemaName.toLowerCase(), entitySetName: 'x', metadataId: tableId(o.schemaName) }; },
+ updateTable: async (l, o) => { record(`updateTable ${l} ${JSON.stringify(o)}`); },
+ updateColumn: async (l, c, o) => { record(`updateColumn ${l}.${c} ${JSON.stringify(o)}`); },
+ createColumns: async (l, options) => { record(`createColumns ${l} ${options.map((c) => c.schemaName).join(',')}`); },
+ createColumn: async (l, o) => { record(`createColumn ${l}.${o.schemaName}`); return { logicalName: o.schemaName.toLowerCase(), metadataId: attributeId(l, o.schemaName) }; },
+ createCustomerColumn: async (l, o) => { record(`createCustomerColumn ${l}.${o.schemaName}`); return { logicalName: o.schemaName.toLowerCase(), metadataId: '' }; },
+ insertStatusValue: async (l, o) => { record(`insertStatusValue ${l}: ${o.label}`); return o.value; },
+ createAlternateKey: async (l, o) => { record(`createAlternateKey ${l}.${o.schemaName}`); },
+ createRelationship: async (o) => { record(`createRelationship ${o.schemaName}`); return { schemaName: o.schemaName, metadataId: tableId(o.schemaName), lookupLogicalName: String(o.lookupSchemaName).toLowerCase() }; },
+ };
+ const provision = { findTables: async () => [], findColumns: async () => [], dataverse: { get: async (url) => {
+ // The environment that ignores the length asked of a one-attribute create: every name column reads 850.
+ if (/StringAttributeMetadata\?\$select=MaxLength$/.test(url)) return { status: 200, body: { MaxLength: 850 } };
+ if (/Attributes\?\$select=MetadataId,LogicalName$/.test(url)) return { status: 200, body: { value: ['new_x', 'new_y'].map((n) => ({ LogicalName: n, MetadataId: attributeId('new_t', n) })) } };
+ if (/Attributes\?\$select=LogicalName,RequiredLevel$/.test(url)) return { status: 200, body: { value: [] } };
+ if (/Relationships\?\$select=/.test(url)) return { status: 200, body: { value: [] } };
+ const table = /EntityDefinitions\(LogicalName='([^']+)'\)\?\$select=LogicalName,EntitySetName$/.exec(url);
+ if (table && existing.includes(table[1])) return { status: 200, body: { LogicalName: table[1], EntitySetName: `${table[1]}s` } };
+ return { status: 404, body: null };
+ } } };
+ return { calls, sdk, provision };
+}
+const runOrder = (doubles, spec, events = []) => provisionDataModel({
+ sdk: doubles.sdk, provision: doubles.provision, runner: makeRunner({ emit: (e) => events.push(e), total: 99 }), spec, apply: true, preResolvedLanguageCode: 1033,
+ provisionedLanguages: async () => [1033, 3082], sleep: async () => {}, warn: (m) => events.push({ warning: m }),
+});
+
+test('a new table\'s steps keep the previous release\'s order — table, quick create, the change set, then the columns that take their own request — and the name column length is set last', async () => {
+ const { calls, sdk, provision } = orderDoubles();
+ const spec = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, relationships: [], entities: [
+ { schemaName: 'new_t', displayName: 'T', quickCreate: true, primaryAttribute: { schemaName: 'new_n', maxLength: 120 }, columns: [{ schemaName: 'new_owner', type: 'Customer' }, textColumn('new_x'), { schemaName: 'new_file', type: 'File' }, { schemaName: 'new_y', type: 'Integer' }] },
+ ] };
+ await runOrder({ calls, sdk, provision }, spec);
+ assert.deepStrictEqual(calls, [
+ 'createTable new_t',
+ 'updateTable new_t {"quickCreateEnabled":true}',
+ 'createColumns new_t new_x,new_y',
+ 'createCustomerColumn new_t.new_owner',
+ 'createColumn new_t.new_file',
+ 'updateColumn new_t.new_n {"maxLength":120}',
+ ]);
+});
+
+// The length is set through the SDK's updateColumn, which starts by reading the column WITH its labels — and a label-bearing metadata
+// read ahead of a labelled create is what makes Dataverse keep only the base-language label of what is created (measured live; see
+// findExistingColumns). That read cannot be narrowed, so it goes where nothing labelled is created after it: once every table,
+// column, status reason, alternate key and relationship of the phase exists, for every table the build created.
+const TWO_TABLES_AND_A_RELATIONSHIP = () => ({
+ solution: { uniqueName: 'S', publisherPrefix: 'new' },
+ entities: [
+ { schemaName: 'new_a', displayName: { 1033: 'A', 3082: 'A' }, pluralName: { 1033: 'As', 3082: 'As' }, quickCreate: true, primaryAttribute: { schemaName: 'new_n', maxLength: 120 }, columns: [textColumn('new_x'), { schemaName: 'new_file', type: 'File' }], statusReasons: [{ label: 'On hold', state: 'Active' }], alternateKeys: [{ schemaName: 'new_a_key', columns: ['new_x'] }] },
+ { schemaName: 'new_b', displayName: 'B', primaryAttribute: { schemaName: 'new_m', maxLength: 90 }, columns: [textColumn('new_y')] },
+ { schemaName: 'new_c', displayName: 'C', primaryAttribute: { schemaName: 'new_o' }, columns: [] },
+ ],
+ relationships: [{ type: 'OneToMany', referenced: 'new_a', referencing: 'new_b', schemaName: 'new_a_b', lookup: { schemaName: 'new_aid', displayName: { 1033: 'A', 3082: 'A' } } }],
+});
+
+test('the name column length of each table the build created is set after the LAST labelled create of the phase — every table, column, status reason, alternate key and relationship — in table order', async () => {
+ const { calls, sdk, provision } = orderDoubles();
+ await runOrder({ calls, sdk, provision }, TWO_TABLES_AND_A_RELATIONSHIP());
+ assert.deepStrictEqual(calls, [
+ 'createTable new_a',
+ 'updateTable new_a {"quickCreateEnabled":true}',
+ 'createColumns new_a new_x',
+ 'createColumn new_a.new_file',
+ 'insertStatusValue new_a: On hold',
+ 'createAlternateKey new_a.new_a_key',
+ 'createTable new_b',
+ 'createColumns new_b new_y',
+ 'createTable new_c',
+ 'createRelationship new_a_b',
+ 'updateColumn new_a.new_n {"maxLength":120}',
+ 'updateColumn new_b.new_m {"maxLength":90}',
+ ], 'the last step is the name column lengths; none is set for a table whose spec gives no length');
+});
+
+test('the length steps are narrated after the relationships, one for each table that asks for a length, and [n/total] ends on the last of them', async () => {
+ const { calls, sdk, provision } = orderDoubles();
+ const events = [];
+ const spec = TWO_TABLES_AND_A_RELATIONSHIP();
+ await runOrder({ calls, sdk, provision }, spec, events);
+ const done = events.filter((e) => e.status && e.status !== 'start');
+ assert.deepStrictEqual(done.slice(-3).map((e) => [e.status, e.label]), [
+ ['ok', 'relationship 1:N new_a->new_b'],
+ ['ok', 'primary column length new_a.new_n -> 120'],
+ ['ok', 'primary column length new_b.new_m -> 90'],
+ ]);
+ const { planFor } = require('../lib/sdk-build.js');
+ const planned = planFor(spec, { phases: ['data-model'] }).map((item) => item.label);
+ assert.deepStrictEqual(planned.slice(-3), ['relationship 1:N new_a->new_b', 'primary column length new_a.new_n', 'primary column length new_b.new_m'], 'and the plan lists them where they are narrated');
+});
+
+// Two things end the data-model phase of the app build: the repair of a lookup column's default label (opt-in, `reconcileLookupLabels`), which is
+// labelled work and so belongs to the steps, and the name column lengths, which come after the last labelled write of all, in the phase's `finally`.
+// The plan lists them in the order the run takes them, so the counter the runner shows ends on its total instead of passing it.
+test('the lookup label steps come before the name column length steps, in the run and in the plan, and [n/total] ends on the last length step', async () => {
+ const { sdk, provision } = orderDoubles();
+ const spec = TWO_TABLES_AND_A_RELATIONSHIP();
+ // No `lookup.displayName`: the build owns this lookup's label, so it has a label step of its own.
+ spec.relationships = [{ type: 'OneToMany', referenced: 'new_a', referencing: 'new_b', schemaName: 'new_a_b', lookup: { schemaName: 'new_aid' } }];
+ const { planFor } = require('../lib/sdk-build.js');
+ const planned = planFor(spec, { phases: ['data-model'] }).map((item) => item.label);
+ const kinds = (labels) => labels.map((label) => (/^relationship /.test(label) ? 'relationship' : /^lookup label /.test(label) ? 'lookup label' : /^primary column length /.test(label) ? 'length' : 'other'))
+ .filter((kind) => kind !== 'other');
+ const events = [];
+ await provisionDataModel({
+ sdk, provision, runner: makeRunner({ emit: (e) => events.push(e), total: planned.length }), spec, apply: true, preResolvedLanguageCode: 1033,
+ provisionedLanguages: async () => [1033, 3082], sleep: async () => {}, warn: (m) => events.push({ warning: m }), reconcileLookupLabels: true,
+ });
+ const done = events.filter((e) => e.status && e.status !== 'start');
+ assert.deepStrictEqual(kinds(planned), ['relationship', 'lookup label', 'length', 'length'], 'the plan');
+ assert.deepStrictEqual(kinds(done.map((e) => e.label)), ['relationship', 'lookup label', 'length', 'length'], `the run: ${JSON.stringify(done.map((e) => e.label))}`);
+ assert.strictEqual(done.length, planned.length, 'the run narrates exactly the steps the plan lists');
+ assert.strictEqual(done[done.length - 1].n, planned.length, '[n/total] ends on the last step');
+ assert.ok(done.every((e) => e.n <= planned.length));
+});
+
+// A re-run finds the table and never touches an existing table's name column, so a table created by a run that halted would keep the
+// length the environment made of its create for good. The lengths are therefore set in a `finally`, for the tables created before the
+// halt, and the halt is the error the caller sees.
+const FIRST_TABLE_CALLS = ['createTable new_a', 'updateTable new_a {"quickCreateEnabled":true}', 'createColumns new_a new_x', 'createColumn new_a.new_file', 'insertStatusValue new_a: On hold', 'createAlternateKey new_a.new_a_key'];
+const SET_FIRST_LENGTH = 'updateColumn new_a.new_n {"maxLength":120}';
+const SET_SECOND_LENGTH = 'updateColumn new_b.new_m {"maxLength":90}';
+
+test('a phase that halts after creating tables still sets the name column lengths of the tables it created, and the halt is the error that is thrown', async (t) => {
+ for (const [what, failOn, existing, expected] of [
+ // The change set is refused too, so the second table's column is created by its own request, which fails.
+ ['a column of the second table is refused', (call) => /^createColumns? new_b[ .]new_y$/.test(call), [], [
+ ...FIRST_TABLE_CALLS, 'createTable new_b', 'createColumns new_b new_y', 'createColumn new_b.new_y', SET_FIRST_LENGTH, SET_SECOND_LENGTH,
+ ]],
+ ['a relationship is refused', (call) => call === 'createRelationship new_a_b', [], [
+ ...FIRST_TABLE_CALLS, 'createTable new_b', 'createColumns new_b new_y', 'createTable new_c', 'createRelationship new_a_b', SET_FIRST_LENGTH, SET_SECOND_LENGTH,
+ ]],
+ ['the second table cannot be created: only the first one was', (call) => call === 'createTable new_b', [], [
+ ...FIRST_TABLE_CALLS, 'createTable new_b', SET_FIRST_LENGTH,
+ ]],
+ // A table that existed before is never set, a halt or not: only the table this run created is.
+ ['the first table already existed, and a column of the second is refused', (call) => /^createColumns? new_b[ .]new_y$/.test(call), ['new_a'], [
+ 'updateTable new_a {"quickCreateEnabled":true}', 'createColumn new_a.new_x', 'createColumn new_a.new_file', 'insertStatusValue new_a: On hold', 'createAlternateKey new_a.new_a_key',
+ 'createTable new_b', 'createColumns new_b new_y', 'createColumn new_b.new_y', SET_SECOND_LENGTH,
+ ]],
+ ]) {
+ await t.test(what, async () => {
+ const doubles = orderDoubles({ failOn, existing });
+ const events = [];
+ await assert.rejects(runOrder(doubles, TWO_TABLES_AND_A_RELATIONSHIP(), events), (err) => err instanceof BuildHalt && /^data-model failed: refused: /.test(err.message), 'the error that is thrown is the one that stopped the phase');
+ assert.deepStrictEqual(doubles.calls, expected);
+ const failed = events.filter((e) => e.status === 'error');
+ assert.strictEqual(failed.length, 1, 'the one failed step is the one that stopped the phase');
+ assert.ok(events.indexOf(failed[0]) < events.findIndex((e) => e.status === 'ok' && /^primary column length /.test(e.label)), 'and the length steps follow it');
+ assert.deepStrictEqual(events.filter((e) => e.warning && /primary name column/.test(e.warning)), [], 'with nothing said about the lengths: they were set');
+ });
+ }
+});
+
+test('a length that cannot be set while the phase is halting is a failed, warned step of its own — and never replaces the error that stopped the phase', async () => {
+ const doubles = orderDoubles({ failOn: (call) => call === 'createRelationship new_a_b' || call === SET_FIRST_LENGTH });
+ const events = [];
+ await assert.rejects(runOrder(doubles, TWO_TABLES_AND_A_RELATIONSHIP(), events), (err) => err instanceof BuildHalt && /^data-model failed: refused: createRelationship new_a_b$/.test(err.message));
+ assert.deepStrictEqual(doubles.calls.slice(-2), [SET_FIRST_LENGTH, SET_SECOND_LENGTH], 'the second table is still set after the first one failed');
+ assert.deepStrictEqual(events.filter((e) => e.status === 'error').map((e) => e.label), ['relationship 1:N new_a->new_b', 'primary column length new_a.new_n -> 120']);
+ const warnings = events.filter((e) => e.warning).map((e) => e.warning);
+ assert.strictEqual(warnings.length, 1, 'and the failed length is warned about');
+ assert.match(warnings[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: asked 120, the platform made 850: refused: updateColumn new_a\.new_n /, 'the warning does not promise that the build goes on: the phase stopped, and a run that finds the table there will not set the length');
+});
+
+// The build runs a phase that halts on a transient answer (a 429, a lock, a 503) again, against the same environment (build-model-app.js). The length is set at the end of
+// the phase, in its `finally`, for a table THAT ATTEMPT created — so the attempt that created a table has set its length even though it halted, and the retry, which finds the
+// table, keeps its name column as it finds it: one halt, one set. "Nothing labelled is created after the read that sets it" is therefore a claim about one attempt: the retry
+// creates what the halt kept the first attempt from, after that attempt's read (alignPrimaryNameLength). This is run through the build's own retry loop.
+test('after a transient halt that follows a sized table\'s create, the length is set exactly once — by the attempt that created the table — and the retry, which finds the table, does not set it again', async () => {
+ const { buildModelApp } = require('../build-model-app.js');
+ const spec = {
+ app: { name: 'Ticket Desk' },
+ solution: { uniqueName: 'TableColumns', publisherPrefix: 'new' },
+ relationships: [],
+ entities: [{
+ schemaName: 'new_ticket', displayName: 'Ticket', primaryAttribute: { schemaName: 'new_name', displayName: 'Name', maxLength: 120 },
+ columns: [textColumn('new_title'), { schemaName: 'new_attachment', displayName: 'Attachment', type: 'File', maxSizeKb: 1024 }],
+ }],
+ };
+ const dv = fakeDataverse(OVERRIDING); // the environment that makes the name column 850 whatever length the create asks for
+ // The File column's own request is answered 503 once: what a lock that outlasts the HTTP client's attempts looks like to the phase.
+ const post = dv.httpClient.post;
+ let refused = false;
+ dv.httpClient.post = async (url, body, options) => {
+ if (!refused && /\/Attributes$/.test(String(url)) && body && body.SchemaName === 'new_attachment') {
+ refused = true;
+ dv.log.push({ method: 'POST', path: `(503) ${String(url).replace(API, '')}`, body });
+ return { status: 503, headers: {}, body: { error: { message: 'Service Unavailable' } } };
+ }
+ return post(url, body, options);
+ };
+ const sdk = await realSdk(dv.httpClient);
+ const attempts = [];
+ const events = [];
+ const runBuild = async (builtSpec, options) => {
+ const attempt = { number: attempts.length + 1, from: dv.log.length };
+ attempts.push(attempt);
+ try {
+ await provisionDataModel({
+ sdk: options.sdk, provision: options.provisionSdk, runner: makeRunner({ emit: (e) => events.push({ attempt: attempt.number, ...e }), total: 99 }), spec: builtSpec, apply: true,
+ preResolvedLanguageCode: 1033, provisionedLanguages: async () => [1033, 3082], sleep: async () => {}, warn: () => {},
+ });
+ } finally {
+ attempt.to = dv.log.length;
+ }
+ return { ok: true, created: {} };
+ };
+ const journal = [];
+ const result = await buildModelApp(spec, { apply: true, env: ORG, retryDelayMs: 0 }, {
+ sdk,
+ provisionSdk: sdk,
+ runBuild,
+ journal: { path: 'x', record: (e) => journal.push(e), close: () => {} },
+ discoverOpDiffState: async () => ({ collision: { appExists: false, solutionExists: false }, forms: [], sitemap: null }),
+ });
+ assert.strictEqual(result.ok, true, 'the retry completed the build');
+ assert.strictEqual(journal.filter((e) => e.status === 'retry').length, 1, 'one transient halt, one retry');
+ assert.strictEqual(attempts.length, 2);
+
+ const requests = (attempt) => dv.log.slice(attempt.from, attempt.to);
+ const isLengthWrite = (r) => r.method === 'PUT' && /\/Attributes\(/.test(r.path);
+ assert.strictEqual(requests(attempts[0]).filter(isLengthWrite).length, 1, 'the attempt that created the table set the length of its name column, in its finally, after the halt');
+ assert.strictEqual(requests(attempts[1]).filter(isLengthWrite).length, 0, 'the retry found the table and wrote nothing to its name column');
+ assert.strictEqual(requests(attempts[1]).filter((r) => /StringAttributeMetadata/.test(r.path)).length, 0, 'nor read it');
+ assert.strictEqual(dv.tables.get('new_ticket').primaryLength, 120, 'and the column has the length the spec asks for');
+ const steps = (n) => events.filter((e) => e.attempt === n && e.status !== 'start' && /^primary column length /.test(e.label)).map((e) => `${e.status} ${e.label}`);
+ assert.deepStrictEqual(steps(1), ['ok primary column length new_ticket.new_name -> 120']);
+ assert.deepStrictEqual(steps(2), ['skip primary column length new_ticket.new_name (table exists — kept)']);
+
+ // What the claim leaves out, and why it is made for one attempt: the retry creates the column the halt kept the first attempt from, AFTER that attempt's label-bearing read.
+ const labelBearingRead = dv.log.findIndex((r) => r.method === 'GET' && /\/Attributes\([0-9a-f-]{36}\)\/Microsoft\.Dynamics\.CRM\.StringAttributeMetadata$/.test(r.path));
+ assert.ok(labelBearingRead >= attempts[0].from && labelBearingRead < attempts[0].to, 'the label-bearing read is the first attempt\'s');
+ assert.ok(dv.log.slice(labelBearingRead + 1).some((r) => r.method === 'POST' && r.body && r.body.SchemaName === 'new_attachment' && !/^\(503\)/.test(r.path)), 'and the retry still creates a column after it');
+});
+
+test('when the new columns cannot be read back, every one is created the per-column way (already-exists answers are skips) and the build says so', async () => {
+ const unreadable = () => ({ status: 503, headers: {}, body: null });
+ const run = await provisionOver(ticketSpec(), { dataverse: { attributeReads: unreadable } });
+ assert.strictEqual(run.dv.attributeReadCount(), 6, 'three attempts per table');
+ assert.strictEqual(columnPosts(run).filter((r) => r.body.SchemaName === 'new_title').length, 1, 'the column is asked for once more, one at a time');
+ assert.strictEqual(run.events.filter((e) => e.status === 'skip' && /^column \w+\.\w+ \(.*\) \(exists\)$/.test(e.label)).length, ORDINARY.length + 3, 'every column of the change set is a skip: the platform already has it');
+ assert.strictEqual(run.warnings.filter((w) => /could be read back/.test(w)).length, 2);
+ assert.strictEqual(run.warnings[0], `${ORDINARY.length} column(s) were created in one request, but 0 could be read back — creating the other ${ORDINARY.length} one by one`);
+});
+
+test('a column list that lags the create is read again; one the platform silently left out is created by its own request', async () => {
+ const lagging = (n, rows) => (n === 1 ? { status: 200, headers: {}, body: { value: rows.slice(0, 2) } } : undefined);
+ const lagged = await provisionOver(ticketSpec(), { dataverse: { attributeReads: lagging } });
+ const baseline = await provisionOver(ticketSpec(), { inlineColumns: false });
+ assert.deepStrictEqual(lagged.result, baseline.result);
+ assert.strictEqual(columnPosts(lagged).filter((r) => r.path.includes("'new_ticket'")).length, 2, 'the second read showed every column: only file and calculated by request');
+ assert.deepStrictEqual(lagged.warnings, []);
+
+ const dropped = await provisionOver(ticketSpec(), { dataverse: { dropInline: ['new_flag'] } });
+ assert.deepStrictEqual(dropped.result, baseline.result, 'the left-out column is created and captured like any other');
+ assert.ok(columnPosts(dropped).some((r) => r.body.SchemaName === 'new_flag'), 'created by its own request');
+ assert.match(dropped.warnings.join('\n'), new RegExp(`${ORDINARY.length} column\\(s\\) were created in one request, but ${ORDINARY.length - 1} could be read back`));
+});
+
+// A confirmation belongs to the column that went in the change set, never to another column that shares its name: one by one a second
+// column of the same name is skipped as already existing, and the narration and the result must say the same. A spec can name a
+// column twice (validation accepts it); the first one goes in the change set and the second, a repeat, takes the per-column path.
+test('a second column with exactly the name of one in the change set is skipped as already existing, and is never given the first one\'s id — whatever its type', async (t) => {
+ for (const [what, second] of [
+ ['an Integer', { schemaName: 'new_doc', displayName: 'Doc (number)', type: 'Integer' }],
+ ['a File', { schemaName: 'new_doc', displayName: 'Doc (file)', type: 'File' }],
+ ['a Customer', { schemaName: 'new_doc', displayName: 'Doc (customer)', type: 'Customer' }],
+ ]) {
+ await t.test(`a Text column, then ${what} of the same name`, async () => {
+ const spec = oneTable([{ schemaName: 'new_doc', displayName: 'Doc', type: 'Text' }, second, textColumn('new_a')]);
+ const run = await provisionOver(spec);
+ const baseline = await provisionOver(spec, { inlineColumns: false });
+ assert.deepStrictEqual(inlineNames(run), ['new_doc', 'new_a'], 'only the first goes in the change set');
+ assert.deepStrictEqual(run.warnings, []);
+ assert.deepStrictEqual(run.events.filter((e) => e.status === 'skip').map((e) => e.label), [`column new_ticket.new_doc (${second.type}) (exists)`], 'the second is skipped — it was not created, so it is not narrated as created');
+ assert.deepStrictEqual(run.events.filter((e) => e.status === 'ok' && /new_doc/.test(e.label)).map((e) => e.label), ['column new_ticket.new_doc (Text)']);
+ assert.deepStrictEqual(run.result.columns.new_ticket.map((c) => c.schemaName), ['new_doc', 'new_a'], 'and the column is listed once, with the first one\'s id');
+ assert.deepStrictEqual(run.result.columns, baseline.result.columns, 'the same columns, with the same ids, as the one-by-one build');
+ assert.deepStrictEqual(run.events, baseline.events, 'and the same steps');
+ });
+ }
+});
+
+// --- the primary name column ---------------------------------------------------------------------------
+
+// The primary name attribute exactly as the table request posts it — the request the previous release sent. Its MaxLength is the
+// one property the platform answers differently on different environments (see DEFAULT_PRIMARY_NAME_LENGTH): a table created with
+// only this attribute came back with 850 characters although 100 was asked for on one environment, and with 100 on another. The
+// previous release always asked for 100, so a spec that gives no length asks for 100 — written out here, whatever the SDK's own
+// default becomes.
+const primaryNameBody = (maxLength) => ({
+ '@odata.type': 'Microsoft.Dynamics.CRM.StringAttributeMetadata',
+ AttributeType: 'String',
+ AttributeTypeName: { Value: 'StringType' },
+ SchemaName: 'new_name',
+ RequiredLevel: { Value: 'None', CanBeChanged: true, ManagedPropertyLogicalName: 'canmodifyrequirementlevelsettings' },
+ MaxLength: maxLength,
+ FormatName: { Value: 'Text' },
+ DisplayName: { '@odata.type': 'Microsoft.Dynamics.CRM.Label', LocalizedLabels: [{ '@odata.type': 'Microsoft.Dynamics.CRM.LocalizedLabel', Label: 'Name', LanguageCode: 1033 }] },
+ IsPrimaryName: true,
+});
+
+// The table request the previous release posts for `oneTable([...])`, recorded from its code: its own SDK's `createTable`, which it
+// called without a length for the name column and so got the SDK's default, 100. Written out in full, key order included, so that
+// nothing in it is derived from the code under test; the A/B test below runs the previous release itself wherever one is at hand.
+const RELEASED_TABLE_REQUEST = {
+ '@odata.type': 'Microsoft.Dynamics.CRM.EntityMetadata',
+ SchemaName: 'new_ticket',
+ DisplayName: { '@odata.type': 'Microsoft.Dynamics.CRM.Label', LocalizedLabels: [{ '@odata.type': 'Microsoft.Dynamics.CRM.LocalizedLabel', Label: 'Ticket', LanguageCode: 1033 }] },
+ DisplayCollectionName: { '@odata.type': 'Microsoft.Dynamics.CRM.Label', LocalizedLabels: [{ '@odata.type': 'Microsoft.Dynamics.CRM.LocalizedLabel', Label: 'Tickets', LanguageCode: 1033 }] },
+ OwnershipType: 'UserOwned',
+ IsActivity: false,
+ HasActivities: false,
+ HasNotes: false,
+ Attributes: [{
+ '@odata.type': 'Microsoft.Dynamics.CRM.StringAttributeMetadata',
+ AttributeType: 'String',
+ AttributeTypeName: { Value: 'StringType' },
+ SchemaName: 'new_name',
+ RequiredLevel: { Value: 'None', CanBeChanged: true, ManagedPropertyLogicalName: 'canmodifyrequirementlevelsettings' },
+ MaxLength: 100,
+ FormatName: { Value: 'Text' },
+ DisplayName: { '@odata.type': 'Microsoft.Dynamics.CRM.Label', LocalizedLabels: [{ '@odata.type': 'Microsoft.Dynamics.CRM.LocalizedLabel', Label: 'Name', LanguageCode: 1033 }] },
+ IsPrimaryName: true,
+ }],
+};
+
+test('a spec that gives no primary name length posts the previous release\'s table request, byte for byte — with columns or without, on either behaviour of the platform', async () => {
+ for (const [model, dataverse] of [['an environment that keeps the length asked', HONOURING], ['an environment that ignores it for a table created alone', OVERRIDING]]) {
+ for (const [what, columns] of [
+ ['no columns', []],
+ ['ordinary columns', [textColumn('new_a'), { schemaName: 'new_b', type: 'Memo' }]],
+ ['only columns that take their own request', [{ schemaName: 'new_owner', type: 'Customer' }]],
+ ]) {
+ const run = await provisionOver(oneTable(columns), { dataverse });
+ assert.strictEqual(tablePosts(run).length, 1, `${model}, ${what}`);
+ assert.strictEqual(JSON.stringify(tablePosts(run)[0].body), JSON.stringify(RELEASED_TABLE_REQUEST), `${model}, ${what}: the same bytes`);
+ }
+ }
+ // For a table with no columns the whole conversation is the previous release's: its probe, its create and the read of the new
+ // table, and nothing more.
+ const plain = await provisionOver(oneTable([]));
+ assert.deepStrictEqual(plain.dv.log.map(requestLine), [
+ "GET /EntityDefinitions(LogicalName='new_ticket')?$select=LogicalName,EntitySetName",
+ 'POST /EntityDefinitions',
+ `GET /EntityDefinitions(${tableId('new_ticket')})?$select=LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute`,
+ ]);
+});
+
+// The previous release is the oracle for "what was sent": its own code and its own SDK bundle, run over the same stub. It lives
+// outside this repository, so this runs where MODEL_APPS_RELEASED_SCRIPTS names the `scripts` directory of a checkout of it, and is
+// skipped elsewhere (the recorded request above stands in for it there).
+const RELEASED_SCRIPTS = process.env.MODEL_APPS_RELEASED_SCRIPTS;
+const SKIP_A_B = 'set MODEL_APPS_RELEASED_SCRIPTS to the scripts directory of the previous release to compare with it';
+
+async function releasedRun(spec, dataverse) {
+ const released = require(path.join(RELEASED_SCRIPTS, 'lib', 'entity-provision.js'));
+ const dv = fakeDataverse(dataverse);
+ const sdk = await realSdk(dv.httpClient, { bundle: path.join(RELEASED_SCRIPTS, 'vendor', 'cds-maker-sdk.cjs') });
+ const events = [];
+ const warnings = [];
+ const result = await released.provisionDataModel({
+ sdk, provision: sdk, runner: released.makeRunner({ emit: (event) => events.push(event), total: 99 }), spec: clone(spec), apply: true, preResolvedLanguageCode: 1033,
+ provisionedLanguages: async () => [1033, 3082], sleep: async () => {}, warn: (m) => warnings.push(m),
+ });
+ return { result, events, warnings, dv };
+}
+
+test('A/B with the previous release: the table request and every column body a spec gets are what the released code posts, and the table ends up the same, on either behaviour of the platform', { skip: !RELEASED_SCRIPTS && SKIP_A_B }, async () => {
+ const localized = {
+ solution: { uniqueName: 'TableColumns', publisherPrefix: 'new' },
+ relationships: [],
+ entities: [{
+ schemaName: 'new_ticket', displayName: { 1033: 'Ticket', 3082: 'Entrada' }, pluralName: { 1033: 'Tickets', 3082: 'Entradas' }, description: 'Support tickets', hasNotes: true,
+ primaryAttribute: { schemaName: 'new_name', displayName: { 1033: 'Name', 3082: 'Nombre' } }, columns: [textColumn('new_a')],
+ }],
+ };
+ const numbered = { schemaName: 'new_name', displayName: 'Name', autoNumberFormat: 'WO-{SEQNUM:5}' };
+ const specs = [
+ ['a table with no columns', oneTable([])],
+ ['a table with ordinary columns of every type and the columns that take their own request', ticketSpec()],
+ ['an auto-numbered name column, with and without columns', oneTable([textColumn('new_a'), { schemaName: 'new_b', type: 'Integer' }], numbered)],
+ ['an auto-numbered name column and no columns', oneTable([], numbered)],
+ ['a localized table with a description and notes', localized],
+ ];
+ const bodiesBySchemaName = (run) => new Map([
+ ...columnPosts(run).map((r) => [r.body.SchemaName, JSON.stringify(r.body)]),
+ ...batchColumns(run).map((body) => [body.SchemaName, JSON.stringify(body)]),
+ ]);
+ for (const [what, spec] of specs) {
+ for (const [model, dataverse] of [['honouring', HONOURING], ['overriding', OVERRIDING]]) {
+ const old = await releasedRun(spec, dataverse);
+ const now = await provisionOver(clone(spec), { dataverse });
+ const label = `${what}, ${model}`;
+ assert.deepStrictEqual(tablePosts(now).map((r) => JSON.stringify(r.body)), tablePosts(old).map((r) => JSON.stringify(r.body)), `${label}: the table requests are the same bytes`);
+ assert.deepStrictEqual([...bodiesBySchemaName(now)].sort(), [...bodiesBySchemaName(old)].sort(), `${label}: every column is the same body, whether the released code posted it by itself or this build put it in the change set`);
+ assert.deepStrictEqual(posts(now).filter((r) => r.path === '/CreateCustomerRelationships').map((r) => JSON.stringify(r.body)), posts(old).filter((r) => r.path === '/CreateCustomerRelationships').map((r) => JSON.stringify(r.body)), `${label}: the Customer actions`);
+ // `lookupLabels` is the one field of the result that is new since the previous release: the label each lookup column carries once the data model is done, which a later phase repairs forms from.
+ const { lookupLabels, ...nowResult } = now.result;
+ assert.ok(lookupLabels && typeof lookupLabels === 'object', `${label}: the result carries the lookup labels`);
+ assert.deepStrictEqual(nowResult, old.result, `${label}: the same result`);
+ assert.deepStrictEqual(now.events, old.events, `${label}: the same steps`);
+ assert.deepStrictEqual(now.warnings, old.warnings, `${label}: and no warning the released code did not give`);
+ for (const [name, table] of old.dv.tables) {
+ assert.strictEqual(now.dv.tables.get(name).primaryLength, table.primaryLength, `${label}: ${name}'s name column ends up the length the released code gave it`);
+ assert.deepStrictEqual([...now.dv.tables.get(name).columns.keys()].sort(), [...table.columns.keys()].sort(), `${label}: ${name} has the same columns`);
+ }
+ if (!spec.entities[0].columns.length) assert.deepStrictEqual(now.dv.log, old.dv.log, `${label}: for a table with no columns, every request is the released code's`);
+ }
+ }
+});
+
+// What the platform makes of a primary name column's length is one of two things (see DEFAULT_PRIMARY_NAME_LENGTH), and the build
+// reaches a table by one of several routes; the length asked of the create, and what the column ends up as, are checked on every
+// route under both. `asked` is the spec's length (undefined: none).
+const lostCreateAnswer = () => ({ status: 400, headers: {}, body: { error: { message: 'Entities already exist: new_ticket' } } });
+const refusedChangeSet = () => ({ status: 400, headers: {}, body: '{"error":{"message":"refused"}}' });
+const CREATE_ROUTES = [
+ ['a table with no columns', [], {}, { aligned: true, changeSets: 0 }],
+ ['a table whose ordinary columns follow in one change set', [textColumn('new_a'), { schemaName: 'new_b', type: 'Integer' }], {}, { aligned: true, changeSets: 1 }],
+ ['a table whose only columns take their own request', [{ schemaName: 'new_owner', type: 'Customer' }], {}, { aligned: true, changeSets: 0 }],
+ ['a table whose change set the platform refuses, then one request per column', [textColumn('new_a')], { batchFails: refusedChangeSet }, { aligned: true, changeSets: 1 }],
+ ['a table found after the answer to its create was lost', [textColumn('new_a')], { createCommitsThenFails: lostCreateAnswer }, { aligned: false, changeSets: 0 }],
+];
+
+test('every route that creates a table asks the previous release\'s length for the name column — 100 unless the spec gives one — and ends with it where the environment keeps it, and with what the previous release got where it does not', async (t) => {
+ for (const [route, columns, faults, { aligned, changeSets }] of CREATE_ROUTES) {
+ for (const [model, behaviour, keeps] of [['honouring', HONOURING, true], ['overriding', OVERRIDING, false]]) {
+ for (const [kind, numbering] of [['a plain name column', {}], ['an auto-numbered name column', { autoNumberFormat: 'WO-{SEQNUM:5}' }]]) {
+ for (const asked of [undefined, 120]) {
+ await t.test(`${route}; ${model} environment; ${kind}; ${asked === undefined ? 'no length given' : `length ${asked}`}`, async () => {
+ const primaryAttribute = { schemaName: 'new_name', displayName: 'Name', ...numbering, ...(asked === undefined ? {} : { maxLength: asked }) };
+ const run = await provisionOver(oneTable(columns, primaryAttribute), { dataverse: { ...behaviour, ...faults } });
+ // The request: the previous release's — one attribute, asking for the length the spec gave or else 100.
+ assert.strictEqual(tablePosts(run).length, 1);
+ assert.deepStrictEqual(tablePosts(run)[0].body.Attributes, [{ ...primaryNameBody(asked === undefined ? 100 : asked), ...(numbering.autoNumberFormat ? { AutoNumberFormat: numbering.autoNumberFormat } : {}) }]);
+ assert.strictEqual(batchPosts(run).length, changeSets, 'and the change sets this route sends');
+ // What the column ends up as. An environment that ignores the length asked of a plain name column made 850 of it; the
+ // build then sets the length the spec gave (where it made the table), and leaves a default alone — as the previous release did.
+ const table = run.dv.tables.get('new_ticket');
+ const keptByPlatform = keeps || Boolean(numbering.autoNumberFormat);
+ const wanted = asked === undefined ? 100 : asked;
+ const expectedLength = keptByPlatform ? wanted : (asked !== undefined && aligned ? asked : 850);
+ assert.strictEqual(table.primaryLength, expectedLength, 'the length the name column ends up as');
+ if (asked === undefined) {
+ assert.deepStrictEqual(lengthReads(run), [], 'a default is not read back');
+ assert.deepStrictEqual(puts(run), [], 'or set');
+ assert.deepStrictEqual(lengthEvents(run), [], 'and has no step');
+ } else {
+ assert.strictEqual(lengthReads(run).length, 1, 'a length the spec gave is read back once');
+ assert.strictEqual(puts(run).length, keptByPlatform || !aligned ? 0 : 1, 'and set only where the environment did not keep it, on a table this build made');
+ assert.strictEqual(lengthEvents(run).length, 1, 'with one narrated step');
+ }
+ });
+ }
+ }
+ }
+ }
+});
+
+test('primaryAttribute.maxLength is the length the table request asks for, whatever columns follow', async () => {
+ const primaryAttribute = { schemaName: 'new_name', displayName: 'Name', maxLength: 120 };
+ const withColumns = await provisionOver(oneTable([{ schemaName: 'new_a', type: 'Text' }], primaryAttribute));
+ const plain = await provisionOver(oneTable([], primaryAttribute));
+ assert.deepStrictEqual(tablePosts(withColumns)[0].body.Attributes, [primaryNameBody(120)]);
+ assert.deepStrictEqual(tablePosts(plain)[0].body.Attributes, [primaryNameBody(120)]);
+ for (const length of [1, 850]) {
+ const run = await provisionOver(oneTable([], { ...primaryAttribute, maxLength: length }));
+ assert.strictEqual(tablePosts(run)[0].body.Attributes[0].MaxLength, length);
+ }
+});
+
+test('a rebuild never changes the length of a primary name column that already exists, whatever primaryAttribute.maxLength says', async () => {
+ // The table is built with the default 100-character name column; the spec then asks for 120. A rebuild that converged the
+ // length would have to write it (a PUT of the column), and might shorten a column that holds data — so it writes nothing,
+ // and reads nothing either: there is nothing to compare.
+ const columns = [{ schemaName: 'new_a', type: 'Text' }];
+ const dv = fakeDataverse(HONOURING);
+ const sdk = await realSdk(dv.httpClient);
+ const make = (events) => makeRunner({ emit: (event) => events.push(event), total: 99 });
+ const options = { sdk, provision: sdk, apply: true, preResolvedLanguageCode: 1033, provisionedLanguages: async () => [1033], sleep: async () => {}, warn: () => {} };
+ await provisionDataModel({ ...options, runner: make([]), spec: oneTable(columns) });
+ assert.strictEqual(tablePosts({ dv })[0].body.Attributes[0].MaxLength, 100);
+ const afterFirst = dv.log.length;
+ const events = [];
+ // A table or column create would be a POST, and the update of the column a PUT.
+ await provisionDataModel({ ...options, runner: make(events), spec: oneTable(columns, { schemaName: 'new_name', displayName: 'Name', maxLength: 120 }) });
+ const rebuild = dv.log.slice(afterFirst);
+ assert.strictEqual(rebuild.filter((r) => r.method !== 'GET').length, 0, 'the rebuild writes nothing: no table, column or length is touched');
+ assert.ok(!rebuild.some((r) => /\/Attributes\(/.test(r.path)), 'and it does not read the column either: nothing is compared with the spec\'s length');
+ assert.deepStrictEqual(
+ events.filter((e) => e.status !== 'start' && /^primary column length /.test(e.label)).map((e) => [e.status, e.label]),
+ [['skip', 'primary column length new_ticket.new_name (table exists — kept)']],
+ 'one narrated step, a skip that says why',
+ );
+ assert.strictEqual(dv.tables.get('new_ticket').primaryLength, 100, 'the column keeps its length');
+});
+
+// --- the length the spec asks for -------------------------------------------------------------------------------
+// The table is created with a request that carries nothing but its primary name attribute, and some environments ignore the length
+// asked of a plain text name column in such a request (see DEFAULT_PRIMARY_NAME_LENGTH). So for a table THIS build creates, the
+// length a spec gives is read back — one typed request — and updated only when it is not the one the spec asked for, once the
+// phase's labelled creates are done. The stub's default makes the same distinction, so a build that sent the length and stopped would
+// end with 850 where the spec said 120.
+
+const asksFor = (maxLength, extra = {}) => ({ schemaName: 'new_name', displayName: 'Name', maxLength, ...extra });
+const requestLine = (r) => `${r.method} ${r.path}`;
+const NAME_LENGTH_READ = "GET /EntityDefinitions(LogicalName='new_ticket')/Attributes(LogicalName='new_name')/Microsoft.Dynamics.CRM.StringAttributeMetadata?$select=MaxLength";
+
+test('a table created with only its primary name column ends up with the length the spec asks for: read back after the create, then updated', async () => {
+ const run = await provisionOver(oneTable([], asksFor(120)));
+ assert.deepStrictEqual(tablePosts(run).map((r) => r.body.Attributes), [[primaryNameBody(120)]], 'the request asks for 120 — and the environment makes 850 of it');
+ assert.strictEqual(run.dv.tables.get('new_ticket').primaryLength, 120, 'so the column is updated, and ends up 120');
+ const id = attributeId('new_ticket', 'new_name');
+ assert.deepStrictEqual(run.dv.log.map(requestLine), [
+ "GET /EntityDefinitions(LogicalName='new_ticket')?$select=LogicalName,EntitySetName",
+ 'POST /EntityDefinitions',
+ `GET /EntityDefinitions(${tableId('new_ticket')})?$select=LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute`,
+ NAME_LENGTH_READ,
+ "GET /EntityDefinitions(LogicalName='new_ticket')/Attributes(LogicalName='new_name')?$select=MetadataId,AttributeType",
+ `GET /EntityDefinitions(LogicalName='new_ticket')/Attributes(${id})/Microsoft.Dynamics.CRM.StringAttributeMetadata`,
+ `PUT /EntityDefinitions(LogicalName='new_ticket')/Attributes(${id})`,
+ ], 'the table\'s existence probe, its create and read-back, then the length: one typed read and the update of the column');
+ const [update] = puts(run);
+ assert.strictEqual(update.body.MaxLength, 120);
+ assert.strictEqual(update.headers['MSCRM.MergeLabels'], 'true', 'the update keeps the labels already stored, as the documented update of a column does');
+ assert.deepStrictEqual(run.events.filter((e) => e.status !== 'start').map((e) => [e.status, e.label]), [
+ ['ok', 'table new_ticket'],
+ ['ok', 'primary column length new_ticket.new_name -> 120'],
+ ]);
+ assert.deepStrictEqual(run.warnings, []);
+});
+
+test('a name column the environment already made the length asked needs no update: the read-back is compared, and the step is a skip', async () => {
+ const run = await provisionOver(oneTable([], asksFor(120)), { dataverse: HONOURING });
+ assert.strictEqual(lengthReads(run).length, 1, 'read once');
+ assert.deepStrictEqual(puts(run), [], 'and not written: it is already 120');
+ assert.deepStrictEqual(lengthEvents(run).map((e) => [e.status, e.label]), [['skip', 'primary column length new_ticket.new_name (already 120)']]);
+ assert.strictEqual(run.dv.tables.get('new_ticket').primaryLength, 120);
+});
+
+// The length is set when the phase's labelled creates are done (the next tests, and the order tests above): after the change set and its
+// read-back, and after the columns that take their own request.
+test('a table that gets ordinary columns is aligned like any other, once its columns exist: the change set, its read-back and the columns made one by one come first, then the length is read back and set', async () => {
+ const run = await provisionOver(oneTable([textColumn('new_a'), { schemaName: 'new_b', type: 'Integer' }, { schemaName: 'new_file', type: 'File' }, { schemaName: 'new_owner', type: 'Customer' }], asksFor(120)));
+ const id = attributeId('new_ticket', 'new_name');
+ assert.deepStrictEqual(tablePosts(run).map((r) => r.body.Attributes), [[primaryNameBody(120)]], 'the create carries only the name column');
+ assert.deepStrictEqual(run.dv.log.map(requestLine), [
+ "GET /EntityDefinitions(LogicalName='new_ticket')?$select=LogicalName,EntitySetName",
+ 'POST /EntityDefinitions',
+ `GET /EntityDefinitions(${tableId('new_ticket')})?$select=LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute`,
+ 'POST /$batch',
+ `GET /EntityDefinitions(${tableId('new_ticket')})/Attributes?$select=MetadataId,LogicalName`,
+ "POST /EntityDefinitions(LogicalName='new_ticket')/Attributes",
+ 'POST /CreateCustomerRelationships',
+ NAME_LENGTH_READ,
+ "GET /EntityDefinitions(LogicalName='new_ticket')/Attributes(LogicalName='new_name')?$select=MetadataId,AttributeType",
+ `GET /EntityDefinitions(LogicalName='new_ticket')/Attributes(${id})/Microsoft.Dynamics.CRM.StringAttributeMetadata`,
+ `PUT /EntityDefinitions(LogicalName='new_ticket')/Attributes(${id})`,
+ ], 'the table, its columns in one change set and one read of them, the File and Customer columns, and last the name column\'s length: no labelled create follows the read that carries labels');
+ assert.deepStrictEqual(inlineNames(run), ['new_a', 'new_b']);
+ assert.strictEqual(run.dv.tables.get('new_ticket').primaryLength, 120);
+ assert.deepStrictEqual(lengthEvents(run).map((e) => [e.status, e.label]), [['ok', 'primary column length new_ticket.new_name -> 120']]);
+ assert.deepStrictEqual(run.warnings, []);
+});
+
+test('an auto-numbered name column: the length asked is read back after the create, and left alone when the environment kept it', async () => {
+ const run = await provisionOver(oneTable([], asksFor(120, { autoNumberFormat: 'WO-{SEQNUM:5}' })));
+ assert.deepStrictEqual(tablePosts(run)[0].body.Attributes, [{ ...primaryNameBody(120), AutoNumberFormat: 'WO-{SEQNUM:5}' }]);
+ assert.strictEqual(lengthReads(run).length, 1, 'read back');
+ assert.deepStrictEqual(puts(run), [], 'and not updated: the platform keeps the length asked of an auto-numbered column');
+ assert.deepStrictEqual(lengthEvents(run).map((e) => [e.status, e.label]), [['skip', 'primary column length new_ticket.new_name (already 120)']]);
+});
+
+test('a change set the platform refuses leaves the length alone: the columns are then created one by one, and the length is set after them', async () => {
+ const run = await provisionOver(oneTable([{ schemaName: 'new_a', type: 'Text' }], asksFor(120)), { dataverse: { batchFails: refusedChangeSet } });
+ assert.deepStrictEqual(tablePosts(run).map((r) => [r.body.Attributes.length, r.body.Attributes[0].MaxLength]), [[1, 120]], 'one create, asking for 120');
+ assert.strictEqual(run.dv.refusals.length, 1);
+ assert.strictEqual(lengthReads(run).length, 1);
+ assert.strictEqual(puts(run).length, 1);
+ const lines = run.dv.log.map(requestLine);
+ assert.ok(lines.lastIndexOf("POST /EntityDefinitions(LogicalName='new_ticket')/Attributes") < lines.indexOf(requestLine(lengthReads(run)[0])), 'the column made by its own request comes before the read of the length');
+ assert.strictEqual(run.dv.tables.get('new_ticket').primaryLength, 120);
+ assert.deepStrictEqual(lengthEvents(run).map((e) => [e.status, e.label]), [['ok', 'primary column length new_ticket.new_name -> 120']]);
+ assert.strictEqual(run.warnings.length, 1, 'only the warning that the columns are created one by one');
+ assert.match(run.warnings[0], /^could not create the 1 ordinary column\(s\) of table new_ticket in one request \(HTTP 400: refused\)/);
+ assert.ok(run.result.columns.new_ticket.some((c) => c.schemaName === 'new_a'), 'and the column was created');
+});
+
+test('a table a create with only its primary name column made, whose length is not the one asked, is read again while the new column is not yet visible', async () => {
+ const notYet = () => ({ status: 404, headers: {}, body: { error: { message: 'Could not find an attribute with LogicalName new_name' } } });
+ const run = await provisionOver(oneTable([], asksFor(120)), { dataverse: { lengthRead: (n) => (n <= 2 ? notYet() : undefined) } });
+ assert.strictEqual(lengthReads(run).length, 3, 'a 404 is asked again, twice');
+ assert.strictEqual(puts(run).length, 1);
+ assert.strictEqual(run.dv.tables.get('new_ticket').primaryLength, 120);
+ assert.deepStrictEqual(run.warnings, []);
+});
+
+test('a failed update of the length is a FAILED step that names the table, the length asked and the one the platform made — and a warning; the build goes on', async () => {
+ const refuse = () => ({ status: 400, headers: {}, body: { error: { message: 'The attribute cannot be changed right now' } } });
+ const run = await provisionOver(oneTable([{ schemaName: 'new_owner', type: 'Customer' }], asksFor(120)), { dataverse: { updateFails: refuse } });
+ assert.strictEqual(tablePosts(run)[0].body.Attributes.length, 1, 'a table whose only column takes the one-by-one path is created with only its primary name column');
+ const failed = run.events.filter((e) => e.status === 'error');
+ assert.strictEqual(failed.length, 1);
+ assert.strictEqual(failed[0].label, 'primary column length new_ticket.new_name -> 120', 'the table, and the length asked');
+ assert.match(failed[0].detail, /^asked 120, the platform made 850: .*The attribute cannot be changed right now/, 'the length the platform made, and why the update failed');
+ assert.strictEqual(run.warnings.length, 1);
+ assert.match(run.warnings[0], /^could not set the length of the primary name column new_ticket\.new_name to 120 .* the rest of the build continues: asked 120, the platform made 850: /);
+ assert.strictEqual(run.dv.tables.get('new_ticket').primaryLength, 850, 'the column keeps the length the platform gave it');
+ assert.ok(run.result.columns.new_ticket.some((c) => c.schemaName === 'new_owner'), 'the build went on and created the column');
+});
+
+test('a read of the length that fails is a FAILED step too — never a silent pass — and no update is attempted without knowing what to compare with', async () => {
+ const unreadable = () => ({ status: 500, headers: {}, body: { error: { message: 'An unexpected error occurred.' } } });
+ const run = await provisionOver(oneTable([], asksFor(120)), { dataverse: { lengthRead: unreadable } });
+ assert.strictEqual(lengthReads(run).length, 1, 'a 500 is not read again');
+ assert.deepStrictEqual(puts(run), []);
+ const failed = run.events.filter((e) => e.status === 'error');
+ assert.strictEqual(failed.length, 1);
+ assert.strictEqual(failed[0].label, 'primary column length new_ticket.new_name -> 120');
+ assert.match(failed[0].detail, /^asked 120, the length the platform made is unknown: could not read the column's length \(HTTP 500: An unexpected error occurred\.\)/);
+ assert.strictEqual(run.warnings.length, 1);
+ assert.match(run.warnings[0], /could not set the length of the primary name column new_ticket\.new_name to 120/);
+});
+
+// A table found after the answer to its create was lost — or one that somebody else made first — is never written to: nothing shows
+// that THIS build made it. But the length the spec asks for is compared with what the table has, in one typed read, and a difference
+// is said out loud: the stub's default makes a plain text name column 850 characters whatever length a create with only that column
+// asks for (measured on one environment), which is the likely state of such a table. Nor is such a table given a change set.
+const lostAnswer = lostCreateAnswer;
+
+test('a table found after the answer to its create was lost is never written, but its name column\'s length is read once and a difference is said out loud', async () => {
+ const plain = await provisionOver(oneTable([], asksFor(120)), { dataverse: { createCommitsThenFails: lostAnswer } });
+ assert.strictEqual(lengthReads(plain).length, 1, 'one typed read of the length');
+ assert.deepStrictEqual(puts(plain), [], 'and nothing is written');
+ assert.strictEqual(plain.dv.tables.get('new_ticket').primaryLength, 850, 'the column keeps the length the platform gave it');
+ assert.deepStrictEqual(lengthEvents(plain).map((e) => [e.status, e.label]), [['skip', 'primary column length new_ticket.new_name (table found after its create — kept at 850, asked 120)']]);
+ assert.strictEqual(plain.warnings.length, 1);
+ assert.match(plain.warnings[0], /^the primary name column new_ticket\.new_name is 850 characters long, not the 120 the spec asks for — .*answer to that create was lost.*left alone/);
+ assert.deepStrictEqual(plain.events.filter((e) => e.status === 'error'), [], 'the build goes on: this is a warning, not a failed step');
+});
+
+test('a table found after its create whose name column already has the length asked is a skip that says so, with no warning', async () => {
+ // An auto-numbered name column keeps the length asked even in a create with only that column.
+ const keeps = await provisionOver(oneTable([], asksFor(120, { autoNumberFormat: 'WO-{SEQNUM:5}' })), { dataverse: { createCommitsThenFails: lostAnswer } });
+ assert.strictEqual(lengthReads(keeps).length, 1);
+ assert.deepStrictEqual(puts(keeps), []);
+ assert.deepStrictEqual(lengthEvents(keeps).map((e) => [e.status, e.label]), [['skip', 'primary column length new_ticket.new_name (already 120)']]);
+ assert.deepStrictEqual(keeps.warnings, []);
+});
+
+test('a table found after its create whose name column\'s length cannot be read is a skip that says so, with a warning — never a silent pass', async () => {
+ const unreadable = () => ({ status: 500, headers: {}, body: { error: { message: 'An unexpected error occurred.' } } });
+ const run = await provisionOver(oneTable([], asksFor(120)), { dataverse: { createCommitsThenFails: lostAnswer, lengthRead: unreadable } });
+ assert.strictEqual(lengthReads(run).length, 1, 'a 500 is not read again');
+ assert.deepStrictEqual(puts(run), []);
+ assert.deepStrictEqual(lengthEvents(run).map((e) => [e.status, e.label]), [['skip', 'primary column length new_ticket.new_name (table found after its create — kept; its length could not be read)']]);
+ assert.strictEqual(run.warnings.length, 1);
+ assert.match(run.warnings[0], /^could not read the length of the primary name column new_ticket\.new_name \(could not read the column's length \(HTTP 500: An unexpected error occurred\.\)\), so the 120 the spec asks for is not confirmed — .*left alone/);
+});
+
+test('a table found after its create is not read when the spec asks for no length; with a length and columns it is read and compared, never written, and given no change set', async () => {
+ const none = await provisionOver(oneTable([], { schemaName: 'new_name', displayName: 'Name' }), { dataverse: { createCommitsThenFails: lostAnswer } });
+ assert.deepStrictEqual(lengthReads(none), [], 'nothing to compare with');
+ assert.deepStrictEqual(lengthEvents(none), []);
+ assert.deepStrictEqual(none.warnings, []);
+ const withColumns = await provisionOver(oneTable([{ schemaName: 'new_a', type: 'Text' }], asksFor(120)), { dataverse: { createCommitsThenFails: lostAnswer } });
+ assert.strictEqual(lengthReads(withColumns).length, 1);
+ assert.deepStrictEqual(puts(withColumns), []);
+ assert.deepStrictEqual(batchPosts(withColumns), [], 'the table is not given a change set');
+ assert.deepStrictEqual(columnPosts(withColumns).map((r) => r.body.SchemaName), ['new_a'], 'its column is created by its own request');
+ assert.strictEqual(withColumns.dv.tables.get('new_ticket').primaryLength, 850, 'and the name column is left as it is');
+ assert.deepStrictEqual(lengthEvents(withColumns).map((e) => [e.status, e.label]), [['skip', 'primary column length new_ticket.new_name (table found after its create — kept at 850, asked 120)']]);
+ assert.strictEqual(withColumns.warnings.length, 1, 'with the one warning, and none about columns created together');
+});
+
+test('the primary column length step is planned exactly when the spec asks for a length, and narrated once however the table was made, so [n/total] holds', async () => {
+ const { planFor } = require('../lib/sdk-build.js');
+ const scenarios = [
+ ['only the primary name column, platform ignores the length', oneTable([], asksFor(120)), {}],
+ ['only the primary name column, already the length', oneTable([], asksFor(120)), HONOURING],
+ ['with columns', oneTable([{ schemaName: 'new_a', type: 'Text' }], asksFor(120)), {}],
+ ['after a refused change set', oneTable([{ schemaName: 'new_a', type: 'Text' }], asksFor(120)), { batchFails: refusedChangeSet }],
+ ['an update that fails', oneTable([], asksFor(120)), { updateFails: () => ({ status: 400, headers: {}, body: { error: { message: 'no' } } }) }],
+ ['a table found after the answer to its create was lost', oneTable([], asksFor(120)), { createCommitsThenFails: lostAnswer }],
+ ['no length asked', oneTable([{ schemaName: 'new_a', type: 'Text' }], { schemaName: 'new_name', displayName: 'Name' }), {}],
+ ];
+ for (const [what, spec, dataverse] of scenarios) {
+ const run = await provisionOver(spec, { dataverse });
+ const planned = planFor(spec, { phases: ['data-model'] });
+ const asked = spec.entities[0].primaryAttribute.maxLength !== undefined;
+ assert.strictEqual(planned.filter((i) => /^primary column length /.test(i.label)).length, asked ? 1 : 0, `${what}: planned`);
+ assert.strictEqual(lengthEvents(run).length, asked ? 1 : 0, `${what}: narrated`);
+ assert.strictEqual(run.events.filter((e) => e.status !== 'start').length, planned.length, `${what}: as many steps as the plan has, so n never passes total`);
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/teardown-publish-once.test.js b/plugins/model-apps/scripts/tests/teardown-publish-once.test.js
new file mode 100644
index 000000000..c4f2a348f
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/teardown-publish-once.test.js
@@ -0,0 +1,361 @@
+'use strict';
+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 { runTeardown: engineTeardown, KIND_HANDLERS } = require('../lib/sdk-teardown.js');
+
+const runTeardown = (spec, opts, deps) => engineTeardown(spec, { env: 'https://contoso.crm.dynamics.com', ...opts }, deps);
+const PARTIAL_ENRICHMENT = Symbol.for('cds-maker-sdk.partialDefaultViewEnrichment');
+const bundleWorkspaces = [];
+
+test.after(() => {
+ for (const dir of bundleWorkspaces) fs.rmSync(dir, { recursive: true, force: true });
+});
+
+function teardownSpec(resetCount) {
+ const entities = [{
+ schemaName: 'cnt_parent',
+ primaryAttribute: { schemaName: 'cnt_name' },
+ columns: [{ schemaName: 'cnt_code', type: 'Text' }],
+ }];
+ const relationships = [];
+ for (let i = 1; i <= resetCount; i += 1) {
+ entities.push({
+ schemaName: `cnt_child${i}`,
+ primaryAttribute: { schemaName: 'cnt_name' },
+ columns: [{ schemaName: `cnt_code${i}`, type: 'Text' }],
+ });
+ relationships.push({
+ type: 'OneToMany',
+ referenced: 'cnt_parent',
+ referencing: `cnt_child${i}`,
+ lookup: { schemaName: `cnt_ParentId${i}` },
+ });
+ }
+ return {
+ solution: { uniqueName: 'ContosoTeardown', publisherPrefix: 'cnt' },
+ entities,
+ relationships,
+ };
+}
+
+function makeTeardownSdk({
+ envelope,
+ envelopeThrows,
+ publishOne,
+ partialFailure,
+ withBatch = true,
+} = {}) {
+ const calls = [];
+ const publishByTable = new Map();
+ const sdk = {
+ resolveArtifact: async (kind, identity) => {
+ calls.push({ method: 'resolveArtifact', kind, identity });
+ return kind === 'solution' ? [{ id: 'sol-1', name: identity.uniqueName }] : [];
+ },
+ enrichDefaultViews: async (logical, cols, opts) => {
+ calls.push({ method: 'enrichDefaultViews', logical, cols, opts });
+ const publishTarget = { type: 'view', id: `view-${logical}` };
+ publishByTable.set(logical, publishTarget);
+ const pendingPublish = [{ scope: { envelope: 'entity', entityLogicalName: logical }, artifacts: [publishTarget] }];
+ if (partialFailure && partialFailure[logical]) {
+ const inner = new Error(`partial save for ${logical}`);
+ inner[PARTIAL_ENRICHMENT] = { updated: [publishTarget.id], results: [], pendingPublish };
+ throw new Error(`wrapped ${logical}`, { cause: inner });
+ }
+ if (opts && opts.publish === false) return { updated: [publishTarget.id], results: [], pendingPublish };
+ return { updated: [publishTarget.id] };
+ },
+ publishArtifact: async (type, id) => {
+ calls.push({ method: 'publishArtifact', type, id });
+ if (typeof publishOne === 'function') return publishOne(type, id);
+ return { type, id, shipped: true, publish: { kind: 'verified' } };
+ },
+ deleteRelationship: async (schemaName) => {
+ calls.push({ method: 'deleteRelationship', schemaName });
+ },
+ deleteTable: async (logical) => {
+ calls.push({ method: 'deleteTable', logical });
+ },
+ deleteSolution: async (id) => {
+ calls.push({ method: 'deleteSolution', id });
+ },
+ };
+ if (withBatch) {
+ sdk.publishArtifacts = async (targets) => {
+ calls.push({ method: 'publishArtifacts', targets });
+ if (typeof envelopeThrows === 'function') throw envelopeThrows(targets);
+ if (envelopeThrows) throw envelopeThrows;
+ if (typeof envelope === 'function') return envelope(targets);
+ return targets.map(({ type, id }) => ({ type, id, shipped: true, publish: { kind: 'verified' } }));
+ };
+ }
+ return { sdk, calls, publishByTable };
+}
+
+function callNames(calls) {
+ return calls.map((call) => call.method);
+}
+
+function lastIndex(calls, method) {
+ return calls.map((call) => call.method).lastIndexOf(method);
+}
+
+function count(calls, method) {
+ return calls.filter((call) => call.method === method).length;
+}
+
+function guid(seed) {
+ return `${seed}${seed}${seed}${seed}${seed}${seed}${seed}${seed}-0000-4000-8000-00000000000${seed}`;
+}
+
+function generatedFetch(entity, statecode) {
+ return (
+ `<fetch version="1.0" mapping="logical"><entity name="${entity}"><attribute name="${entity}id" />` +
+ `<filter type="and"><condition attribute="statecode" operator="eq" value="${statecode}" /></filter>` +
+ `</entity></fetch>`
+ );
+}
+
+function bundleHarness(entities) {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'teardown-publish-once-'));
+ bundleWorkspaces.push(workspace);
+ const GENERATED_AT = '2026-09-30T10:00:00Z';
+ const rows = {};
+ const byEntity = {};
+ const posts = [];
+ entities.forEach((entity, index) => {
+ const active = guid(String(index + 1));
+ const inactive = guid(String(index + 4));
+ byEntity[entity] = [active, inactive];
+ rows[active] = {
+ savedqueryid: active,
+ name: `Active ${entity}`,
+ description: '',
+ returnedtypecode: entity,
+ querytype: 0,
+ isdefault: true,
+ fetchxml: generatedFetch(entity, 0),
+ layoutxml: `<grid name="resultset" object="1" jump="${entity}_name" select="1" icon="1" preview="1"><row name="result" id="${entity}id"><cell name="${entity}_name" width="300" /></row></grid>`,
+ };
+ rows[inactive] = {
+ savedqueryid: inactive,
+ name: `Inactive ${entity}`,
+ description: '',
+ returnedtypecode: entity,
+ querytype: 0,
+ isdefault: false,
+ fetchxml: generatedFetch(entity, 1),
+ layoutxml: `<grid name="resultset" object="1" jump="${entity}_name" select="1" icon="1" preview="1"><row name="result" id="${entity}id"><cell name="${entity}_name" width="300" /></row></grid>`,
+ };
+ });
+ const rowFor = (decodedUrl) => {
+ const match = decodedUrl.match(/\/savedqueries\(([^)]+)\)/);
+ return match ? rows[match[1]] : null;
+ };
+ const httpClient = {
+ get: async (url) => {
+ const decoded = decodeURIComponent(url);
+ if (decoded.includes('/savedqueries?') && decoded.includes('querytype eq 0')) {
+ const entity = (decoded.match(/returnedtypecode eq '([^']+)'/) || [])[1];
+ const ids = byEntity[entity] || [];
+ return {
+ status: 200,
+ headers: {},
+ body: {
+ value: ids.map((id, i) => ({
+ savedqueryid: id,
+ name: `${i === 0 ? 'Active' : 'Inactive'} ${entity}`,
+ isdefault: i === 0,
+ canbedeleted: { Value: false },
+ fetchxml: generatedFetch(entity, i),
+ createdon: GENERATED_AT,
+ })),
+ },
+ };
+ }
+ const row = rowFor(decoded);
+ if (row) return { status: 200, headers: { etag: 'W/"1"' }, body: row };
+ return { status: 200, headers: {}, body: { value: [] } };
+ },
+ post: async (url, body) => {
+ posts.push({ url: decodeURIComponent(url), body });
+ return {
+ status: 204,
+ headers: { 'odata-entityid': 'https://example.crm.dynamics.com/api/data/v9.0/any(11111111-1111-1111-1111-111111111111)' },
+ body: {},
+ };
+ },
+ patch: async (url, body) => {
+ const row = rowFor(decodeURIComponent(url));
+ Object.assign(row, body);
+ return { status: 204, headers: {}, body: {} };
+ },
+ delete: async () => ({ status: 204, headers: {}, body: {} }),
+ put: async () => ({ status: 204, headers: {}, body: {} }),
+ };
+ const sdk = createMakerSdk({
+ workspaceStorage: createNodeWorkspaceStorage(workspace),
+ instanceUrl: 'https://example.crm.dynamics.com',
+ httpClient,
+ });
+ return { sdk, posts };
+}
+
+function realBundleTeardownSpec(entities) {
+ return {
+ entities: [
+ {
+ schemaName: 'p5_parent',
+ existing: true,
+ enrichDefaultViews: false,
+ primaryAttribute: { schemaName: 'p5_name' },
+ columns: [{ schemaName: 'p5_code', type: 'Text' }],
+ },
+ ...entities.map((entity, index) => ({
+ schemaName: entity,
+ existing: true,
+ enrichDefaultViews: true,
+ primaryAttribute: { schemaName: `${entity}_name` },
+ columns: [{ schemaName: `${entity}_code`, type: 'Text' }],
+ })),
+ ],
+ relationships: entities.map((entity, index) => ({
+ type: 'OneToMany',
+ referenced: 'p5_parent',
+ referencing: entity,
+ lookup: { schemaName: `p5_ParentId${index + 1}` },
+ })),
+ };
+}
+
+test('batches K=3, keeps K=1 as one publish, and leaves the legacy immediate path unchanged', async () => {
+ const batched = makeTeardownSdk();
+ const result = await runTeardown(teardownSpec(3), { apply: true }, { sdk: batched.sdk, emit: () => {} });
+ assert.equal(result.ok, true);
+ assert.equal(count(batched.calls, 'publishArtifacts'), 1, callNames(batched.calls).join(' -> '));
+ assert.equal(count(batched.calls, 'publishArtifact'), 0);
+ assert.deepEqual(
+ batched.calls.find((call) => call.method === 'publishArtifacts').targets,
+ [
+ { type: 'view', id: 'view-cnt_child1' },
+ { type: 'view', id: 'view-cnt_child2' },
+ { type: 'view', id: 'view-cnt_child3' },
+ ],
+ );
+ batched.calls
+ .filter((call) => call.method === 'enrichDefaultViews')
+ .forEach((call) => assert.equal(call.opts.publish, false, `${call.logical} should defer the publish`));
+
+ const single = makeTeardownSdk();
+ await runTeardown(teardownSpec(1), { apply: true }, { sdk: single.sdk, emit: () => {} });
+ assert.equal(count(single.calls, 'publishArtifacts'), 0);
+ assert.equal(count(single.calls, 'publishArtifact'), 1);
+ assert.deepEqual(single.calls.find((call) => call.method === 'publishArtifact'), { method: 'publishArtifact', type: 'view', id: 'view-cnt_child1' });
+
+ const legacyCalls = [];
+ await KIND_HANDLERS.resetDefaultViews.del({
+ enrichDefaultViews: async (...args) => { legacyCalls.push(args); return { updated: ['view-cnt_child1'] }; },
+ }, { id: 'cnt_child1', cols: [{ name: 'cnt_name' }] });
+ assert.deepEqual(legacyCalls, [['cnt_child1', [{ name: 'cnt_name' }]]], 'the direct two-argument call keeps the old immediate SDK contract');
+
+ const legacy = makeTeardownSdk({ withBatch: false });
+ await runTeardown(teardownSpec(1), { apply: true }, { sdk: legacy.sdk, emit: () => {} });
+ assert.equal(count(legacy.calls, 'publishArtifacts'), 0);
+ assert.equal(count(legacy.calls, 'publishArtifact'), 0);
+ assert.deepEqual(legacy.calls.find((call) => call.method === 'enrichDefaultViews').opts, undefined, 'a legacy SDK shape keeps the old enrich-and-publish call');
+});
+
+test('publishes after the last reset and before the first relationship delete without moving other teardown order', async () => {
+ const { sdk, calls } = makeTeardownSdk();
+ await runTeardown(teardownSpec(3), { apply: true }, { sdk, emit: () => {} });
+ const publishIndex = calls.findIndex((call) => call.method === 'publishArtifacts');
+ assert.ok(lastIndex(calls, 'enrichDefaultViews') < publishIndex, callNames(calls).join(' -> '));
+ assert.ok(publishIndex < calls.findIndex((call) => call.method === 'deleteRelationship'), callNames(calls).join(' -> '));
+ assert.ok(lastIndex(calls, 'deleteRelationship') < calls.findIndex((call) => call.method === 'deleteTable'), callNames(calls).join(' -> '));
+ assert.ok(lastIndex(calls, 'deleteTable') < calls.findIndex((call) => call.method === 'deleteSolution'), callNames(calls).join(' -> '));
+});
+
+test('envelope failure falls back per target, names only the unpublished table, and a partial reset still gets published', async () => {
+ const warnings = [];
+ const { sdk, calls } = makeTeardownSdk({
+ partialFailure: { cnt_child2: true },
+ envelope: (targets) => targets.map(({ type, id }) => ({
+ type,
+ id,
+ shipped: false,
+ publish: { kind: 'failed', error: new Error('envelope failed') },
+ })),
+ publishOne: async (type, id) => {
+ if (id === 'view-cnt_child3') return { type, id, shipped: false, publish: { kind: 'failed', error: new Error('single publish failed') } };
+ return { type, id, shipped: true, publish: { kind: 'verified' } };
+ },
+ });
+ const result = await runTeardown(teardownSpec(3), { apply: true }, { sdk, emit: () => {}, warn: (message) => warnings.push(message) });
+
+ assert.equal(result.ok, true, JSON.stringify(result.errors));
+ assert.equal(count(calls, 'publishArtifacts'), 1);
+ assert.deepEqual(
+ calls.filter((call) => call.method === 'publishArtifact').map((call) => call.id),
+ ['view-cnt_child1', 'view-cnt_child2', 'view-cnt_child3'],
+ );
+ assert.equal(count(calls, 'deleteRelationship'), 3, 'relationship teardown still runs');
+ assert.deepEqual(warnings, result.warnings);
+ assert.equal(warnings.length, 1, warnings.join('\n'));
+ assert.match(warnings[0], /cnt_child3/);
+ assert.doesNotMatch(warnings[0], /cnt_child1|cnt_child2/);
+ assert.match(warnings[0], /saved but may still be unpublished/i);
+ assert.match(warnings[0], /lookup as still referenced/i);
+});
+
+test('a thrown publishArtifacts preflight still falls back, and a later emit failure settles the owed publish exactly once', async () => {
+ const refused = makeTeardownSdk({
+ partialFailure: { cnt_child2: true },
+ envelopeThrows: new Error('target not in workspace'),
+ });
+ const result = await runTeardown(teardownSpec(2), { apply: true }, { sdk: refused.sdk, emit: () => {} });
+ assert.equal(result.ok, true);
+ assert.equal(count(refused.calls, 'publishArtifacts'), 1);
+ assert.deepEqual(
+ refused.calls.filter((call) => call.method === 'publishArtifact').map((call) => call.id),
+ ['view-cnt_child1', 'view-cnt_child2'],
+ );
+
+ const thrown = makeTeardownSdk();
+ await assert.rejects(
+ runTeardown(teardownSpec(2), { apply: true }, {
+ sdk: thrown.sdk,
+ emit: (event) => {
+ if (event.phase === 'relationships' && event.status === 'start') throw new Error('emit boom');
+ },
+ }),
+ /emit boom/,
+ );
+ assert.equal(count(thrown.calls, 'publishArtifacts'), 1, callNames(thrown.calls).join(' -> '));
+ assert.equal(count(thrown.calls, 'publishArtifact'), 0);
+ assert.equal(count(thrown.calls, 'deleteRelationship'), 0, 'the throw stops the relationship step after the publish barrier is settled');
+});
+
+test('the real vendored bundle turns three per-table PublishXml requests into one deferred envelope', async () => {
+ const entities = ['p5_alpha', 'p5_beta', 'p5_gamma'];
+
+ const before = bundleHarness(entities);
+ await before.sdk.initWorkspace();
+ for (const entity of entities) {
+ await before.sdk.enrichDefaultViews(entity, [{ name: `${entity}_name` }, { name: 'createdon' }]);
+ }
+ const beforePublishes = before.posts.filter((call) => call.url.endsWith('/PublishXml'));
+ assert.equal(beforePublishes.length, 3, JSON.stringify(beforePublishes.map((call) => call.body)));
+
+ const after = bundleHarness(entities);
+ await after.sdk.initWorkspace();
+ after.sdk.deleteRelationship = async () => {};
+ await runTeardown(realBundleTeardownSpec(entities), { apply: true }, { sdk: after.sdk, emit: () => {} });
+ const afterPublishes = after.posts.filter((call) => call.url.endsWith('/PublishXml'));
+ assert.equal(afterPublishes.length, 1, JSON.stringify(afterPublishes.map((call) => call.body)));
+ assert.match(afterPublishes[0].body.ParameterXml, /<entity>p5_alpha<\/entity>.*<entity>p5_beta<\/entity>.*<entity>p5_gamma<\/entity>/);
+});
diff --git a/plugins/model-apps/scripts/tests/unsynced-edits.test.js b/plugins/model-apps/scripts/tests/unsynced-edits.test.js
new file mode 100644
index 000000000..8945b6aa3
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/unsynced-edits.test.js
@@ -0,0 +1,29 @@
+'use strict';
+// A push is skipped only on the SDK's own proof that the workspace copy equals what was last synced, and
+// every doubt reads as "changed". The behaviour against the real bundle is pinned in rebuild-writes-real-bundle.test.js.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { hasUnsyncedEdits } = require('../lib/unsynced-edits.js');
+
+const sdkWith = (diff) => ({ diffArtifact: async (type, id) => (typeof diff === 'function' ? diff(type, id) : diff) });
+
+test('unsynced edits: an empty diff is the only proof of "nothing to push"', async () => {
+ assert.equal(await hasUnsyncedEdits(sdkWith({ artifactType: 'view', artifactId: 'v', changes: [] }), 'view', 'v'), false);
+ assert.equal(await hasUnsyncedEdits(sdkWith({ changes: [{ pointer: '/columns/1', type: 'added', newValue: {} }] }), 'view', 'v'), true);
+});
+
+test('unsynced edits: the diff is asked about the artifact in question', async () => {
+ const asked = [];
+ await hasUnsyncedEdits(sdkWith((type, id) => { asked.push([type, id]); return { changes: [] }; }), 'form', 'f-1');
+ assert.deepEqual(asked, [['form', 'f-1']]);
+});
+
+test('unsynced edits: anything short of a clear answer reads as changed (fail open: write as before)', async () => {
+ assert.equal(await hasUnsyncedEdits(undefined, 'view', 'v'), true, 'no SDK');
+ assert.equal(await hasUnsyncedEdits({}, 'view', 'v'), true, 'an SDK without the method');
+ assert.equal(await hasUnsyncedEdits({ diffArtifact: async () => { throw new Error('workspace file unreadable'); } }, 'view', 'v'), true, 'a diff that throws');
+ assert.equal(await hasUnsyncedEdits({ diffArtifact: () => { throw new Error('sync throw'); } }, 'view', 'v'), true, 'a diff that throws synchronously');
+ for (const odd of [undefined, null, {}, { changes: null }, { changes: 'none' }, { changes: {} }, 0, '']) {
+ assert.equal(await hasUnsyncedEdits(sdkWith(odd), 'view', 'v'), true, `diff answer ${JSON.stringify(odd)}`);
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/valid-page-differential.test.js b/plugins/model-apps/scripts/tests/valid-page-differential.test.js
index 04e26bb9f..0386f322a 100644
--- a/plugins/model-apps/scripts/tests/valid-page-differential.test.js
+++ b/plugins/model-apps/scripts/tests/valid-page-differential.test.js
@@ -9,29 +9,24 @@
// - PRECISE: every valid page the lexer refuses is one of the RECORDED classes below, each a place where two programs share the text up to the decision and compile differently
// (TWO_WAY shows both, with TypeScript's reading of each), and every refusal names its guess. A page that is refused and belongs to no class fails the test, so a regression of a new
// shape cannot arrive silently; a class that no page meets fails too, so the list cannot go stale.
+// - NO REGRESSION: where the base is given, every valid page that it resolves is resolved here: a page lost anywhere fails the test. The count of the pages that this lexer resolves and the base does not is reported.
//
// The pages are tests/helpers/valid-pages.js: generic arrows and function expressions in every position, casts and `satisfies` with every operator and operand after them, instantiation
// expressions and hooks, interfaces and type literals with every member form, generic function types in every position and with every kind of parameter list, destructured and default
// parameters, and the statements an everyday page is made of. The base is optional: BASE_LIB_PATH points at the scripts/lib directory of the lexer before this change; without it the
-// comparison is skipped and the rest runs.
+// comparison is skipped and the rest runs. What the comparison asserts depends on the base, because the decoys are what a lexer that misreads rewrites: a base from before the lexer was hardened misreads
+// shapes this corpus holds and rewrites the data after them on at least 100 pages, which shows that the net sees a misread (and this lexer rewrites none of them); a base that reads every page of the
+// corpus right — the previous release, whose misreads are in pages that hold the text of a call in their own text, which the decoys after a page cannot show (TWO_WAY has those pairs) — rewrites none, so
+// what it shows is the improvement: pages that this lexer resolves and the base does not. Either way the count of each is reported.
const { test } = require('node:test');
const assert = require('node:assert');
-const path = require('node:path');
-const { loadTypescriptOracle } = require('./helpers/typescript-oracle.js');
-const { validPages, NAVIGATION_CALL, SIGNATURE_MEMBERS, HIDDEN_CLOSING_MEMBERS, HIDING_ELEMENTS, INITIALIZER_ELEMENTS } = require('./helpers/valid-pages.js');
+const { loadTypescriptOracle, loadBaseLexer } = require('./helpers/typescript-oracle.js');
+const { validPages, openLinePages, NAVIGATION_CALL, SIGNATURE_MEMBERS, HIDDEN_CLOSING_MEMBERS, HIDING_ELEMENTS, INITIALIZER_ELEMENTS, FAILING_LIST_ELEMENTS, EXACT_INITIALIZER_ELEMENTS, PROSE_ELEMENTS, SHAPED_PROSE_ELEMENTS, PROSE_OPEN_ELEMENTS } = require('./helpers/valid-pages.js');
const next = require('../lib/pageref-resolver.js');
const SKIP = 'no TypeScript parser oracle: set TYPESCRIPT_ORACLE_PATH to a typescript package to run it';
const ID = '11111111-1111-4111-8111-111111111111';
-const loadBase = () => {
- const at = process.env.BASE_LIB_PATH;
- if (!at) return null;
- try {
- return require(path.join(at, 'pageref-resolver.js'));
- } catch {
- return null;
- }
-};
+const loadBase = loadBaseLexer;
// What a lexer does with a page: whether it resolves the call the page makes (and nothing else is changed), and the guess it names where it does not.
function reading(lib, code) {
@@ -77,20 +72,20 @@ const REFUSAL_CLASSES = [
{
id: 'JSX text that starts with a parenthesis, then a `,`, `;` or line break, and a comment, a template or a regex that is open at its closing tag',
kind: 'generic',
- what: 'the text after the `)` could be the members of a type that holds a comment, a template or a regex with the closing tag in it: `interface P { <U>(x: U); // </U> }` and `<U>(x: U); // </U>` share their text, and the closing tag is the end of the element in one and inside a comment in the other. Text before it that no type can hold (two names on a line, a name and a `/`) leaves no such type, and is read as the element.',
+ what: 'the text after the `)` could be the members of a type that holds a comment, a template or a regex with the closing tag in it: `interface P { <U>(x: U); // </U> }` and `<U>(x: U); // </U>` share their text, and the closing tag is the end of the element in one and inside a comment in the other. Text before it that no type can hold (two names on a line, a name and a `/`) leaves no such type, and is read as the element. After an `=`, a `(`, a `[`, a `:` or an `=>` no member of a type begins, and the text is the element for certain.',
matches: (page) => page.group === 'parenthesised element' && HIDING_ELEMENTS.includes(page.element),
},
{
- id: 'JSX text that starts with a parenthesis, where something may start an expression before its `)` and a `/`, a `<` or a back-tick follows',
+ id: 'JSX text that starts with a parenthesis, where something may start an expression before its `)` and a `/`, a `<` or a back-tick follows that the scan cannot read exactly',
kind: 'generic',
- what: 'the parenthesised text could be the parameter list of a call signature with a default, a computed name, a decorator, an accessor\'s body or a constraint, and what follows may be a regex, JSX or a template that holds a `)` of its own: `interface P { <U>(a = /[)]/); m: \'</U>\' }` and `<U>(a = /[)]/); m: \'</U>` share their text, and the `)` that ends the list is another one in each.',
+ what: 'the parenthesised text could be the parameter list of a call signature with a default, a computed name, a decorator, an accessor\'s body or a constraint, and what follows may be a regex, JSX or a template that holds a `)` of its own: `interface P { <U>(a = f(/[)]/)); m: \'</U>\' }` and `<U>(a = f(/[)]/)); m: \'</U>` share their text, and the `)` that ends the list is another one in each. A default that starts with a regex or an element, a `/` that divides a name or a number, and a template with no `${` are read exactly. A `/` after a line comment is none of those: the comment may end in a word, and the regex on the next line is no division (`<U>(a = 1 + // c` and `/[)]/)`).',
matches: (page) => page.group === 'parenthesised element' && INITIALIZER_ELEMENTS.includes(page.element),
},
{
- id: 'an element whose first attribute is `extends` and that closes at once',
+ id: 'an element whose first attribute is `extends` and that closes at once, where another `/` closes the regex on its line',
kind: 'generic',
- what: 'a `<Name extends` and a `/`: an element with an attribute named `extends` where an expression starts, and type parameters in a type, whose constraint is read as an expression where it starts no type — here a regex. `const e = <T extends />;` and `let f: <T extends />;…[/]/>(a: T) => T;` begin with the same text.',
- matches: (page) => page.group === 'everyday' && /^const e\d+ = /.test(page.name),
+ what: 'a `<Name extends` and a `/`: an element with an attribute named `extends` where an expression starts, and type parameters in a type, whose constraint is read as an expression where it starts no type — here a regex that another `/` on the line closes. `const e = <T extends />; const r = a / b;` and `let f: <T extends />; const r = a />(a: T) => T;` begin with the same text. (A regex that its line does not close is unterminated, TS1161: only the element compiles.)',
+ matches: (page) => page.group === 'everyday' && /^const e3 = /.test(page.name),
},
{
id: 'a division on the next line',
@@ -115,21 +110,95 @@ const TWO_WAY = [
},
{
kind: 'generic',
+ // An element whose text starts with a parenthesis stands where a member of a type may begin at its head — after a `return` here, where `return <U>(x)` is also a method named `return` — so that the text alone does not tell the two programs
+ // apart. After an `=`, a `(`, a `[`, a `:` or an `=>` no member begins, and such an element is read for certain (source-literals.js, NO_MEMBER_BEFORE).
pairs: [
['an interface with a call signature, and a string that holds the call', `interface P { <U>(x: U): T; }\nconst s = '</U>;${CALL};//';`, 0],
['an element whose text starts with a parenthesis, then the call', `const el = <U>(x: U): T;</U>;\n${CALL};`, 1],
['a type literal with a call signature, then the call', `type P = { <U>(x: U): T; };\n${CALL};`, 1],
// The same text with no return type: the type's string holds the closing tag and the call, and an element's text ends at the closing tag that is in it.
['an interface with a call signature with no return type, and a string that holds the closing tag and the call', `interface P { <U>(x: U); a: '</U>;${CALL};//'; }`, 0],
- ['an element whose text starts with a parenthesis, which ends at the closing tag in what is a string to the type, then the call', `const el = <U>(x: U); a: '</U>;${CALL};//'`, 1],
+ ['an element whose text starts with a parenthesis, which ends at the closing tag in what is a string to the type, then the call', `return <U>(x: U); a: '</U>;${CALL};//'`, 1],
['an interface with a call signature with no return type, and a comment that holds the closing tag and the call', `interface P { <U>(x: U); // </U>;${CALL};\n}`, 0],
- ['an element whose text starts with a parenthesis, which ends at the closing tag in what is a comment to the type, then the call', `const el = <U>(x: U); // </U>;${CALL};`, 1],
- // A default in the parameter list: the regex holds a `)`, which ends the list in a scan of it and is the regex's to the type.
- ['an interface with a call signature whose default is a regex that holds a `)`, and a string that holds the closing tag and the call', `interface P { <U>(a = /[)]/); m: '</U>;${CALL};//'; }`, 0],
- ['an element whose text starts with a parenthesis and holds the same default, then the call', `const el = <U>(a = /[)]/); m: '</U>;\n${CALL};`, 1],
- // `<T extends` and a `/`: type parameters whose constraint is a regex in a type, an element with an attribute named `extends` where an expression starts.
+ ['an element whose text starts with a parenthesis, which ends at the closing tag in what is a comment to the type, then the call', `return <U>(x: U); // </U>;${CALL};`, 1],
+ // A default in the parameter list: the regex holds a `)`, which ends the list in a scan that does not read the regex and is the regex's to the type. Where the regex is the default's first token the scan reads
+ // it exactly; here it is an argument, which the scan does not.
+ ['an interface with a call signature whose default calls a function with a regex that holds a `)`, and a string that holds the closing tag and the call', `interface P { <U>(a = f(/[)]/)); m: '</U>;${CALL};//'; }`, 0],
+ ['an element whose text starts with a parenthesis and holds the same default, then the call', `const el = <U>(a = f(/[)]/)); m: '</U>;\n${CALL};`, 1],
+ // A default whose regex follows a line comment: the last token before the comment is the operator, so the `/` on the next line begins a regex, whose `)` is not the one that ends the list. Taken for a division, the
+ // `/` ended the list at that `)`, and (for the text of a signature with no return type) hid the closing tag of the head in the regex. The base reads the second pair wrong: it rewrites the token in the regex.
+ ['an interface with a call signature whose default holds a regex after a line comment, and a string that holds the closing tag and the call', `interface P { <U>(a = 1 + // c\n/[)]/); m: '</U>;${CALL};//'; }`, 0],
+ ['an element whose text starts with a parenthesis and holds the same default, then the call', `const el = <U>(a = 1 + // c\n/[)]/); m: '</U>;\n${CALL};`, 1],
+ ['an interface with a call signature with no return type, and a later member whose default holds, after a line comment, a regex that holds the closing tag and the call', `interface P { <U>(x); m(a = 1 + // c\n/[</U>;${CALL}//]/): void }`, 0],
+ ['an element whose text starts with a parenthesis and holds the same text up to the closing tag, then the call', `return <U>(x); m(a = 1 + // c\n/[</U>;\n${CALL};//]/): void`, 1],
+ // `<T extends` and a `/`: type parameters whose constraint is a regex in a type, an element with an attribute named `extends` where an expression starts. A regex that its line does not close is no type's.
['a function type whose type parameter\'s constraint is a regex that holds the call', `let f: <T extends />;${CALL};[/]/>(a: T) => T;`, 0],
- ['an element whose first attribute is `extends` and that closes at once, then the call', `const el = <T extends />;\n${CALL};`, 1],
+ ['an element whose first attribute is `extends` and that closes at once, with another `/` on its line, then the call', `const el = <T extends />; const r = a / b; ${CALL};`, 1],
+ // A member named by a number: `1e-5` is ONE token to the scanner, so a type that has one for a name, then a string that holds the closing tag and the call, is a type, and `1e` and a `-` are two names and a sign in the text of an element.
+ ['an interface with a call signature with no return type, and a member named `1e-5` whose type is a string that holds the closing tag and the call', `interface P { <U>(x); 1e-5: '</U>;${CALL};//'; }`, 0],
+ ['an element whose text starts with a parenthesis and holds the same text up to the closing tag, then the call', `return <U>(x); 1e-5: '</U>;${CALL};//'`, 1],
+ // A nested element in a default value: its text is JSX text, which has no comment or string in it, and code goes on after its closing tag. Taken for code, `x // y</b> +` is a comment up to the end of its line, and the `/` on the
+ // next line a division; and `<b>'x</b> + '` is a string, which hides the quote that opens the string that holds the closing tag and the call.
+ ['an interface with a call signature with no return type, and a later member whose default holds a nested element with a `//` in its text, an operator, and on the next line a regex that holds the closing tag and the call', `interface P { <U>(x); m(a = <b>x // y</b> +\n/[</U>;${CALL}//]/): void }`, 0],
+ ['an element whose text starts with a parenthesis and holds the same text up to the closing tag, then the call', `return <U>(x); m(a = <b>x // y</b> +\n/[</U>;${CALL};//]/): void`, 1],
+ ['an interface with a call signature with no return type, and a later member whose default holds a nested element with a quote in its text, and a string that holds the closing tag and the call', `interface P { <U>(x); m(a = <b>'x</b> + '</U>;${CALL};//'): void }`, 0],
+ ['an element whose text starts with a parenthesis and holds the same text up to the closing tag, then the call', `return <U>(x); m(a = <b>'x</b> + '</U>;${CALL};//'): void`, 1],
+ ['an interface with a call signature with no return type, and a later member whose default holds a nested element with a `//` in its text, an operator, and a template that holds the closing tag and the call', `interface P { <U>(x); m(a = <b>x // y</b> + \`\n</U>;${CALL};//\`): void }`, 0],
+ ['an element whose text starts with a parenthesis and holds the same text up to the closing tag, then the call', `return <U>(x); m(a = <b>x // y</b> + \`\n</U>;${CALL};//\`): void`, 1],
+ // A nested tag that a type reads as code although its second word is no `extends`: the type parameters of a signature with a modifier (`<public V>`), a comparison with a keyword in it (`a <b in c> d`), the type arguments of a name with a type
+ // operator in them (`Array<keyof X>`), an empty list of type parameters or type arguments (`<>(y)`, `f(x)<> || …`). The tag is an element's, to the reading that takes the head for one, whose closing tag is in the string after it.
+ ['an interface with a call signature with no return type, a signature whose type parameters start with a modifier, and a string that holds the closing tag and the call', `interface P { <U>(x); <public V>(y): '</public>'; q: '</U>;${CALL};//'; }`, 0],
+ ['an element whose text starts with a parenthesis and holds an element named `public`, then the call', `return <U>(x); <public V>(y): '</public>'; q: '</U>;${CALL};//'`, 1],
+ ['an interface with a call signature with no return type, and a member whose default compares with a keyword in the tag, and a string that holds the closing tag and the call', `interface P { <U>(x); m(p = a <b in c> '</b>' + '</U>;${CALL};//'): void }`, 0],
+ ['an element whose text starts with a parenthesis and holds an element with an attribute named `in`, then the call', `return <U>(x); m(p = a <b in c> '</b>' + '</U>;${CALL};//'): void`, 1],
+ ['an interface with a call signature with no return type, and a member whose type arguments start with a type operator, and a string that holds the closing tag and the call', `interface P { <U>(x); m: Array<keyof X> = '</keyof>' + '</U>;${CALL};//'; }`, 0],
+ ['an element whose text starts with a parenthesis and holds an element named `keyof`, then the call', `return <U>(x); m: Array<keyof X> = '</keyof>' + '</U>;${CALL};//'`, 1],
+ ['an interface with a call signature with no return type, a signature with an empty list of type parameters, and a string that holds the closing tag and the call', `interface P { <U>(x); <>(y): '</>'; q: '</U>;${CALL};//'; }`, 0],
+ ['an element whose text starts with a parenthesis and holds a fragment, then the call', `return <U>(x); <>(y): '</>'; q: '</U>;${CALL};//'`, 1],
+ ['an interface with a call signature with no return type, and a member whose default has an empty list of type arguments after a call, and a string that holds the closing tag and the call', `interface P { <U>(x); m(p = f(x)<> || '</>' + '</U>;${CALL};//'): void }`, 0],
+ ['an element whose text starts with a parenthesis and holds a fragment, then the call', `return <U>(x); m(p = f(x)<> || '</>' + '</U>;${CALL};//'): void`, 1],
+ // Two comments on one line, each opened in the text of its own nested element, end at the same line break: both are places where the type's reading and the element's differ.
+ ['an interface with a call signature with no return type, and a member whose default holds two nested elements with a `//` in their text, and a template that holds the closing tag and the call', `interface P { <U>(x); m(a = <b>//</b> - <i>//</i> ?? \`\n</U>;${CALL};//\`): void }`, 0],
+ ['an element whose text starts with a parenthesis and holds the same text up to the closing tag, then the call', `return <U>(x); m(a = <b>//</b> - <i>//</i> ?? \`\n</U>;${CALL};//\`): void`, 1],
+ // A `/` on the line after a comment that stands behind an open `[` or an initializer's `=` may begin a regex that a computed name, a default or an initializer holds, and the closing tag of the head is inside it. The base takes the
+ // last word of the comment for the token before the `/`, and resolves the element.
+ ['an interface with a call signature with no return type, and a computed name whose regex follows a comment behind an open bracket and holds the closing tag and the call', `interface P { <U>(x); [ // note\n/[</U>;${CALL};//]/]: string }`, 0],
+ ['an element whose text starts with a parenthesis and holds the same text up to the closing tag, then the call', `return <U>(x); [ // note\n/[</U>;${CALL};//]/]: string`, 1],
+ ['an interface with a call signature with no return type, and an initializer whose regex follows a comment behind its `=` and holds the closing tag and the call', `interface P { <U>(x); m: A = // note\n/[</U>;${CALL};//]/ }`, 0],
+ ['an element whose text starts with a parenthesis and holds the same text up to the closing tag, then the call', `return <U>(x); m: A = // note\n/[</U>;${CALL};//]/`, 1],
+ // The other lines that end in an open bracket, an `=` or an operator after a comment, where a member of a type may begin at the head: none is told from the members of a type by its text, and each is a pair. (Where no member of
+ // a type begins — after an `=`, a `(`, a `[`, a `:` or an `=>` — the element is the only reading and these are certain.)
+ ['an interface with a call signature with no return type, and a method whose default has a regex on the line after a comment behind its `=`, which holds the closing tag and the call', `interface P { <U>(x); f(a = // note\n/[</U>;${CALL};//]/): void }`, 0],
+ ['an element whose text starts with a parenthesis and holds the same text up to the closing tag, then the call', `return <U>(x); f(a = // note\n/[</U>;\n${CALL};//]/): void`, 1],
+ ['an interface with a call signature with no return type, and an optional member whose initializer is a regex on the line after a comment behind its `=`', `interface P { <U>(x); m? = // note\n/[</U>;${CALL};//]/ }`, 0],
+ ['an element whose text starts with a parenthesis and holds the same text up to the closing tag, then the call', `return <U>(x); m? = // note\n/[</U>;\n${CALL};//]/`, 1],
+ ['an interface with a call signature with no return type, and a computed name that is an assignment, with a regex on the line after a comment behind its `=`', `interface P { <U>(x); [ x = // note\n/[</U>;${CALL};//]/]: string }`, 0],
+ ['an element whose text starts with a parenthesis and holds the same text up to the closing tag, then the call', `return <U>(x); [ x = // note\n/[</U>;\n${CALL};//]/]: string`, 1],
+ ['an interface with a call signature with no return type, and an initializer with an operator before a comment, and a regex on the next line', `interface P { <U>(x); m: A = b + // note\n/[</U>;${CALL};//]/ }`, 0],
+ ['an element whose text starts with a parenthesis and holds the same text up to the closing tag, then the call', `return <U>(x); m: A = b + // note\n/[</U>;\n${CALL};//]/`, 1],
+ // Where a member of a type may begin at the head, the head is not told from a call signature by what stands before it: `return <U>(x)` is a method named `return`, and `m? <U>(x)` a method with an optional mark. After an `=` or a
+ // `(` none begins and the element is read for certain; these two stay a guess, which is why NO_MEMBER_BEFORE has neither a keyword nor a `?`.
+ ['an interface with a method named `return` that has type parameters and no return type, and a string that holds the closing tag and the call', `interface P { return <U>(x); a: '</U>;${CALL};//'; }`, 0],
+ ['an element returned, whose text starts with a parenthesis and holds the same text up to the closing tag, then the call', `return <U>(x); a: '</U>;${CALL};//'`, 1],
+ ['an interface with an optional method that has type parameters and no return type, and a string that holds the closing tag and the call', `interface P { m? <U>(x); a: '</U> : null; ${CALL};//'; }`, 0],
+ ['an element in a conditional, whose text starts with a parenthesis and holds the same text up to the closing tag, then the call', `const el = c ? <U>(x); a: '</U> : null; ${CALL};//'`, 1],
+ // A tag with a line break before the `=` of its attribute: in a type it is an initializer that ends at the break and a member with an initializer of its own, and the string after it holds the closing tag and the call; in the
+ // element it is an element with an attribute, whose closing tag is in what is a string to the type.
+ ['an interface with a call signature with no return type, and an initializer that compares with a tag whose `=` is on a line of its own, and a string that holds the closing tag and the call', `interface P { <U>(x); m: A = x <a\nhref\n="/x"> '</a>' + '</U>;${CALL};//'; }`, 0],
+ ['an element whose text starts with a parenthesis and holds an element with an attribute on three lines, then the call', `return <U>(x); m: A = x <a\nhref\n="/x"> '</a>' + '</U>;${CALL};//'`, 1],
+ ['an interface with a call signature with no return type, and an initializer that compares with a tag whose valued `get` is on a line of its own', `interface P { <U>(x); m: A = x <a\nget="/x"> '</a>' + '</U>;${CALL};//'; }`, 0],
+ ['an element whose text starts with a parenthesis and holds an element with an attribute named `get` on its own line, then the call', `return <U>(x); m: A = x <a\nget="/x"> '</a>' + '</U>;${CALL};//'`, 1],
+ // A fragment after an operand and a line comment that ends in any character: the operand is what stands before the comment, and `<>` is an empty list of type arguments after it.
+ ['an interface with a call signature with no return type, and a default whose operand is followed by a line comment that ends in a colon, and `<>` on the next line', `interface P { <U>(x); m(p = f // note:\n<> || '</>' + '</U>;${CALL};//'): void }`, 0],
+ ['an element whose text starts with a parenthesis and holds a fragment after the comment, then the call', `return <U>(x); m(p = f // note:\n<> || '</>' + '</U>;${CALL};//'): void`, 1],
+ ['an interface with a call signature with no return type, and a default whose operand is a number that ends in a dot, and `<>` after it', `interface P { <U>(x); m(p = 1.<> || '</>' + '</U>;${CALL};//'): void }`, 0],
+ ['an element whose text starts with a parenthesis and holds a fragment after a number, then the call', `return <U>(x); m(p = 1.<> || '</>' + '</U>;${CALL};//'): void`, 1],
+ // An import type has no line-break rule before its `(`, and a `(` on the next line after any other type begins a call signature: `typeof import` and a line break, then the path that holds the closing tag and the call.
+ ['an interface with a call signature with no return type, and a member of type `typeof import`, a line break, and a path that holds the closing tag and the call', `interface P { <U>(x); m: typeof import\n('</U>;${CALL};//') }`, 0],
+ ['an element whose text starts with a parenthesis and holds the same text up to the closing tag, then the call', `return <U>(x); m: typeof import\n('</U>;${CALL};//')`, 1],
+ // After `get` or `set` a `[` begins an accessor's computed name, an expression: `[a, /x/]` is a comma expression with a regex in it, which holds the closing tag and the call. Elsewhere it is an index signature.
+ ['an interface with a call signature with no return type, and an accessor whose computed name is a comma expression with a regex that holds the closing tag and the call', `interface P { <U>(x); get [a, /[</U>;${CALL};//]/](): string }`, 0],
+ ['an element whose text starts with a parenthesis and holds the same text up to the closing tag, then the call', `return <U>(x); get [a, /[</U>;${CALL};//]/](): string`, 1],
],
},
{
@@ -182,6 +251,13 @@ const CERTAIN_SHAPES = [
['a quoted method signature in an object type', (page) => /^type literal in a (parameter|generic function type)/.test(page.group) && /^(['"])(?:m|a\\'b)\1\(/.test(page.name)],
['a call or construct signature with no return type', (page) => /^type literal in a generic function type|^interface member|^type literal member|^class implements|^type literal in a parameter/.test(page.group) && SIGNATURE_MEMBERS.includes(page.name)],
['an element whose text starts with a parenthesis', (page) => page.group === 'parenthesised element' && !HIDING_ELEMENTS.includes(page.element) && !INITIALIZER_ELEMENTS.includes(page.element)],
+ ['an element whose text starts with a parenthesis and holds a comment, a template or a regex that is open at its closing tag, after an `=`, a `(`, a `[`, a `:` or an `=>`, where no member of a type begins', (page) => page.group === 'parenthesised element' && page.member === false && HIDING_ELEMENTS.includes(page.element)],
+ ['an element whose text starts with a parenthesis, a separator and a line that ends in an open `[`, an initializer\'s `=` or an operator after a `//`, and a line that starts with a `/`, where no member of a type begins', (page) => page.group === 'parenthesised element' && page.member === false && PROSE_OPEN_ELEMENTS.includes(page.element)],
+ ['an element whose text starts with a parenthesis, a separator, a line with a `//` in it — a URL, a label and a URL, a name and a note — and a line that starts with a `/`', (page) => page.group === 'parenthesised element' && PROSE_ELEMENTS.includes(page.element)],
+ ['an element whose text starts with a parenthesis, a separator, a line with a `//` in it that begins with a bracket, a quote, a tag or an operator, ends in a postfix `!`, a call or an index, has a number with a `.` or an exponent sign, or starts with a modifier, and a line that starts with a `/`', (page) => page.group === 'parenthesised element' && SHAPED_PROSE_ELEMENTS.includes(page.element)],
+ ['a label and a type that fails at its second token (a number and a word, an object type that is none, `new`, `import`) or an `=` before a closing tag', (page) => page.group === 'parenthesised element' && FAILING_LIST_ELEMENTS.includes(page.element)],
+ ['a default whose first token is a regex or an element, a division of a name or a number, or a template with no `${`', (page) => page.group === 'parenthesised element' && EXACT_INITIALIZER_ELEMENTS.includes(page.element)],
+ ['an element whose first attribute is `extends` and that closes at once, where no `/` closes a regex on its line', (page) => page.group === 'everyday' && /^const e[12] = /.test(page.name)],
];
test('valid pages: this lexer never reads the text of a call as a call, and refuses a page that compiles only in the recorded classes, naming its guess', (t) => {
@@ -195,6 +271,7 @@ test('valid pages: this lexer never reads the text of a call as a call, and refu
const unsound = [];
const silent = [];
const refusedAgain = [];
+ const regressed = [];
for (const page of validPages()) {
stats.pages += 1;
const source = parses(ts, page.code);
@@ -221,7 +298,10 @@ test('valid pages: this lexer never reads the text of a call as a call, and refu
if (base) {
const there = reading(base, page.code);
if (there.resolves) stats.baseResolved += 1;
- if (there.resolves && !here.resolves) stats.baseRegressions += 1;
+ if (there.resolves && !here.resolves) {
+ stats.baseRegressions += 1;
+ regressed.push(`${page.group} / ${JSON.stringify(page.name)} (${here.kind})`);
+ }
if (!there.resolves && here.resolves) stats.baseImprovements += 1;
if (parses(ts, decoyed).parseDiagnostics.length === 0 && !decoysIntact(reading(base, decoyed).deployed)) stats.baseDecoysRewritten += 1;
}
@@ -236,11 +316,14 @@ test('valid pages: this lexer never reads the text of a call as a call, and refu
assert.deepStrictEqual(silent.slice(0, 5), [], 'a valid page the lexer refuses with no guess to name');
assert.deepStrictEqual(unexplained.slice(0, 8), [], `${unexplained.length} valid pages are refused that belong to no recorded class`);
assert.deepStrictEqual([...met].filter(([, n]) => n === 0).map(([cls]) => cls.id), [], 'a recorded class that no page meets');
+ if (base) assert.deepStrictEqual(regressed.slice(0, 8), [], `${regressed.length} pages that the base resolves are refused here`);
// The net is not vacuous, and the lexer is precise: nearly every page that compiles is resolved.
assert.ok(stats.valid >= 25000, `only ${stats.valid} pages were valid`);
assert.ok(stats.resolved >= 0.96 * stats.valid, `only ${stats.resolved} of ${stats.valid} valid pages were resolved`);
if (base) {
- assert.ok(stats.baseDecoysRewritten >= 100 && stats.baseDecoysRewritten > stats.decoysRewritten, `the base rewrites ${stats.baseDecoysRewritten} decoys, this lexer ${stats.decoysRewritten}`);
+ // A base that misreads is what calibrates the net: it rewrites the data after the pages it reads wrong, and this lexer rewrites none of it. The previous release rewrites none of these decoys (see the head of this
+ // file), so there is nothing to calibrate against and the count is not demanded: the improvements are the comparison.
+ if (stats.baseDecoysRewritten > 0) assert.ok(stats.baseDecoysRewritten >= 100 && stats.baseDecoysRewritten > stats.decoysRewritten, `the base rewrites ${stats.baseDecoysRewritten} decoys, this lexer ${stats.decoysRewritten}`);
assert.ok(stats.baseImprovements >= 100, `${stats.baseImprovements} pages are resolved here and not by the base`);
}
});
@@ -270,3 +353,27 @@ test('valid pages: each recorded class is two programs with the same text, both
if (base && !baseRight) assert.ok(baseWrong >= 1, `${kind}: the base reads one of the pair wrong`);
}
});
+
+// The lines that end in an open `[`, an initializer's `=` after a `?` or a type, or an `=` or an operator in a parameter list, behind a `//` and a path on the next line, at a head where a member of a type may begin (`return`, `,`,
+// `;`, `{`, a `?`, `default`): the text could be the members of a type, a regex may begin at the path's `/`, and the closing tag may be inside it — both programs compile (TWO_WAY has the pairs). The page is refused after the guess and
+// nothing in it is rewritten. 2.13.0 resolves some of them: it takes the word that ends the comment for the token before the `/`, which reads the element's page right and the other program's page wrong, and the text alone does not tell
+// them apart. How many it resolves is reported. Where no member begins the same lines are the element for certain, and the corpus of the first test holds them (resolved, none lost).
+test('valid pages: a line that ends in an open bracket or an initializer, at a head where a member of a type may begin, is refused after a guess, and nothing is rewritten', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) return t.skip(SKIP);
+ const base = loadBase();
+ let valid = 0;
+ let baseResolved = 0;
+ const wrong = [];
+ for (const page of openLinePages()) {
+ const source = parses(ts, page.code);
+ if (source.parseDiagnostics.length > 0 || realCalls(ts, source) !== 1) continue;
+ valid += 1;
+ const here = reading(next, page.code);
+ if (here.resolves || here.kind !== 'generic' || here.deployed !== page.code) wrong.push(`${page.name}: ${here.kind}`);
+ if (base && reading(base, page.code).resolves) baseResolved += 1;
+ }
+ t.diagnostic(`${valid} valid pages with a line that ends in an open bracket or an initializer, at a head where a member may begin; the base resolves ${baseResolved} of them`);
+ assert.deepStrictEqual(wrong.slice(0, 5), [], 'a page that is resolved, or refused with another guess, or rewritten');
+ assert.ok(valid >= 50, `only ${valid} pages were valid`);
+});
diff --git a/plugins/model-apps/scripts/tests/validate-flags.test.js b/plugins/model-apps/scripts/tests/validate-flags.test.js
index c824bb748..8dbd9696d 100644
--- a/plugins/model-apps/scripts/tests/validate-flags.test.js
+++ b/plugins/model-apps/scripts/tests/validate-flags.test.js
@@ -4,6 +4,8 @@
const test = require('node:test');
const assert = require('node:assert');
const { execFileSync } = require('node:child_process');
+const fs = require('node:fs');
+const os = require('node:os');
const path = require('node:path');
const { validateFlags, parseArgs } = require('../lib/dataverse-auth.js');
@@ -12,6 +14,18 @@ const { nearestName } = require('../lib/nearest-name.js');
const PLUGIN = path.join(__dirname, '..', '..');
const script = (n) => path.join(PLUGIN, 'scripts', n);
const SPEC = path.join(PLUGIN, 'samples', 'app-spec.project-tracker.json');
+// A build opens its workspace — by default `.maker-workspace` beside the spec — and the SDK binds it to the first
+// environment that opens it. The spec here is a committed sample, so a run that used the default would leave a
+// workspace bound to the placeholder environment in `samples/`, where a later real build using that folder as its app
+// folder would be halted. These runs name a temporary one instead.
+const SAMPLES_WORKSPACE = path.join(PLUGIN, 'samples', '.maker-workspace');
+const workspaces = [];
+function tempWorkspace() {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'validate-flags-ws-'));
+ workspaces.push(dir);
+ return dir;
+}
+test.after(() => { for (const dir of workspaces) fs.rmSync(dir, { recursive: true, force: true }); });
function run(args) {
try {
@@ -83,7 +97,8 @@ test('nearestName declines a suggestion beyond a single edit', () => {
// --- End-to-end: the dangerous case this whole change exists for -------------------------------
test('build-model-app rejects a typo\'d phase selector instead of planning every phase', () => {
- const base = ['--env', 'https://contoso.crm.dynamics.com', '--spec', '@' + SPEC, '--no-live-plan'];
+ const existed = fs.existsSync(SAMPLES_WORKSPACE);
+ const base = ['--env', 'https://contoso.crm.dynamics.com', '--spec', '@' + SPEC, '--no-live-plan', '--workspace', tempWorkspace()];
const good = run([script('build-model-app.js'), ...base, '--stage', 'ui']);
assert.strictEqual(good.code, 0, good.stderr);
const planned = JSON.parse(good.stdout).planItems.length;
@@ -93,6 +108,7 @@ test('build-model-app rejects a typo\'d phase selector instead of planning every
assert.match(typo.stderr, /unknown flag\(s\): --stagee \(did you mean --stage\?\)/);
// The regression being pinned: before this guard the typo planned strictly MORE than --stage ui.
assert.ok(planned > 0 && planned < 9, `--stage ui should plan a subset, planned ${planned}`);
+ assert.strictEqual(fs.existsSync(SAMPLES_WORKSPACE), existed, 'the run left no workspace in the committed samples folder');
});
test('teardown-model-app rejects an unknown flag rather than ignoring it', () => {
@@ -108,7 +124,9 @@ test('verify-model-app rejects an unknown flag rather than ignoring it', () => {
});
test('a correct invocation still succeeds after the guard', () => {
- const r = run([script('build-model-app.js'), '--env', 'https://contoso.crm.dynamics.com', '--spec', '@' + SPEC, '--no-live-plan', '--stage', 'ui']);
+ const existed = fs.existsSync(SAMPLES_WORKSPACE);
+ const r = run([script('build-model-app.js'), '--env', 'https://contoso.crm.dynamics.com', '--spec', '@' + SPEC, '--no-live-plan', '--stage', 'ui', '--workspace', tempWorkspace()]);
assert.strictEqual(r.code, 0, r.stderr);
assert.strictEqual(JSON.parse(r.stdout).dryRun, true);
+ assert.strictEqual(fs.existsSync(SAMPLES_WORKSPACE), existed, 'the run left no workspace in the committed samples folder');
});
diff --git a/plugins/model-apps/scripts/tests/verify-model-app.test.js b/plugins/model-apps/scripts/tests/verify-model-app.test.js
index 442b39b96..5dad83f30 100644
--- a/plugins/model-apps/scripts/tests/verify-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/verify-model-app.test.js
@@ -303,6 +303,10 @@ function loadVerifyCli({ parseResult, validateResult = { ok: true }, verifyResul
const made = new Set();
const fakeFs = {
mkdirSync: (dir, opts) => { made.add(dir); events.push({ type: 'mkdirSync', dir, opts }); },
+ // The throwaway workspace verify's SDK works in: created by name, removed when the run ends. Recorded so a test
+ // can tell it from the app folder's workspace, which verify never creates or opens.
+ mkdtempSync: (prefix) => { const dir = `${prefix}x1y2z3`; made.add(dir); events.push({ type: 'mkdtempSync', dir }); return dir; },
+ rmSync: (dir, opts) => { events.push({ type: 'rmSync', dir, opts }); },
// The workspace check inspects the final component, then creates a missing directory and
// inspects it again. A double that only records mkdir would throw here and hide the call.
lstatSync: (dir) => {
@@ -480,16 +484,24 @@ test('verify CLI prints per-check status and aliases missing checks into emitRes
assert.match(stderr, /✗ verify FAIL — 1 missing \(1\/2 present\)/);
assert.strictEqual(emitted.ok, false);
assert.deepStrictEqual(emitted.payload.errors, ['view:new_ticket.Open Tickets']);
- assert.ok(harness.events.some((e) => e.type === 'mkdirSync' && /\\.test-workspace\\verify$/.test(e.dir)));
+ // `--workspace` names only where the build's baseline is read from: verify creates nothing there, and its SDK
+ // works in a throwaway workspace of its own, removed before the result is printed.
+ assert.ok(!harness.events.some((e) => e.type === 'mkdirSync' && /\.test-workspace/.test(e.dir)), 'the named workspace is not created');
assert.ok(harness.events.some((e) => e.type === 'initWorkspace'));
+ const sdkRoot = harness.events.find((e) => e.type === 'createMakerSdk').cfg.workspaceStorage.__mockWorkspaceRoot;
+ assert.doesNotMatch(sdkRoot, /\.test-workspace/, 'the SDK is not opened on the named workspace');
+ const removed = harness.events.findIndex((e) => e.type === 'rmSync' && e.dir === sdkRoot);
+ assert.ok(removed > -1, 'the throwaway workspace is removed');
+ assert.ok(removed < harness.events.findIndex((e) => e.type === 'emitResult'), 'before emitResult ends the process');
});
-test('verify CLI accepts a positional spec, uses the default workspace, and prints PASS', async () => {
+test('verify CLI accepts a positional spec, leaves the default workspace alone, and prints PASS', async () => {
// Build the path with `path.join` rather than a hard-coded `D:\...` literal: the CLI derives the
// default workspace via path.join, so on a POSIX runner it produces `samples/.maker-workspace`
// and a backslash-anchored assertion could never match (this test failed on every non-Windows CI
// runner for that reason, not because the CLI was wrong).
const specPath = path.join(__dirname, '..', '..', 'samples', 'app-spec.support-desk.json');
+ const defaultWorkspace = path.join(__dirname, '..', '..', 'samples', '.maker-workspace');
const harness = loadVerifyCli({
parseResult: { positional: [specPath], flags: { env: 'https://org.example' } },
verifyResult: {
@@ -506,7 +518,11 @@ test('verify CLI accepts a positional spec, uses the default workspace, and prin
assert.match(stderr, /✓ verify PASS \(1\/1 present\)/);
assert.strictEqual(emitted.ok, true);
assert.deepStrictEqual(emitted.payload.missing, []);
- assert.ok(harness.events.some((e) => e.type === 'createMakerSdk' && e.cfg.workspaceStorage.__mockWorkspaceRoot === path.join(__dirname, '..', '..', 'samples', '.maker-workspace')));
+ // The default workspace is the build's, and belongs to the environment it was first opened for: verify neither
+ // opens it for its SDK nor creates it (a read-only run must not bind a folder that has no workspace yet).
+ const sdkRoots = harness.events.filter((e) => e.type === 'createMakerSdk').map((e) => e.cfg.workspaceStorage.__mockWorkspaceRoot);
+ assert.ok(sdkRoots.length >= 1 && sdkRoots.every((root) => root !== defaultWorkspace && path.dirname(root) === os.tmpdir()), `the SDK works in a throwaway workspace: ${JSON.stringify(sdkRoots)}`);
+ 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 () => {
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.js
new file mode 100644
index 000000000..60500f90b
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/verify-page-code-batch.test.js
@@ -0,0 +1,259 @@
+'use strict';
+
+// Verify reads the code of the pages whose navigation it checks. It ran `pac model genpage download` once per
+// page — a process start, an auth and a round trip each. A reader that can (`pageCodes`) now downloads the pages
+// together, and the page reads begin with the pass instead of after every other check. These tests count pac
+// runs and prove each page is still reported exactly as it was.
+
+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 { readerFor } = require('../verify-model-app.js');
+const { verifySpec } = require('../lib/verify-spec.js');
+const { makeGenpageCli } = require('../lib/genpage-cli.js');
+const { instrument } = require('./helpers/read-probe.js');
+
+const pid = (n) => `${String(n).padStart(8, '0')}-0000-4000-8000-0000000000aa`;
+const source = (id) => `// source of ${String(id).toLowerCase()}\n`;
+const NAV = (id) => `Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "${id}", data: {} });`;
+
+// --- the reader ------------------------------------------------------------------------------------
+
+const stubSdk = () => ({
+ queryRecords: async (set) => (set === 'appmodule' ? [{ appmoduleid: 'app-uuid-1', appmoduleidunique: 'uid-1' }] : []),
+ findTables: async () => [],
+ findColumns: async () => [],
+});
+
+// Stands in for `pac model genpage download`: writes <outDir>/<dirName(id)>/page.tsx for each id it is given.
+function fakeGenpageCli({ dirName = (id) => id, omitInBatch = new Set(), failBatch = false, failIds = new Set(), extraDirs = {} } = {}) {
+ const runs = [];
+ return {
+ runs,
+ enumerateEnv: async () => ({ ok: true, ids: [] }),
+ download: async ({ outputDir, pageIds }) => {
+ runs.push([...pageIds]);
+ if (failBatch && pageIds.length > 1) throw new Error('pac genpage download failed: the batch was refused');
+ const bad = pageIds.find((id) => failIds.has(String(id).toLowerCase()));
+ if (bad) throw new Error(`pac genpage download failed: page ${bad} was not found`);
+ for (const id of pageIds) {
+ if (pageIds.length > 1 && omitInBatch.has(String(id).toLowerCase())) continue;
+ fs.mkdirSync(path.join(outputDir, dirName(id)), { recursive: true });
+ fs.writeFileSync(path.join(outputDir, dirName(id), 'page.tsx'), source(id), 'utf8');
+ }
+ for (const [dir, text] of Object.entries(extraDirs)) {
+ fs.mkdirSync(path.join(outputDir, dir), { recursive: true });
+ fs.writeFileSync(path.join(outputDir, dir, 'page.tsx'), text, 'utf8');
+ }
+ return true;
+ },
+ };
+}
+
+const readerWith = (genpageCli) => readerFor(stubSdk(), 'contoso_app', { genpageCli, workspaceDir: os.tmpdir() });
+
+test('the code of several pages comes from ONE pac run, each page answered with its own code', async () => {
+ const cli = fakeGenpageCli();
+ const reader = readerWith(cli);
+ const ids = [1, 2, 3, 4, 5].map(pid);
+ const answers = await reader.pageCodes(ids);
+ assert.deepStrictEqual(cli.runs, [ids], 'one download holding every id, in order (five before)');
+ assert.deepStrictEqual([...answers.keys()], ids);
+ const single = readerWith(fakeGenpageCli());
+ for (const id of ids) {
+ assert.deepStrictEqual(answers.get(id), { code: source(id) });
+ assert.strictEqual(answers.get(id).code, await single.pageCode(id), 'byte-for-byte the code the one-page reader returns');
+ }
+});
+
+test('a long list goes in chunks of 25 ids — one run per chunk, no id in two runs', async () => {
+ for (const [count, shape] of [[25, [25]], [26, [25, 1]], [60, [25, 25, 10]]]) {
+ const cli = fakeGenpageCli();
+ const ids = Array.from({ length: count }, (_, n) => pid(n + 1));
+ const answers = await readerWith(cli).pageCodes(ids);
+ assert.deepStrictEqual(cli.runs.map((run) => run.length), shape, `${count} ids`);
+ assert.deepStrictEqual(cli.runs.flat(), ids, `${count} ids: every id once, in order`);
+ assert.strictEqual(answers.size, count);
+ for (const id of ids) assert.deepStrictEqual(answers.get(id), { code: source(id) });
+ }
+});
+
+test('a page is found by its own directory name, whatever the case, and never from another page\'s files', async () => {
+ const cli = fakeGenpageCli({ dirName: (id) => id.toUpperCase(), extraDirs: { 'not-a-requested-page': '// stray code' } });
+ const ids = [1, 2, 3].map(pid);
+ const answers = await readerWith(cli).pageCodes(ids);
+ assert.strictEqual(cli.runs.length, 1);
+ for (const id of ids) assert.deepStrictEqual(answers.get(id), { code: source(id) });
+ assert.ok([...answers.values()].every((a) => !/stray/.test(a.code)), 'a directory nobody asked for is nobody\'s code');
+});
+
+test('a page the successful batch left no directory for is asked for by itself, as before', async () => {
+ const missing = pid(3);
+ const cli = fakeGenpageCli({ omitInBatch: new Set([missing]) });
+ const answers = await readerWith(cli).pageCodes([pid(1), pid(2), missing, pid(4)]);
+ assert.deepStrictEqual(cli.runs, [[pid(1), pid(2), missing, pid(4)], [missing]]);
+ assert.deepStrictEqual(answers.get(missing), { code: source(missing) });
+ assert.deepStrictEqual(answers.get(pid(4)), { code: source(pid(4)) });
+});
+
+test('a batch pac refuses falls back to one run per page — a bad page costs its own miss, not its neighbours\'', async () => {
+ const bad = pid(2);
+ const cli = fakeGenpageCli({ failBatch: true, failIds: new Set([bad]) });
+ const reader = readerWith(cli);
+ const answers = await reader.pageCodes([pid(1), bad, pid(3)]);
+ assert.deepStrictEqual(cli.runs, [[pid(1), bad, pid(3)], [pid(1)], [bad], [pid(3)]], 'the batch, then each page alone');
+ assert.deepStrictEqual(answers.get(pid(1)), { code: source(pid(1)) });
+ assert.deepStrictEqual(answers.get(pid(3)), { code: source(pid(3)) });
+ const alone = await reader.pageCode(bad).then(() => null, (e) => e);
+ assert.ok(answers.get(bad).error instanceof Error);
+ assert.strictEqual(answers.get(bad).error.message, alone.message, 'the miss carries what the one-page download throws');
+});
+
+test('pages already downloaded are not downloaded again, and a duplicate in the list is fetched once', async () => {
+ const cli = fakeGenpageCli();
+ const reader = readerWith(cli);
+ await reader.pageCode(pid(1));
+ const answers = await reader.pageCodes([pid(1), pid(2), pid(3), pid(2).toUpperCase(), pid(3)]);
+ assert.deepStrictEqual(cli.runs, [[pid(1)], [pid(2), pid(3)]]);
+ assert.strictEqual(answers.size, 3);
+ await reader.pageCodes([pid(3), pid(2), pid(1)]);
+ assert.strictEqual(cli.runs.length, 2, 'asked again: answered from what was downloaded');
+});
+
+test('through the real genpage CLI wrapper, N pages are one `pac model genpage download --page-id a,b,c` run', async () => {
+ const downloads = [];
+ const run = async (args) => {
+ if (args[2] !== 'download') return { status: 0, stdout: '', stderr: '' };
+ downloads.push(args);
+ const outDir = args[args.indexOf('--output-directory') + 1];
+ for (const id of args[args.indexOf('--page-id') + 1].split(',')) {
+ fs.mkdirSync(path.join(outDir, id), { recursive: true });
+ fs.writeFileSync(path.join(outDir, id, 'page.tsx'), source(id), 'utf8');
+ }
+ return { status: 0, stdout: '', stderr: '' };
+ };
+ const genpageCli = makeGenpageCli('https://contoso.crm.dynamics.com', { run, sleep: async () => {} });
+ const ids = [1, 2, 3, 4].map(pid);
+ const answers = await readerWith(genpageCli).pageCodes(ids);
+ assert.strictEqual(downloads.length, 1, 'one pac run for four pages');
+ assert.strictEqual(downloads[0][downloads[0].indexOf('--page-id') + 1], ids.join(','));
+ assert.strictEqual(downloads[0][downloads[0].indexOf('--app-id') + 1], 'app-uuid-1');
+ for (const id of ids) assert.deepStrictEqual(answers.get(id), { code: source(id) });
+});
+
+// --- verify ----------------------------------------------------------------------------------------
+
+// Six pages; each navigates to the next except the page numbered 4 and the last. Page 2 is not in the app's
+// sitemap, so its code is never read. Page 3's deployed code navigates to a wrong id.
+function pagesSpec(count = 6, extraEntities = []) {
+ const pages = Array.from({ length: count }, (_, n) => ({
+ key: `p${n}`,
+ name: `Page ${n}`,
+ ...(n === 4 || n === count - 1 ? {} : { navigatesTo: [{ targetKey: `p${n + 1}` }] }),
+ source: { kind: 'tsx', codeFile: `p${n}.tsx` },
+ }));
+ return {
+ entities: [...extraEntities, { schemaName: 'contoso_item', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] }],
+ schemaVersion: 2,
+ pages,
+ appShell: { areas: [{ label: 'M', groups: [{ label: 'G', subAreas: pages.map((p) => ({ page: p.key, title: p.name })) }] }] },
+ };
+}
+
+function pageReader({ count = 6, batch = false, failing = {}, pageCodesThrows = false } = {}) {
+ const calls = { pageCode: [], pageCodes: [] };
+ const all = Array.from({ length: count }, (_, n) => pid(n));
+ const inSitemap = all.filter((id) => id !== pid(2));
+ const sitemap = `<SiteMap><Area><Group>${inSitemap.map((id, i) => `<SubArea Id="s${i}" GenPageId="${id}"/>`).join('')}</Group></Area></SiteMap>`;
+ const codeFor = (id) => {
+ const n = all.indexOf(String(id).toLowerCase());
+ return n === 3 ? NAV(pid(99)) : NAV(pid(n + 1));
+ };
+ const read = {
+ findTable: async () => ({ logicalName: 'contoso_item' }),
+ findColumns: async () => [],
+ queryRecords: async () => [],
+ sitemapXml: async () => sitemap,
+ sitemapPageIds: async () => inSitemap,
+ existenceIds: async () => all,
+ manifest: async () => ({ schemaVersion: 1, pages: all.map((id, n) => ({ key: `p${n}`, name: `Page ${n}`, pageId: id })) }),
+ pageCode: async (id) => {
+ calls.pageCode.push(id);
+ if (failing[id]) throw new Error(failing[id]);
+ return codeFor(id);
+ },
+ };
+ if (batch) {
+ read.pageCodes = async (ids) => {
+ calls.pageCodes.push([...ids]);
+ if (pageCodesThrows) throw new Error('the reader broke');
+ return new Map(ids.map((id) => [String(id).toLowerCase(), failing[id] ? { error: new Error(failing[id]) } : { code: codeFor(id) }]));
+ };
+ }
+ return { read, calls };
+}
+
+test('verify asks for the code of the pages it checks in one batch — same pages, same order, same report', async () => {
+ const perPage = pageReader();
+ const batched = pageReader({ batch: true });
+ const before = await verifySpec(pagesSpec(), perPage.read);
+ const after = await verifySpec(pagesSpec(), batched.read);
+ assert.deepStrictEqual(perPage.calls.pageCode, [pid(0), pid(1), pid(3)], 'one pac run per page before');
+ assert.deepStrictEqual(batched.calls.pageCodes, [[pid(0), pid(1), pid(3)]], 'one batch: deployed pages with navigation, once each, in spec order');
+ assert.deepStrictEqual(batched.calls.pageCode, [], 'and no per-page run');
+ assert.deepStrictEqual(after, before);
+ assert.ok(after.checks.some((c) => c.kind === 'page-nav' && c.present) && after.checks.some((c) => c.kind === 'page-nav' && !c.present), 'the fixture reports passes and failures');
+});
+
+test('a page whose code could not be downloaded is the same page-code miss with or without the batch', async () => {
+ const failing = { [pid(1)]: 'pac genpage download failed: page was not found' };
+ const before = await verifySpec(pagesSpec(), pageReader({ failing }).read);
+ const after = await verifySpec(pagesSpec(), pageReader({ batch: true, failing }).read);
+ assert.deepStrictEqual(after, before);
+ assert.deepStrictEqual(after.checks.filter((c) => c.kind === 'page-code').map((c) => [c.name, c.present, c.detail]), [['Page 1', false, 'pac genpage download failed: page was not found']]);
+});
+
+test('a reader whose pageCodes fails outright is asked page by page — the report is unchanged', async () => {
+ const before = await verifySpec(pagesSpec(), pageReader().read);
+ const broken = pageReader({ batch: true, pageCodesThrows: true });
+ const after = await verifySpec(pagesSpec(), broken.read);
+ assert.deepStrictEqual(after, before);
+ assert.deepStrictEqual(broken.calls.pageCode, [pid(0), pid(1), pid(3)]);
+});
+
+test('a single page with navigation is the one-page download — no batch', async () => {
+ const one = pageReader({ count: 2, batch: true });
+ const result = await verifySpec(pagesSpec(2), one.read);
+ assert.deepStrictEqual(one.calls.pageCodes, []);
+ assert.deepStrictEqual(one.calls.pageCode, [pid(0)]);
+ assert.ok(result.checks.some((c) => c.kind === 'page-nav'));
+});
+
+test('the page reads start with the pass, ahead of the other checks — and at their old place one read at a time', async () => {
+ const entities = Array.from({ length: 8 }, (_, n) => ({ schemaName: `new_e${n}`, columns: [{ schemaName: `new_e${n}_a` }] }));
+ const order = async (concurrency) => {
+ const { read } = pageReader({ batch: true });
+ const probe = instrument({ ...read, findColumns: async () => [] }, { latency: () => 2 });
+ await verifySpec(pagesSpec(6, entities), probe.read, { concurrency });
+ const names = probe.stats.calls.map((c) => c.name);
+ return { existence: names.indexOf('existenceIds'), lastEntityRead: names.lastIndexOf('findColumns') };
+ };
+ const overlapped = await order(4);
+ assert.ok(overlapped.existence < overlapped.lastEntityRead, `the pac listing started at read ${overlapped.existence}, before the entity checks were through (${overlapped.lastEntityRead})`);
+ const sequential = await order(1);
+ assert.ok(sequential.existence > sequential.lastEntityRead, 'one at a time it is made where the page checks come, after the entity checks');
+});
+
+test('a failed page-authority read ends the pass with the same error wherever it happened, and an earlier failure outranks it', async () => {
+ const boom = new Error('pac listing failed');
+ const failingListing = (extra = {}) => ({ ...pageReader({ batch: true }).read, existenceIds: async () => { throw boom; }, ...extra });
+ for (const concurrency of [1, 4]) {
+ await assert.rejects(verifySpec(pagesSpec(), failingListing(), { concurrency }), (e) => e === boom, `width ${concurrency}`);
+ }
+ const entityFails = failingListing({ findColumns: async () => { throw new Error('entity read failed'); } });
+ for (const concurrency of [1, 4]) {
+ await assert.rejects(verifySpec(pagesSpec(), entityFails, { concurrency }), /entity read failed/, `width ${concurrency}`);
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/verify-parallel-checks.test.js b/plugins/model-apps/scripts/tests/verify-parallel-checks.test.js
new file mode 100644
index 000000000..9054882fb
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/verify-parallel-checks.test.js
@@ -0,0 +1,660 @@
+'use strict';
+
+// Verify runs its independent reads side by side. These tests prove three things about that:
+// * the reads really overlap (and stay bounded);
+// * the report is the one the old one-at-a-time run produced, whichever read answers first;
+// * nothing is read twice because two checks happened to ask together, and a failure stays loud.
+// `concurrency: 1` is the old run (one read at a time, in the old order) and is the oracle.
+
+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 { verifySpec } = require('../lib/verify-spec.js');
+const { resolveRoleBusinessUnit } = require('../lib/sdk-build.js');
+const { readerFor } = require('../verify-model-app.js');
+const { SDK_ROLE_MARKER } = require('../lib/app-spec.js');
+const { turn, hash, instrument, callKeys } = require('./helpers/read-probe.js');
+
+// --- a spec and reader that reach most sections of verify ------------------------------------------
+
+const TABLES = ['new_t0', 'new_t1', 'new_t2', 'new_t3', 'new_t4'];
+const ROOT_BU = '00000000-0000-4000-8000-0000000000b1';
+const PAGE_OVERVIEW = '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8';
+const PAGE_DETAIL = '5c0a4889-45fd-46ea-91a8-ff876914d644';
+const formId = (table, which) => `${String(TABLES.indexOf(table) + 1).padStart(8, '0')}-0000-4000-8000-00000000000${which}`;
+const persona = (name, over = {}) => ({ persona: name, jobs: [{ name: 'work', privileges: [{ entity: 'new_t0', access: ['read'] }] }], ...over });
+
+function richSpec() {
+ return {
+ solution: { uniqueName: 'verify_checks', publisherPrefix: 'new' },
+ app: { name: 'Verify Checks', uniqueName: 'new_verifychecks' },
+ schemaVersion: 2,
+ entities: TABLES.map((t) => ({ schemaName: t, columns: [{ schemaName: `${t}_a` }, { schemaName: `${t}_b` }] })),
+ views: TABLES.map((t) => ({ entity: t, name: `Active ${t}` })),
+ charts: TABLES.slice(0, 3).map((t) => ({ entity: t, name: `Chart ${t}` })),
+ forms: TABLES.flatMap((t) => [
+ { entity: t, name: `${t} Main`, formType: 'Main' },
+ { entity: t, name: `${t} Alt`, formType: 'Main' },
+ ]),
+ relationships: [
+ { type: 'OneToMany', referenced: 'new_t0', referencing: 'new_t1', lookup: { schemaName: 'new_T0Id' } },
+ { type: 'OneToMany', referenced: 'new_t0', referencing: 'new_t2', lookup: { schemaName: 'new_T0Id' } },
+ ],
+ commands: [
+ { entity: 'new_t0', label: 'Go', library: 'a.js', function: 'A.go' },
+ { entity: 'new_t2', label: 'Go', library: 'b.js', function: 'B.go' },
+ ],
+ businessRules: [{ entity: 'new_t0', name: 'Rule A' }, { entity: 'new_t1', name: 'Rule B' }],
+ personas: [persona('Agent'), persona('Dispatcher'), persona('Auditor', { appAccess: false })],
+ pages: [
+ { key: 'overview', name: 'Overview', navigatesTo: [{ targetKey: 'detail' }], source: { kind: 'tsx', codeFile: 'overview.tsx' } },
+ { key: 'detail', name: 'Detail', source: { kind: 'tsx', codeFile: 'detail.tsx' } },
+ ],
+ appShell: {
+ areas: [{
+ label: 'Main',
+ groups: [{
+ label: 'G',
+ subAreas: [
+ ...TABLES.map((t) => ({ entity: t, title: t })),
+ { page: 'overview', title: 'Overview' },
+ { page: 'detail', title: 'Detail' },
+ ],
+ }],
+ }],
+ },
+ };
+}
+
+function richReader() {
+ const sitemap = '<SiteMap><Area><Group>'
+ + TABLES.slice(0, 3).map((t) => `<SubArea Entity="${t}"/>`).join('')
+ + `<SubArea Id="s1" GenPageId="${PAGE_OVERVIEW}"/><SubArea Id="s2" GenPageId="${PAGE_DETAIL}"/></Group></Area></SiteMap>`;
+ return {
+ findTable: async (logical) => (logical === 'new_t3' ? null : { logicalName: logical }),
+ findColumns: async (logical) => [{ logicalName: `${logical}_a` }],
+ queryRecords: async (set, opts = {}) => {
+ const filter = String((opts && opts.filter) || '');
+ if (set === 'savedquery') return /returnedtypecode eq 'new_t3'/.test(filter) ? [] : [{ savedqueryid: 'sq' }];
+ if (set === 'savedqueryvisualization') return /'new_t2'/.test(filter) ? [] : [{ savedqueryvisualizationid: 'sv' }];
+ if (set === 'businessunit') return [{ businessunitid: ROOT_BU }];
+ if (set === 'role') {
+ // A role is found only in the root business unit, as in a real environment.
+ if (!filter.includes(`_businessunitid_value eq ${ROOT_BU}`)) return [];
+ const name = /name eq '([^']+)'/.exec(filter);
+ return name ? [{ roleid: `role-${name[1]}`, description: SDK_ROLE_MARKER, ismanaged: false }] : [];
+ }
+ if (set === 'workflow') return /Rule A/.test(filter) ? [{ workflowid: 'wf', statecode: 1 }] : [];
+ if (set === 'systemform') {
+ const byId = /formid eq ([0-9a-fA-F-]{36})/.exec(filter);
+ if (byId) return [{ formid: byId[1], name: 'form', objecttypecode: 'x', type: 2 }];
+ const entity = /objecttypecode eq '([^']+)'/.exec(filter);
+ const name = /name eq '([^']+)'/.exec(filter);
+ if (!entity || !name) return [];
+ const which = / Main$/.test(name[1].replace(/''/g, "'")) ? 1 : 2;
+ return [{ formid: formId(entity[1], which), name: name[1], objecttypecode: entity[1], type: 2 }];
+ }
+ return [];
+ },
+ formDefaultState: async (_entity, id) => ({ isDefault: String(id).endsWith('1') }),
+ formTopology: async (_entity, id) => `<form><DisplayConditions Order="${String(id).endsWith('1') ? 0 : 1}" FallbackForm="true"><Everyone /></DisplayConditions><tabs /></form>`,
+ servedMainForms: async (entity) => [
+ { id: formId(entity, 1), name: `${entity} Main` },
+ { id: formId(entity, 2), name: `${entity} Alt` },
+ ],
+ sitemapXml: async () => sitemap,
+ entityRelationships: async () => [],
+ commandBar: async (entity) => entity !== 'new_t2',
+ appRoleIds: async () => ({ ok: true, roleIds: ['role-Agent'] }),
+ // Every persona holds the same table privilege, so the same two privilege sets are asked for by all of them.
+ entityPrivileges: async (entity) => [{ Name: `prvRead${entity}`, PrivilegeId: `${entity}-read`, PrivilegeType: 'Read' }],
+ rolePrivileges: async () => [{ privilegeId: 'new_t0-read', depth: 'Global' }, { privilegeId: 'appmodule-read', depth: 'Global' }],
+ appEntityComponents: async () => ({ ok: true, present: TABLES.slice(0, 2) }),
+ sitemapPageIds: async () => [PAGE_OVERVIEW, PAGE_DETAIL],
+ existenceIds: async () => [PAGE_OVERVIEW, PAGE_DETAIL],
+ manifest: async () => ({ schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: PAGE_OVERVIEW }, { key: 'detail', name: 'Detail', pageId: PAGE_DETAIL }] }),
+ pageCode: async (id) => (String(id).toLowerCase() === PAGE_OVERVIEW ? `Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "${PAGE_DETAIL}", data: {} });` : ''),
+ };
+}
+
+const runRich = (opts, instrumentation) => {
+ const probe = instrument(richReader(), instrumentation);
+ return verifySpec(richSpec(), probe.read, opts).then((result) => ({ result, stats: probe.stats }));
+};
+
+test('the fixture reaches most of verify and reports a mix of passes and failures', async () => {
+ const { result } = await runRich({ concurrency: 1 }, { latency: () => 0 });
+ const kinds = new Set(result.checks.map((c) => c.kind));
+ assert.ok(result.checks.length >= 60, `${result.checks.length} checks`);
+ for (const kind of ['entity', 'column', 'view', 'chart', 'form', 'form-default', 'form-default-unique', 'form-order', 'form-order-served', 'relationship', 'command', 'business-rule', 'role', 'role-privileges', 'app-role', 'subarea', 'app-table-component', 'page', 'page-subarea']) {
+ assert.ok(kinds.has(kind), `the fixture should produce '${kind}' checks (got ${[...kinds].join(', ')})`);
+ }
+ assert.ok(result.checks.some((c) => c.present) && result.missing.length > 0, 'some checks pass and some fail');
+});
+
+test('independent reads overlap — up to 4 at a time, never more — and one at a time when asked', async () => {
+ const wide = await runRich(undefined, { latency: () => 2 });
+ assert.strictEqual(wide.stats.maxInFlight, 4, 'the default overlaps four reads');
+ const eight = await runRich({ concurrency: 8 }, { latency: () => 2 });
+ assert.ok(eight.stats.maxInFlight > 4 && eight.stats.maxInFlight <= 8, `width 8 overlapped ${eight.stats.maxInFlight}`);
+ const two = await runRich({ concurrency: 2 }, { latency: () => 2 });
+ assert.strictEqual(two.stats.maxInFlight, 2);
+ const one = await runRich({ concurrency: 1 }, { latency: () => 2 });
+ assert.strictEqual(one.stats.maxInFlight, 1, 'concurrency 1 is the old one-at-a-time run');
+});
+
+test('the overlapped run reads exactly what the one-at-a-time run reads and reports the same', async () => {
+ const sequential = await runRich({ concurrency: 1 }, { latency: () => 0 });
+ const overlapped = await runRich(undefined, { latency: () => 1 });
+ assert.deepStrictEqual(callKeys(overlapped.stats), callKeys(sequential.stats), 'same reads, none added and none dropped');
+ assert.deepStrictEqual(overlapped.result, sequential.result, 'same report, in the same order');
+});
+
+test('the report does not depend on which read answers first (random latencies, several widths)', async () => {
+ const baseline = await runRich({ concurrency: 1 }, { latency: () => 0 });
+ for (const seed of [1, 2, 3, 4, 5, 6, 7, 8]) {
+ const latency = (call) => hash(`${seed}:${JSON.stringify([call.name, call.args])}`) % 5;
+ for (const concurrency of [2, 3, 4, 7]) {
+ const run = await runRich({ concurrency }, { latency });
+ assert.deepStrictEqual(run.result, baseline.result, `seed ${seed}, width ${concurrency}`);
+ assert.deepStrictEqual(callKeys(run.stats), callKeys(baseline.stats), `seed ${seed}, width ${concurrency}: same reads`);
+ }
+ }
+});
+
+test('the concurrency option must be a positive integer', async () => {
+ for (const bad of [0, -1, 1.5, '4', NaN, null]) {
+ await assert.rejects(runRich({ concurrency: bad }, { latency: () => 0 }), /verify concurrency must be a positive integer/, String(bad));
+ }
+ await assert.doesNotReject(runRich({ concurrency: undefined }, { latency: () => 0 }));
+});
+
+test('a read that fails ends the run — nothing starts after it — and the failure first in report order is the one thrown', async () => {
+ const entities = Array.from({ length: 12 }, (_, i) => ({ schemaName: `new_e${i}`, columns: [] }));
+ const spec = { entities, views: [], charts: [], forms: [], appShell: { areas: [] } };
+ const run = async (concurrency, failures) => {
+ const started = [];
+ let startedAtFirstFailure = null;
+ const read = {
+ findTable: async (logical) => ({ logicalName: logical }),
+ findColumns: async (logical) => {
+ started.push(logical);
+ const failure = failures[logical];
+ for (let turns = failure ? failure.turns : 1; turns > 0; turns--) await turn();
+ if (failure) {
+ if (startedAtFirstFailure === null) startedAtFirstFailure = started.length;
+ throw new Error(failure.message);
+ }
+ return [];
+ },
+ queryRecords: async () => [],
+ sitemapXml: async () => '',
+ };
+ const outcome = await verifySpec(spec, read, { concurrency }).then((result) => ({ result }), (error) => ({ error }));
+ return { ...outcome, started, startedAtFirstFailure };
+ };
+ // Table 5 fails at once; table 2, earlier in the report, fails a few turns later.
+ const failures = { new_e2: { turns: 8, message: 'boom e2' }, new_e5: { turns: 0, message: 'boom e5' } };
+
+ const oracle = await run(1, failures);
+ assert.strictEqual(oracle.error.message, 'boom e2', 'one at a time stops at the first failing table');
+ assert.deepStrictEqual(oracle.started, ['new_e0', 'new_e1', 'new_e2']);
+
+ const overlapped = await run(4, failures);
+ assert.strictEqual(overlapped.error.message, 'boom e2', 'the failure first in report order wins, as it does one at a time');
+ assert.strictEqual(overlapped.started.length, overlapped.startedAtFirstFailure, 'no read starts once one has failed');
+ assert.ok(overlapped.started.length < entities.length, 'the rest of the run was not started');
+});
+
+test('a failure in an earlier section outranks one in a later section that happened sooner', async () => {
+ const spec = { entities: [{ schemaName: 'new_e0', columns: [] }], views: [{ entity: 'new_e0', name: 'V' }], charts: [], forms: [], appShell: { areas: [] } };
+ const read = {
+ findTable: async (logical) => ({ logicalName: logical }),
+ findColumns: async () => { for (let i = 0; i < 6; i++) await turn(); throw new Error('entity read failed'); },
+ queryRecords: async () => { throw new Error('view read failed'); },
+ sitemapXml: async () => '',
+ };
+ for (const concurrency of [1, 4]) {
+ await assert.rejects(verifySpec(spec, read, { concurrency }), /entity read failed/, `width ${concurrency}`);
+ }
+});
+
+// The page checks' slow reads (a `pac` listing, about five seconds, with no timeout of its own) start with the pass. A pass
+// that fails must not wait for them: before the pass overlapped its reads, a failing first check threw at once, and a hung
+// `pac` could never turn that into a hang.
+const answersWithin = (promise, ms) => new Promise((resolve) => {
+ const timer = setTimeout(() => resolve({ waitedMs: ms }), ms);
+ promise.then((value) => { clearTimeout(timer); resolve({ value }); }, (error) => { clearTimeout(timer); resolve({ error }); });
+});
+
+test('a verify that fails on its first check does not wait for a page read that never answers', async () => {
+ const reader = {
+ ...richReader(),
+ findTable: async () => { throw new Error('the environment could not be read'); },
+ existenceIds: () => new Promise(() => {}),
+ };
+ const outcome = await answersWithin(verifySpec(richSpec(), reader, { concurrency: 4 }), 2000);
+ assert.ok(outcome.error, `the pass ended with the check's failure instead of waiting ${outcome.waitedMs} ms for the page read`);
+ assert.match(outcome.error.message, /the environment could not be read/);
+});
+
+test('a verify whose page check is waiting for a read that never answers still ends when an earlier check fails', async () => {
+ // The page check is listed late; it starts while an earlier table check is still waiting, and then waits on the pac
+ // listing that never answers. When the earlier check fails, the pass must neither wait for that listing nor lose the
+ // earlier check's error to it.
+ let failEarlier;
+ const earlier = new Promise((resolve, reject) => { failEarlier = () => reject(new Error('table new_t4 could not be read')); });
+ const base = richReader();
+ const sets = [];
+ const reader = {
+ ...base,
+ findTable: (logical) => (logical === 'new_t4' ? earlier : base.findTable(logical)),
+ queryRecords: async (set, opts) => { sets.push(set); return base.queryRecords(set, opts); },
+ existenceIds: () => new Promise(() => {}),
+ };
+ const pass = verifySpec(richSpec(), reader, { concurrency: 4 });
+ // Every task after the page check (the persona roles, say) has started: so has the page check, and it is waiting.
+ for (let i = 0; i < 200 && !sets.includes('role'); i += 1) await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.ok(sets.includes('role'), 'the pass got past the page check');
+ failEarlier();
+ const outcome = await answersWithin(pass, 2000);
+ assert.ok(outcome.error, `the pass ended with the earlier check's failure instead of waiting ${outcome.waitedMs} ms`);
+ assert.match(outcome.error.message, /table new_t4 could not be read/);
+});
+
+test('a page read that is merely slow is still waited for when nothing has failed', async () => {
+ let release;
+ const slow = new Promise((resolve) => { release = () => resolve([PAGE_OVERVIEW, PAGE_DETAIL]); });
+ const reader = { ...richReader(), existenceIds: () => slow };
+ const pass = verifySpec(richSpec(), reader, { concurrency: 4 });
+ const early = await answersWithin(pass, 150);
+ assert.ok(early.waitedMs, 'the report is not produced before the page checks have their answers');
+ release();
+ const result = await pass;
+ assert.ok(result.checks.some((c) => c.kind === 'page'), 'and once the listing answers, the page checks report');
+});
+
+// A check listed after the page check that fails: the persona check reads the reader's `appRoleIds` outside any guard (every
+// read there is guarded and reported as a finding), so a reader whose `appRoleIds` throws when it is looked up makes it fail.
+// A getter, so that it is the lookup that fails and the reader can still be copied.
+const laterCheckFails = (reader, onFail) => Object.defineProperty(reader, 'appRoleIds', { get() { onFail(); throw new Error('a later check failed'); } });
+
+test('a failure in a check listed AFTER the page check does not discard the page check\'s own failure: the earlier one in the report is the one thrown, as one at a time', async () => {
+ // A check listed after the page check fails while the page reads are still out, and the page reads then fail too: the page
+ // check's failure is the lower-numbered one, so it is the one the pass throws.
+ const base = richReader();
+ let open;
+ const gate = new Promise((resolve) => { open = resolve; });
+ let laterFailed = 0;
+ const reader = laterCheckFails({ ...base, existenceIds: async () => { await gate; throw new Error('pac could not list the pages'); } }, () => { laterFailed += 1; });
+ const pass = verifySpec(richSpec(), reader, { concurrency: 4 }).then(() => ({}), (error) => ({ error }));
+ for (let i = 0; i < 300 && !laterFailed; i += 1) await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.ok(laterFailed, 'a check listed after the page check has failed while the page reads are still out');
+ for (let i = 0; i < 30; i += 1) await turn();
+ open();
+ const outcome = await pass;
+ assert.match(outcome.error.message, /pac could not list the pages/);
+
+ const oracleReader = laterCheckFails({ ...base, existenceIds: async () => { throw new Error('pac could not list the pages'); } }, () => {});
+ const oracle = await verifySpec(richSpec(), oracleReader, { concurrency: 1 }).then(() => ({}), (error) => ({ error }));
+ assert.match(oracle.error.message, /pac could not list the pages/, 'one at a time reaches the page check first and throws its failure');
+});
+
+test('a failure in a check listed after the page check still waits for the page reads — and throws that failure when the page check itself passes', async () => {
+ const base = richReader();
+ let open;
+ const gate = new Promise((resolve) => { open = resolve; });
+ let laterFailed = 0;
+ let endCalls = 0;
+ const reader = laterCheckFails({ ...base, existenceIds: async () => { await gate; return [PAGE_OVERVIEW, PAGE_DETAIL]; }, endPageReads: async () => { endCalls += 1; } }, () => { laterFailed += 1; });
+ const pass = verifySpec(richSpec(), reader, { concurrency: 4 }).then(() => ({}), (error) => ({ error }));
+ for (let i = 0; i < 300 && !laterFailed; i += 1) await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.ok(laterFailed, 'the later check has failed');
+ const early = await answersWithin(pass, 100);
+ assert.ok(early.waitedMs, 'the pass is still waiting for the page reads: whether the page check fails is still open');
+ open();
+ const outcome = await pass;
+ assert.match(outcome.error.message, /a later check failed/);
+ assert.strictEqual(endCalls, 0, 'nothing was given up on, so there is nothing to end');
+});
+
+// --- ending what a pass gave up on ---------------------------------------------------------------------------
+// A pass that stops waiting for a page read leaves its pac run going — and, with a batch shim, the shim's process tree —
+// and the folder its download writes to. The verify CLI exits the moment the pass throws, so the reader is asked to end
+// them first and the pass waits for it.
+
+test('a pass that gave up on a page read asks the reader to end its page reads, and waits for that before it throws', async () => {
+ let started = 0;
+ let finished = 0;
+ const reader = {
+ ...richReader(),
+ findTable: async () => { throw new Error('the environment could not be read'); },
+ existenceIds: () => new Promise(() => {}),
+ endPageReads: async () => { started += 1; for (let i = 0; i < 25; i += 1) await turn(); finished += 1; },
+ };
+ const outcome = await answersWithin(verifySpec(richSpec(), reader, { concurrency: 4 }), 2000);
+ assert.match(outcome.error.message, /the environment could not be read/);
+ assert.strictEqual(started, 1, 'asked once');
+ assert.strictEqual(finished, 1, 'and the pass did not throw until the reader said it had ended them');
+});
+
+test('nothing the reader\'s endPageReads throws replaces the failure that ended the pass', async () => {
+ const reader = {
+ ...richReader(),
+ findTable: async () => { throw new Error('the environment could not be read'); },
+ existenceIds: () => new Promise(() => {}),
+ endPageReads: async () => { throw new Error('could not end the page reads'); },
+ };
+ const outcome = await answersWithin(verifySpec(richSpec(), reader, { concurrency: 4 }), 2000);
+ assert.match(outcome.error.message, /the environment could not be read/);
+});
+
+test('a pass that gave up on nothing does not end the reader\'s page reads — a reader may be used for another pass', async () => {
+ let ended = 0;
+ const reader = { ...richReader(), endPageReads: async () => { ended += 1; } };
+ await verifySpec(richSpec(), reader, { concurrency: 4 });
+ await verifySpec(richSpec(), reader, { concurrency: 1 });
+ assert.strictEqual(ended, 0);
+ // Nor one whose page reads had answered by the time another check failed.
+ const answered = { ...reader, findTable: async (logical) => { for (let i = 0; i < 400; i += 1) await turn(); throw new Error(`late failure for ${logical}`); } };
+ await assert.rejects(verifySpec(richSpec(), answered, { concurrency: 4 }), /late failure/);
+ assert.strictEqual(ended, 0, 'the page reads had answered: nothing was given up on');
+});
+
+// The reader that does the ending: it owns the pac client and the folders.
+function pageReader(genpageCli, options = {}) {
+ const sdk = { queryRecords: async (set) => (set === 'appmodule' ? [{ appmoduleid: 'app-1' }] : []), findTables: async () => [] };
+ return readerFor(sdk, 'new_app', { genpageCli, ...options });
+}
+
+test('endPageReads ends the downloads in flight, removes their folders before it answers, and starts nothing after it', async () => {
+ const folders = [];
+ let aborted = 0;
+ let failDownload;
+ const genpageCli = {
+ enumerateEnv: async () => ({ ok: true, ids: [] }),
+ download: ({ outputDir }) => { folders.push(outputDir); return new Promise((_, reject) => { failDownload = reject; }); },
+ // pac settles a moment after it is killed, so the reader has something to wait for.
+ abort: () => { aborted += 1; setTimeout(() => failDownload(new Error('pac was ended')), 30); },
+ };
+ const reader = pageReader(genpageCli);
+ const inFlight = reader.pageCode(PAGE_OVERVIEW).catch((error) => error);
+ for (let i = 0; i < 200 && !folders.length; i += 1) await turn();
+ assert.strictEqual(folders.length, 1, 'the download is out');
+ assert.ok(fs.existsSync(folders[0]), 'and its folder exists while pac runs');
+
+ await reader.endPageReads();
+ assert.strictEqual(aborted, 1, 'the pac client was told to end its runs');
+ assert.ok(!fs.existsSync(folders[0]), 'the folder is gone by the time endPageReads answers');
+ assert.match((await inFlight).message, /pac was ended/);
+
+ // Nothing starts afterwards: no download, no folder, no listing.
+ const later = await reader.pageCode(PAGE_DETAIL).catch((error) => error);
+ assert.match(later.message, /page reads were ended/);
+ const batch = await reader.pageCodes([PAGE_OVERVIEW, PAGE_DETAIL]);
+ assert.deepStrictEqual([...batch.values()].map((a) => /page reads were ended/.test(a.error && a.error.message)), [true, true], 'a batch is answered as each page\'s own failure');
+ await assert.rejects(reader.existenceIds(), /page reads were ended/);
+ assert.strictEqual(folders.length, 1, 'no second download was started');
+});
+
+test('endPageReads: a download that was waiting for the app id when the reads were ended makes no folder and starts no pac', async () => {
+ let downloads = 0;
+ let answerAppId;
+ const sdk = { queryRecords: (set) => (set === 'appmodule' ? new Promise((resolve) => { answerAppId = () => resolve([{ appmoduleid: 'app-1' }]); }) : Promise.resolve([])), findTables: async () => [] };
+ const reader = readerFor(sdk, 'new_app', { genpageCli: { enumerateEnv: async () => ({ ok: true, ids: [] }), download: async () => { downloads += 1; return true; }, abort: () => {} } });
+ // The folders this reader makes are watched where it makes them, not by listing the temp directory: other test files, running
+ // at the same time, make `verify-page-*` folders there too.
+ const madeFolders = [];
+ const mkdtempSync = fs.mkdtempSync;
+ fs.mkdtempSync = (prefix, ...rest) => { madeFolders.push(String(prefix)); return mkdtempSync.call(fs, prefix, ...rest); };
+ let answers;
+ try {
+ const waiting = reader.pageCodes([PAGE_OVERVIEW, PAGE_DETAIL]);
+ for (let i = 0; i < 50 && !answerAppId; i += 1) await turn();
+ const ending = reader.endPageReads();
+ answerAppId();
+ answers = await waiting;
+ await ending;
+ } finally {
+ fs.mkdtempSync = mkdtempSync;
+ }
+ assert.strictEqual(downloads, 0, 'no pac was started for a pass that had ended');
+ assert.deepStrictEqual(madeFolders.filter((prefix) => path.basename(prefix).startsWith('verify-page-')), [], 'and no folder was made');
+ assert.ok([...answers.values()].every((a) => a.error), 'every page is answered as a failure of its own');
+});
+
+// The reader that was used for the pass that ended its page reads may be used for another: a listing that endPageReads cut short is
+// the answer of the pass that ended it, and not one to hand the next.
+test('a listing that endPageReads cut short is not what the next pass on the same reader is answered with', async () => {
+ let listings = 0;
+ let endListing;
+ const genpageCli = {
+ // The first listing hangs until its client is told to end its runs, as a pac listing does; the next one answers.
+ enumerateEnv: () => {
+ listings += 1;
+ if (listings > 1) return Promise.resolve({ ok: true, ids: [PAGE_OVERVIEW] });
+ return new Promise((resolve) => { endListing = () => resolve({ ok: false, ids: [], error: 'pac genpage list (env-wide) was ended: pac was ended' }); });
+ },
+ abort: () => endListing(),
+ };
+ const reader = pageReader(genpageCli);
+ const cutShort = reader.existenceIds().catch((error) => error);
+ await reader.endPageReads();
+ assert.match((await cutShort).message, /was ended/, 'the pass that ended it is told so');
+ reader.beginVerificationPass();
+ assert.deepStrictEqual(await reader.existenceIds(), [PAGE_OVERVIEW], 'the next pass lists again');
+ assert.strictEqual(listings, 2);
+});
+
+test('the next pass begins with the page reads usable again, and the wait for downloads that cannot be ended is bounded', async () => {
+ const code = 'export default function P() { return null; }';
+ const genpageCli = {
+ enumerateEnv: async () => ({ ok: true, ids: [PAGE_OVERVIEW] }),
+ download: async ({ outputDir, pageIds }) => { fs.mkdirSync(path.join(outputDir, pageIds[0]), { recursive: true }); fs.writeFileSync(path.join(outputDir, pageIds[0], 'page.tsx'), code); return true; },
+ };
+ const reader = pageReader(genpageCli);
+ await reader.endPageReads();
+ await assert.rejects(reader.pageCode(PAGE_OVERVIEW), /page reads were ended/);
+ reader.beginVerificationPass();
+ assert.strictEqual(await reader.pageCode(PAGE_OVERVIEW), code, 'a reader may be used for another pass');
+ assert.deepStrictEqual(await reader.existenceIds(), [PAGE_OVERVIEW]);
+
+ // A pac client that cannot end its runs (no `abort`) must not hold the pass for ever.
+ const stuck = pageReader({ enumerateEnv: async () => ({ ok: true, ids: [] }), download: () => new Promise(() => {}) }, { endWaitMs: 50 });
+ stuck.pageCode(PAGE_DETAIL).catch(() => {});
+ for (let i = 0; i < 50; i += 1) await turn();
+ const startedAt = Date.now();
+ await stuck.endPageReads();
+ assert.ok(Date.now() - startedAt < 1500, 'it answered after the bound');
+});
+
+test('the root business unit is read once, and every caller asking at the same time gets it', async () => {
+ let reads = 0;
+ const lookup = async () => { reads += 1; await turn(); return [{ businessunitid: ROOT_BU }]; };
+ const cache = {};
+ const together = await Promise.all([
+ resolveRoleBusinessUnit(lookup, undefined, cache),
+ resolveRoleBusinessUnit(lookup, undefined, cache),
+ resolveRoleBusinessUnit(lookup, '', cache),
+ ]);
+ assert.deepStrictEqual(together, [ROOT_BU, ROOT_BU, ROOT_BU], 'a caller that asks while the lookup is under way must not be told there is no business unit');
+ assert.strictEqual(await resolveRoleBusinessUnit(lookup, undefined, cache), ROOT_BU);
+ assert.strictEqual(reads, 1);
+
+ // A lookup that fails stays one answer for everyone — unresolved, which callers fail closed on — not a retry per caller.
+ let failedReads = 0;
+ const failing = async () => { failedReads += 1; await turn(); throw new Error('429 throttled'); };
+ const failedCache = {};
+ assert.deepStrictEqual(await Promise.all([1, 2, 3].map(() => resolveRoleBusinessUnit(failing, undefined, failedCache))), [null, null, null]);
+ assert.strictEqual(failedReads, 1);
+
+ const explicit = '11111111-1111-4111-8111-111111111111';
+ assert.strictEqual(await resolveRoleBusinessUnit(failing, explicit, {}), explicit, 'an explicit business unit needs no read');
+ assert.strictEqual(failedReads, 1);
+});
+
+test('personas verified at the same time all find their roles after one business-unit lookup', async () => {
+ const { result, stats } = await runRich(undefined, { latency: () => 2 });
+ assert.deepStrictEqual(result.checks.filter((c) => c.kind === 'role').map((c) => [c.name, c.present]), [['Agent', true], ['Dispatcher', true], ['Auditor', true]]);
+ assert.strictEqual(stats.calls.filter((c) => c.name === 'queryRecords' && c.args[0] === 'businessunit').length, 1);
+});
+
+test('a table\'s privileges are read once per pass, however many personas ask for them', async () => {
+ const sequential = await runRich({ concurrency: 1 }, { latency: () => 0 });
+ const { result, stats } = await runRich(undefined, { latency: () => 2 });
+ const asked = (name) => stats.calls.filter((c) => c.name === name).map((c) => c.args[0]).sort();
+ assert.deepStrictEqual(asked('entityPrivileges'), ['appmodule', 'new_t0'], 'five reads before: Agent and Dispatcher each asked for both, Auditor for one');
+ assert.deepStrictEqual(asked('rolePrivileges'), ['role-Agent', 'role-Auditor', 'role-Dispatcher']);
+ assert.ok(result.checks.filter((c) => c.kind === 'role-privileges').length === 3 && result.checks.filter((c) => c.kind === 'role-privileges').every((c) => c.present));
+ assert.deepStrictEqual(result, sequential.result);
+});
+
+// --- the reader: the SDK's first read of a table must not be asked for twice ------------------------------
+
+// Models what the vendored SDK does before the first record read of a table: one metadata GET for the table's
+// EntitySetName, whose ANSWER (not the request in flight) is cached.
+function entitySetCachingSdk({ failFirstRead = new Set() } = {}) {
+ const cached = new Set();
+ const log = [];
+ let inFlight = 0;
+ let maxInFlight = 0;
+ const sdk = {
+ queryRecords: async (set, query) => {
+ log.push(['read', set]);
+ inFlight += 1;
+ maxInFlight = Math.max(maxInFlight, inFlight);
+ try {
+ if (!cached.has(set)) {
+ log.push(['entity-set-name', set]);
+ await turn();
+ if (failFirstRead.has(set)) { failFirstRead.delete(set); throw new Error(`HTTP 503 resolving ${set}`); }
+ cached.add(set);
+ }
+ await turn();
+ return [{ set, query }];
+ } finally {
+ inFlight -= 1;
+ }
+ },
+ other: () => 'other',
+ };
+ return { sdk, log, stats: () => ({ maxInFlight }) };
+}
+
+test('reads of one table that start together resolve its EntitySetName once; other tables are not held up', async () => {
+ const { sdk, log, stats } = entitySetCachingSdk();
+ const read = readerFor(sdk, 'new_app', {});
+ const answers = await Promise.all([
+ read.queryRecords('savedquery', { n: 1 }), read.queryRecords('savedquery', { n: 2 }),
+ read.queryRecords('savedquery', { n: 3 }), read.queryRecords('savedquery', { n: 4 }),
+ read.queryRecords('role', { n: 5 }), read.queryRecords('role', { n: 6 }),
+ ]);
+ assert.deepStrictEqual(answers.map((a) => a[0].query.n), [1, 2, 3, 4, 5, 6], 'each read gets its own answer');
+ assert.deepStrictEqual(log.filter((e) => e[0] === 'entity-set-name').map((e) => e[1]).sort(), ['role', 'savedquery'], 'one lookup per table, not one per read');
+ assert.strictEqual(log.filter((e) => e[0] === 'read').length, 6, 'every read is still made');
+ assert.ok(stats().maxInFlight >= 4, 'the later reads of a table overlap once its name is known, and tables overlap each other');
+});
+
+test('a first read that fails shares nothing — the next read of the table tries again and reports its own outcome', async () => {
+ const { sdk, log } = entitySetCachingSdk({ failFirstRead: new Set(['role']) });
+ const read = readerFor(sdk, 'new_app', {});
+ const outcomes = await Promise.allSettled([read.queryRecords('role', { n: 1 }), read.queryRecords('role', { n: 2 }), read.queryRecords('role', { n: 3 })]);
+ assert.strictEqual(outcomes[0].status, 'rejected');
+ assert.match(outcomes[0].reason.message, /HTTP 503 resolving role/);
+ assert.strictEqual(outcomes[1].status, 'fulfilled');
+ assert.strictEqual(outcomes[2].status, 'fulfilled');
+ assert.strictEqual(log.filter((e) => e[0] === 'entity-set-name').length, 2, 'one lookup failed, the next waiting read did it again, the third reused its answer');
+});
+
+test('the reader reaches every other SDK member unchanged — methods keep their `this`, properties are the SDK\'s own', async () => {
+ class FakeSdk {
+ constructor() {
+ this.calls = [];
+ this.dataverse = { get: async () => ({ status: 200, body: { value: [] } }) };
+ }
+ async queryRecords(set) { this.calls.push(`query:${set}`); return []; }
+ async findColumns(logical) { this.calls.push(`columns:${logical}`); return [{ logicalName: 'a' }]; }
+ }
+ const sdk = new FakeSdk();
+ const read = readerFor(sdk, 'new_app', {});
+ assert.deepStrictEqual(await read.findColumns('new_t'), [{ logicalName: 'a' }]);
+ await read.queryRecords('role', {});
+ await read.queryRecords('role', {});
+ assert.deepStrictEqual(sdk.calls, ['columns:new_t', 'query:role', 'query:role'], 'the calls landed on the SDK itself, not on a copy');
+});
+
+// --- the real SDK bundle behind the reader ---------------------------------------------------------------
+
+const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
+
+function recordingHttpClient() {
+ const gets = [];
+ const stats = { inFlight: 0, maxInFlight: 0 };
+ const reply = (body) => ({ status: 200, headers: {}, body });
+ const httpClient = {
+ get: async (url) => {
+ gets.push(url);
+ stats.inFlight += 1;
+ stats.maxInFlight = Math.max(stats.maxInFlight, stats.inFlight);
+ try {
+ for (let i = 0; i < 3; i++) await turn();
+ const decoded = decodeURIComponent(url);
+ const meta = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(decoded);
+ if (meta) return reply({ LogicalName: meta[1], EntitySetName: `${meta[1]}s` });
+ if (/\/businessunits\?/.test(decoded)) return reply({ value: [{ businessunitid: ROOT_BU }] });
+ if (/\/roles\?/.test(decoded)) {
+ const name = /name eq '([^']+)'/.exec(decoded);
+ return reply({ value: name && decoded.includes(`_businessunitid_value eq ${ROOT_BU}`) ? [{ roleid: `role-${name[1]}`, description: SDK_ROLE_MARKER, ismanaged: false }] : [] });
+ }
+ if (/\/savedquerys\?|\/savedqueryvisualizations\?/.test(decoded)) return reply({ value: [{ savedqueryid: 'sq', savedqueryvisualizationid: 'sv' }] });
+ return reply({ value: [] });
+ } finally {
+ stats.inFlight -= 1;
+ }
+ },
+ post: async () => { throw new Error('verify must not write'); },
+ patch: async () => { throw new Error('verify must not write'); },
+ put: async () => { throw new Error('verify must not write'); },
+ delete: async () => { throw new Error('verify must not write'); },
+ };
+ return { httpClient, gets, stats };
+}
+
+async function verifyThroughRealSdk(concurrency) {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'verify-parallel-real-'));
+ try {
+ const { httpClient, gets, stats } = recordingHttpClient();
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });
+ await sdk.initWorkspace();
+ const spec = {
+ solution: { uniqueName: 'verify_checks', publisherPrefix: 'new' },
+ app: { name: 'Verify Checks', uniqueName: 'new_verifychecks' },
+ entities: [],
+ views: TABLES.map((t) => ({ entity: t, name: `Active ${t}` })),
+ charts: TABLES.slice(0, 3).map((t) => ({ entity: t, name: `Chart ${t}` })),
+ forms: [],
+ personas: [persona('Agent'), persona('Dispatcher'), persona('Auditor', { appAccess: false })],
+ appShell: { areas: [] },
+ };
+ const result = await verifySpec(spec, readerFor(sdk, 'new_verifychecks', {}), { concurrency });
+ return { result, gets: [...gets].sort(), stats };
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+test('through the real SDK, overlapping reads send the same requests as the one-at-a-time run, EntitySetName included', async () => {
+ const sequential = await verifyThroughRealSdk(1);
+ const overlapped = await verifyThroughRealSdk(4);
+ assert.strictEqual(sequential.stats.maxInFlight, 1);
+ assert.ok(overlapped.stats.maxInFlight >= 2 && overlapped.stats.maxInFlight <= 4, `${overlapped.stats.maxInFlight} requests overlapped`);
+ assert.deepStrictEqual(overlapped.gets, sequential.gets, 'the same requests, none added by the overlap');
+ const nameLookups = overlapped.gets.map((u) => /EntityDefinitions\(LogicalName='([^']+)'\)\?\$select=EntitySetName$/.exec(decodeURIComponent(u))).filter(Boolean).map((m) => m[1]);
+ assert.deepStrictEqual(nameLookups, [...new Set(nameLookups)], 'no table\'s EntitySetName was asked for twice');
+ assert.ok(nameLookups.includes('savedquery') && nameLookups.includes('role'), 'the tables the checks share were looked up');
+ assert.deepStrictEqual(overlapped.result, sequential.result);
+ assert.ok(overlapped.result.checks.filter((c) => c.kind === 'role').every((c) => c.present), 'roles are found in the root business unit');
+});
diff --git a/plugins/model-apps/scripts/tests/verify-spec.test.js b/plugins/model-apps/scripts/tests/verify-spec.test.js
index d249aeef2..376918597 100644
--- a/plugins/model-apps/scripts/tests/verify-spec.test.js
+++ b/plugins/model-apps/scripts/tests/verify-spec.test.js
@@ -1357,6 +1357,23 @@ test('verifySpec: an override row that appears late is retried, not reported as
assert.strictEqual(r.ok, true, JSON.stringify(r.missing));
});
+test('verifySpec: an override row that stays absent is read three times before it is called absent — the budget the build\u2019s own proof shares', async () => {
+ // The build re-proves a feature after its publish with the same reads (AI_PROOF_BUDGET), so the two cannot disagree
+ // about one row for want of a second look. Counted per setting: every feature the build writes is checked.
+ const reads = new Map();
+ const base = aiRead({});
+ const read = {
+ ...base,
+ queryRecords: async (set, o) => {
+ if (set === 'appsetting') reads.set(o.filter, (reads.get(o.filter) || 0) + 1);
+ return base.queryRecords(set, o);
+ },
+ };
+ const r = await verifyAi({ ...AI_BASE, ai: { appFeatures: { formFill: true } } }, read);
+ assert.strictEqual(r.ok, false);
+ assert.ok(reads.size > 0 && [...reads.values()].every((n) => n === 3), JSON.stringify([...reads]));
+});
+
test('verifySpec: the AI check is reader-gated and absent-spec-safe (existing callers unaffected)', async () => {
// No ai block at all -> no ai checks.
const noAi = await verifyAi(AI_BASE, aiRead(ALL_SETTINGS_ON));
diff --git a/plugins/model-apps/scripts/tests/view-filter-labels.test.js b/plugins/model-apps/scripts/tests/view-filter-labels.test.js
new file mode 100644
index 000000000..e3ab67dcf
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/view-filter-labels.test.js
@@ -0,0 +1,2266 @@
+'use strict';
+// ADO 6691114 — view-filter option LABELS must resolve against the option metadata the ENVIRONMENT holds
+// whenever the spec alone cannot prove the value, and a label that matches nothing must stop the build BEFORE
+// it writes anything.
+//
+// The gap, reproduced live against the released build: a view on an EXISTING table the spec declares no column
+// of — `{ "schemaName": "account", "existing": true }` with the filter `{ "attr": "industrycode", "op": "eq",
+// "value": "Accounting" }` — passes lint, and then `resolveFilterValue` (sdk-build.js) sends the label raw: it
+// resolves only through `choiceValueMap` (app-spec.js), which knows the options a SPEC column declares, numbered
+// 100000000 + index. Dataverse rejects the saved view (HTTP 400, an invalid-fetch error naming the integer the
+// column expects) MID-BUILD, after the tables and columns were written. `industrycode` is a LOCAL option set; a
+// column bound to a SYSTEM global choice is the same case.
+// 1. a filter on a LOCAL option set of an existing table the spec does not declare (the reproduced failure);
+// 2. the same, on a column bound to a SYSTEM global choice;
+// 3. a declared global choice that already existed with other values — the SDK's createGlobalOptionSet REUSES
+// an existing set unchanged, so 100000000 + index was never what the filter needed.
+// (A column bound to a global choice the spec does not declare is a lint ERROR, so that never reaches the build.)
+// A label that matches nothing halts naming the view, the column and the valid labels — before any view is
+// written, and, where the environment already shows it, before the build writes anything at all; a dry run
+// reports it; verify expects the value the build wrote.
+const { test } = require('node:test');
+const assert = require('node:assert');
+const os = require('node:os');
+const path = require('node:path');
+const fs = require('node:fs');
+const {
+ labelUses,
+ hasLabelUses,
+ resolveViewFilterLabels,
+ checkViewFilterLabelsBeforeBuild,
+ describeProblems,
+ readChoiceAttributes,
+ readGlobalChoiceOptions,
+ makeChoiceReader,
+ makeGlobalChoiceReader,
+} = require('../lib/view-filter-labels.js');
+const { runSdkBuild, viewDef, annotateLivePlan, planFor, BuildHalt } = require('../lib/sdk-build.js');
+const { verifySpec } = require('../lib/verify-spec.js');
+const { lintAppSpec } = require('../lib/spec-lint.js');
+const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');
+const { isTransientHalt, buildModelApp } = require('../build-model-app.js');
+
+const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
+
+// ── fixtures ─────────────────────────────────────────────────────────────────────────────────────
+
+const lbl = (...pairs) => ({
+ LocalizedLabels: pairs.map(([LanguageCode, Label]) => ({ Label, LanguageCode })),
+ UserLocalizedLabel: { Label: pairs[0][1], LanguageCode: pairs[0][0] },
+});
+
+// The Dataverse option rows a cast read answers with: Options: [{ Value, Label }].
+const opts = (...rows) => rows.map(([Value, ...labels]) => ({ Value, Label: lbl(...labels) }));
+
+// `byTable`: { table: { Picklist: { column: rows }, MultiSelectPicklist: {…}, State: {…}, Status: {…} } }.
+// A table the map does not name answers 404 on every cast, as a table the environment lacks does.
+// `globalSets`: { name: rows } — the global option sets the environment holds; any other name answers 404.
+function choiceClient(byTable, { failCast, status = 503, globalSets, failGlobal } = {}) {
+ const paths = [];
+ return {
+ paths,
+ get: async (p) => {
+ paths.push(p);
+ // The table-existence probe the dry run makes before it judges anything on the table.
+ const exists = /EntityDefinitions\(LogicalName='([^']+)'\)\?\$select=LogicalName,EntitySetName/.exec(p);
+ if (exists) {
+ return byTable[exists[1]]
+ ? { status: 200, headers: {}, body: { LogicalName: exists[1], EntitySetName: `${exists[1]}s` } }
+ : { status: 404, headers: {}, body: { error: { message: 'not found' } } };
+ }
+ const set = /GlobalOptionSetDefinitions\(Name='([^']+)'\)/.exec(p);
+ if (set) {
+ if (failGlobal) return { status, headers: {}, body: {} };
+ return globalSets && globalSets[set[1]]
+ ? { status: 200, headers: {}, body: { Name: set[1], IsGlobal: true, Options: globalSets[set[1]] } }
+ : { status: 404, headers: {}, body: { error: { message: 'not found' } } };
+ }
+ const m = /LogicalName='([^']+)'\)\/Attributes\/Microsoft\.Dynamics\.CRM\.(\w+)AttributeMetadata\?/.exec(p);
+ if (!m) return { status: 200, headers: {}, body: { value: [] } };
+ const [, table, cast] = m;
+ if (failCast === cast) return { status, headers: {}, body: {} };
+ if (!byTable[table]) return { status: 404, headers: {}, body: { error: { message: 'not found' } } };
+ const columns = byTable[table][cast] || {};
+ return { status: 200, headers: {}, body: { value: Object.entries(columns).map(([LogicalName, Options]) => ({ LogicalName, OptionSet: { Options } })) } };
+ },
+ };
+}
+
+const TIER = opts([227350000, [1033, 'Silver'], [3082, 'Plata']], [227350001, [1033, 'Gold'], [3082, 'Oro']], [227350002, [1033, 'Bronze']]);
+
+// The global choice every spec here declares, so a column bound to it is a VALID spec (an undeclared one is a
+// lint error). Its numbering is the spec's 100000000 + index; TIER above is what an environment that already
+// had the set under other values holds.
+const TIER_SET = { name: 'new_tierset', options: ['Silver', 'Gold', 'Bronze'] };
+
+const customer = (columns, extra) => ({ schemaName: 'new_customer', displayName: 'Customer', primaryAttribute: { schemaName: 'new_name' }, columns, ...extra });
+const specOf = (entities, views, extra) => ({
+ solution: { uniqueName: 'S', publisherPrefix: 'new' },
+ app: { name: 'A' },
+ entities,
+ views,
+ globalChoices: [TIER_SET],
+ ...extra,
+});
+const view = (entity, filters, name = 'Gold customers') => ({ entity, name, columns: ['new_name'], activeOnly: false, filters });
+const eq = (attr, value) => ({ attr, op: 'eq', value });
+
+const GLOBAL_TIER_COLUMN = { schemaName: 'new_tier', type: 'Choice', globalChoice: 'new_tierset' };
+
+// A table the spec reuses without declaring any column of it, and the local option set the reproduced failure was on.
+const ACCOUNT = { schemaName: 'account', displayName: 'Account', existing: true, primaryAttribute: { schemaName: 'name' }, columns: [] };
+const INDUSTRY = opts([1, [1033, 'Accounting']], [6, [1033, 'Retail']], [23, [1033, 'Consulting']]);
+
+const resolveAll = (spec, client) => resolveViewFilterLabels(spec, spec.views, { read: client ? makeChoiceReader({ client }) : null });
+
+// ── 1. what counts as a label use ─────────────────────────────────────────────────────────────────
+
+test('ADO 6691114: only a non-integer string in a value-taking filter is a label use', () => {
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [
+ eq('new_tier', 'Gold'),
+ eq('new_tier', '227350001'),
+ eq('new_tier', '227350001,227350002'),
+ { attr: 'new_tier', op: 'eq', value: 227350001 },
+ { attr: 'new_tier', op: 'in', values: ['Gold', 'Silver', '100000000'] },
+ { attr: 'ownerid', op: 'eq-userid' },
+ { attr: 'createdon', op: 'this-week' },
+ ])]);
+ assert.deepStrictEqual(labelUses(spec, spec.views[0]).map((u) => [u.attr, u.label]), [['new_tier', 'Gold'], ['new_tier', 'Gold'], ['new_tier', 'Silver']]);
+ assert.strictEqual(hasLabelUses(spec, spec.views[0]), true);
+ assert.strictEqual(hasLabelUses(spec, view('new_customer', [{ attr: 'ownerid', op: 'eq-userid' }, eq('new_tier', '2')])), false);
+});
+
+test('ADO 6691114: a declared column that is not a Choice is never a label use', () => {
+ const spec = specOf([customer([{ schemaName: 'new_code', type: 'Text' }, { schemaName: 'new_flag', type: 'Boolean' }])],
+ [view('new_customer', [eq('new_code', 'ABC'), { attr: 'new_flag', op: 'eq', value: 'true' }])]);
+ assert.deepStrictEqual(labelUses(spec, spec.views[0]), []);
+});
+
+test('ADO 6691114: an id or a date on a column the spec does not declare is no label use — but is on a declared Choice column', () => {
+ const GUID_VALUE = '11111111-2222-3333-4444-555555555555';
+ const undeclared = specOf([{ schemaName: 'account', displayName: 'Account', existing: true, primaryAttribute: { schemaName: 'name' }, columns: [] }], [
+ view('account', [eq('parentaccountid', GUID_VALUE), eq('createdon', '2024-01-31'), eq('createdon', '2024-01-31T10:00:00Z'), eq('industrycode', 'Retail')], 'Accounts'),
+ ]);
+ assert.deepStrictEqual(labelUses(undeclared, undeclared.views[0]).map((u) => u.label), ['Retail']);
+ // A Choice column the spec DOES declare keeps every string a label, so a stray id there is reported, not passed through.
+ const declared = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', GUID_VALUE)])]);
+ assert.deepStrictEqual(labelUses(declared, declared.views[0]).map((u) => u.label), [GUID_VALUE]);
+});
+
+test('ADO 6691114: a half-typed spec is no crash — an entity with no schemaName is validation\'s finding, not a TypeError', () => {
+ const spec = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, entities: [{}, customer([])], views: [view('new_customer', [eq('industrycode', 'Retail')])] };
+ assert.deepStrictEqual(labelUses(spec, spec.views[0]).map((u) => u.attr), ['industrycode']);
+ assert.deepStrictEqual(labelUses(spec, view('new_unknown', [eq('industrycode', 'Retail')])).map((u) => u.attr), ['industrycode']);
+});
+
+// ── 2. the three gaps, and every other way a label resolves ───────────────────────────────────────
+
+test('ADO 6691114 gap 1: a filter on a LOCAL option set of an existing table the spec does not declare resolves from the environment', async () => {
+ // The reproduced failure: `Accounting` on account.industrycode went to Dataverse as the text "Accounting".
+ const spec = specOf([ACCOUNT], [view('account', [eq('industrycode', 'Accounting')], 'Accounts')]);
+ const r = await resolveAll(spec, choiceClient({ account: { Picklist: { industrycode: INDUSTRY } } }));
+ assert.deepStrictEqual(r.problems, []);
+ assert.strictEqual(r.value('account', 'industrycode', 'Accounting'), 1);
+});
+
+test('ADO 6691114 gap 2: the same on a column bound to a SYSTEM global choice resolves from the environment', async () => {
+ // A global-bound column carries the shared set through `OptionSet` exactly as a local one does.
+ const spec = specOf([{ ...ACCOUNT, schemaName: 'incident', displayName: 'Case' }], [view('incident', [eq('caseorigincode', 'Web')], 'Web cases')]);
+ const r = await resolveAll(spec, choiceClient({ incident: { Picklist: { caseorigincode: opts([1, [1033, 'Phone']], [3, [1033, 'Web']]) } } }));
+ assert.deepStrictEqual(r.problems, []);
+ assert.strictEqual(r.value('incident', 'caseorigincode', 'Web'), 3);
+});
+
+test('ADO 6691114 gap 3: a declared global choice that already existed with other values resolves to the live value', async () => {
+ const spec = specOf([customer([{ schemaName: 'new_status', type: 'Choice', globalChoice: 'new_statusset' }])],
+ [view('new_customer', [eq('new_status', 'Closed')])], { globalChoices: [{ name: 'new_statusset', displayName: 'Status', options: ['Open', 'Closed'] }] });
+ const r = await resolveAll(spec, choiceClient({ new_customer: { Picklist: { new_status: opts([227350010, [1033, 'Open']], [227350011, [1033, 'Closed']]) } } }));
+ assert.strictEqual(r.value('new_customer', 'new_status', 'Closed'), 227350011, 'createGlobalOptionSet reuses an existing set unchanged, so 100000001 was never right');
+});
+
+test('ADO 6691114: the environment wins over the spec for a column the spec declares inline too', async () => {
+ // A maker adds an option in the portal and the platform assigns its own value; the spec's
+ // 100000000 + index is no longer what the column holds.
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] }])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const r = await resolveAll(spec, choiceClient({ new_customer: { Picklist: { new_tier: TIER } } }));
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Gold'), 227350001);
+});
+
+test('ADO 6691114: a label in ANY language matches, and an ambiguous alias is refused rather than tie-broken', async () => {
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Oro')])]);
+ const r = await resolveAll(spec, choiceClient({ new_customer: { Picklist: { new_tier: TIER } } }));
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Oro'), 227350001);
+
+ // "Abierto" is option 0 in Spanish and option 1 in English — one string cannot select two values.
+ const clash = opts([1, [1033, 'Open'], [3082, 'Abierto']], [2, [1033, 'Abierto'], [3082, 'Cerrado']]);
+ const spec2 = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Abierto')], 'Open ones')]);
+ const r2 = await resolveAll(spec2, choiceClient({ new_customer: { Picklist: { new_tier: clash } } }));
+ assert.strictEqual(r2.value('new_customer', 'new_tier', 'Abierto'), undefined);
+ assert.strictEqual(r2.problems.length, 1);
+ assert.strictEqual(r2.problems[0].reason, 'ambiguous');
+ assert.match(describeProblems(r2.problems), /"Abierto" names more than one option \(1, 2\)/);
+});
+
+test('ADO 6691114: a label that matches no option is a problem naming the view, the column and the valid labels', async () => {
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Platinum')], 'Top customers')]);
+ const r = await resolveAll(spec, choiceClient({ new_customer: { Picklist: { new_tier: TIER } } }));
+ assert.strictEqual(r.problems.length, 1);
+ const text = describeProblems(r.problems);
+ assert.match(text, /view "Top customers"/);
+ assert.match(text, /new_customer\.new_tier/);
+ assert.match(text, /"Platinum"/);
+ assert.match(text, /Silver, Gold, Bronze/);
+ assert.match(text, /integer/i, 'tells the author the raw value is the way out');
+});
+
+test('ADO 6691114: a long option list is cut off, saying how many were left out', async () => {
+ const many = opts(...Array.from({ length: 40 }, (_, i) => [i, [1033, `Option ${i}`]]));
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Nope')])]);
+ const r = await resolveAll(spec, choiceClient({ new_customer: { Picklist: { new_tier: many } } }));
+ assert.match(describeProblems(r.problems), /Option 0, .*Option 24 … and 15 more/);
+});
+
+test('ADO 6691114: a raw integer passes through untouched, with no read of the environment', async () => {
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', '227350001'), { attr: 'new_tier', op: 'in', values: ['227350000', 227350002] }])]);
+ const client = choiceClient({ new_customer: { Picklist: { new_tier: TIER } } });
+ const r = await resolveAll(spec, client);
+ assert.deepStrictEqual(r.problems, []);
+ assert.deepStrictEqual(client.paths, [], 'nothing needed resolving, so nothing was read');
+ assert.strictEqual(r.value('new_customer', 'new_tier', '227350001'), undefined, 'and nothing is rewritten');
+});
+
+test('ADO 6691114: a string that is not an option of a column the environment says is not a choice stays as written', async () => {
+ // `new_legalname` is not declared, so only the environment can say it is not a choice.
+ const spec = specOf([customer([])], [view('new_customer', [eq('new_legalname', 'Contoso Ltd'), eq('new_name', 'Contoso'), { attr: 'createdon', op: 'on', value: '2024-01-01' }])]);
+ const client = choiceClient({ new_customer: { Picklist: { new_tier: TIER } } });
+ const r = await resolveAll(spec, client);
+ assert.deepStrictEqual(r.problems, []);
+ assert.deepStrictEqual(r.warnings, []);
+ assert.strictEqual(r.value('new_customer', 'new_legalname', 'Contoso Ltd'), undefined);
+ assert.strictEqual(client.paths.length, 4, 'read once to learn it is not a choice');
+});
+
+test('ADO 6691114: the status and state columns resolve by label too', async () => {
+ const spec = specOf([customer([])], [view('new_customer', [eq('statuscode', 'Escalated'), eq('statecode', 'Inactive')])]);
+ const r = await resolveAll(spec, choiceClient({ new_customer: {
+ Status: { statuscode: opts([1, [1033, 'Active']], [100000000, [1033, 'Escalated']]) },
+ State: { statecode: opts([0, [1033, 'Active']], [1, [1033, 'Inactive']]) },
+ } }));
+ assert.deepStrictEqual(r.problems, []);
+ assert.strictEqual(r.value('new_customer', 'statuscode', 'Escalated'), 100000000);
+ assert.strictEqual(r.value('new_customer', 'statecode', 'Inactive'), 1);
+});
+
+test('ADO 6691114: a multi-select column resolves too', async () => {
+ const spec = specOf([customer([{ schemaName: 'new_tags', type: 'MultiChoice', globalChoice: 'new_tierset' }])], [{ entity: 'new_customer', name: 'Tagged', columns: ['new_name'], filters: [{ attr: 'new_tags', op: 'contain-values', value: 'Gold' }] }]);
+ const r = await resolveAll(spec, choiceClient({ new_customer: { MultiSelectPicklist: { new_tags: TIER } } }));
+ assert.strictEqual(r.value('new_customer', 'new_tags', 'Gold'), 227350001);
+});
+
+test('ADO 6691114: each table is read once however many filters and views use it', async () => {
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [
+ view('new_customer', [eq('new_tier', 'Gold'), eq('new_tier', 'Silver'), eq('new_name', 'Contoso')], 'One'),
+ view('new_customer', [eq('new_tier', 'Bronze')], 'Two'),
+ ]);
+ const client = choiceClient({ new_customer: { Picklist: { new_tier: TIER } } });
+ await resolveAll(spec, client);
+ assert.strictEqual(client.paths.length, 4, 'one read per choice kind, for the one table');
+ assert.ok(client.paths.every((p) => /LogicalName='new_customer'/.test(p)));
+});
+
+// ── 3. what the spec alone can prove, and what a failed read does ──────────────────────────────────
+
+test('ADO 6691114: with no environment to read, the spec\'s own options still resolve (the old behaviour)', async () => {
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] }])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const r = await resolveAll(spec, null);
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Gold'), 100000001);
+ assert.deepStrictEqual(r.problems, []);
+});
+
+test('ADO 6691114: a table the environment does not have yet resolves from the spec — the build is about to create it', async () => {
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] }])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const r = await resolveAll(spec, choiceClient({}));
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Gold'), 100000001);
+});
+
+test('ADO 6691114: a failed read falls back to what the spec declares', async () => {
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] }])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const r = await resolveAll(spec, choiceClient({ new_customer: {} }, { failCast: 'Picklist' }));
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Gold'), 100000001);
+ assert.deepStrictEqual(r.problems, []);
+});
+
+test('ADO 6691114: a label the spec does not declare and a failed read cannot confirm is a problem, never a raw value', async () => {
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Platinum')])]);
+ const r = await resolveAll(spec, choiceClient({ new_customer: {} }, { failCast: 'Picklist', status: 503 }));
+ assert.strictEqual(r.problems.length, 1);
+ assert.strictEqual(r.problems[0].reason, 'unreadable');
+ assert.match(describeProblems(r.problems), /could not read.*new_customer.*503/s);
+});
+
+test('ADO 6691114: a failed read leaves a label the spec DOES declare resolved from the spec', async () => {
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const r = await resolveAll(spec, choiceClient({ new_customer: {} }, { failCast: 'Picklist', status: 503 }));
+ assert.deepStrictEqual(r.problems, []);
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Gold'), 100000001);
+});
+
+test('ADO 6691114: a column the spec does not declare, on a table that could not be read, is left as written — with a warning', async () => {
+ const spec = specOf([customer([])], [view('new_customer', [eq('industrycode', 'Retail')])]);
+ const r = await resolveAll(spec, choiceClient({ new_customer: {} }, { failCast: 'State', status: 503 }));
+ assert.deepStrictEqual(r.problems, []);
+ assert.ok(r.warnings.some((w) => /industrycode/.test(w) && /Retail/.test(w) && /503/.test(w)), JSON.stringify(r.warnings));
+});
+
+test('ADO 6691114: a declared choice column the environment lacks resolves from the spec (the build creates it)', async () => {
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] }])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const r = await resolveAll(spec, choiceClient({ new_customer: { Picklist: { new_other: TIER } } }));
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Gold'), 100000001);
+});
+
+// ── 3b. before the build writes anything ──────────────────────────────────────────────────────────
+//
+// Before the build runs, the environment cannot hold what the build is about to create, so a label is judged by
+// whichever side is AUTHORITATIVE for it, and only a definite answer is a problem. Anything else is left to the
+// views phase, which asks again once the build has run.
+
+const preflight = (spec, client, extra = {}) => checkViewFilterLabelsBeforeBuild(spec, spec.views, {
+ read: client ? makeChoiceReader({ client }) : null,
+ readGlobalChoice: client ? makeGlobalChoiceReader({ client }) : null,
+ ...extra,
+});
+
+test('ADO 6691114 pre-flight: the reproduced failure — a typo on a local option set of an existing table — is a problem before anything is written', async () => {
+ const client = choiceClient({ account: { Picklist: { industrycode: INDUSTRY } } });
+ const bad = await preflight(specOf([ACCOUNT], [view('account', [eq('industrycode', 'Accountig')], 'Accounts')]), client);
+ assert.strictEqual(bad.problems.length, 1);
+ assert.match(describeProblems(bad.problems), /view "Accounts" \(account\): filter on industrycode — "Accountig" is not an option of account\.industrycode\. Valid labels: Accounting, Retail, Consulting\./);
+ const good = await preflight(specOf([ACCOUNT], [view('account', [eq('industrycode', 'Accounting')], 'Accounts')]), client);
+ assert.deepStrictEqual(good.problems, []);
+ assert.strictEqual(good.resolved.get('account|industrycode|Accounting'), 1, 'what a column the environment already has says is final, and handed on');
+});
+
+test('ADO 6691114 pre-flight: only what the environment already held is handed on as resolved — what the build creates is not', async () => {
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] }])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ assert.strictEqual((await preflight(spec, choiceClient({ new_customer: { Picklist: { new_tier: TIER } } }))).resolved.size, 1, 'the column is there');
+ assert.strictEqual((await preflight(spec, choiceClient({ new_customer: { Picklist: { new_other: TIER } } }))).resolved.size, 0, 'the build is about to create the column');
+ assert.strictEqual((await preflight(spec, choiceClient({}))).resolved.size, 0, 'and the table');
+});
+
+test('ADO 6691114: the final resolution takes what the pre-flight resolved and does not read those tables again', async () => {
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const client = choiceClient({ new_customer: { Picklist: { new_tier: TIER } } });
+ const r = await resolveViewFilterLabels(spec, spec.views, { read: makeChoiceReader({ client }), prior: new Map([['new_customer|new_tier|Gold', 227350001]]) });
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Gold'), 227350001);
+ assert.deepStrictEqual(client.paths, []);
+});
+
+test('ADO 6691114 pre-flight: a column of an existing table bound to a system global choice is judged the same way', async () => {
+ const incident = { ...ACCOUNT, schemaName: 'incident', displayName: 'Case' };
+ const client = choiceClient({ incident: { Picklist: { caseorigincode: opts([1, [1033, 'Phone']], [3, [1033, 'Web']]) } } });
+ assert.deepStrictEqual((await preflight(specOf([incident], [view('incident', [eq('caseorigincode', 'Web')])]), client)).problems, []);
+ const bad = await preflight(specOf([incident], [view('incident', [eq('caseorigincode', 'Fax')])]), client);
+ assert.match(describeProblems(bad.problems), /"Fax" is not an option of incident\.caseorigincode\. Valid labels: Phone, Web\./);
+});
+
+test('ADO 6691114 pre-flight: a column the spec declares and the environment lacks is the spec\'s to decide, on an existing table or a new one', async () => {
+ const declared = [customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] }])];
+ for (const byTable of [{ new_customer: { Picklist: { new_other: TIER } } }, {}]) {
+ const client = choiceClient(byTable);
+ assert.deepStrictEqual((await preflight(specOf(declared, [view('new_customer', [eq('new_tier', 'Gold')])]), client)).problems, []);
+ const bad = await preflight(specOf(declared, [view('new_customer', [eq('new_tier', 'Platinum')], 'Top')]), client);
+ assert.match(describeProblems(bad.problems), /"Platinum" is not an option of new_customer\.new_tier\. Valid labels: Silver, Gold\./);
+ }
+});
+
+test('ADO 6691114 pre-flight: a column the environment already has keeps the options it has, whatever the spec lists', async () => {
+ // The build creates what is missing and leaves an existing column alone, so the environment is final.
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold', 'Platinum'] }])], [view('new_customer', [eq('new_tier', 'Platinum')])]);
+ const bad = await preflight(spec, choiceClient({ new_customer: { Picklist: { new_tier: TIER } } }));
+ assert.match(describeProblems(bad.problems), /"Platinum" is not an option of new_customer\.new_tier\. Valid labels: Silver, Gold, Bronze\./);
+});
+
+test('ADO 6691114 pre-flight: a column bound to a declared global choice follows the set — the environment\'s when it already exists, the spec\'s when it does not', async () => {
+ const tableWithoutColumn = { new_customer: { Picklist: { new_other: TIER } } };
+ const spec = (label) => specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', label)])]);
+ // No such set yet: the build creates it from the spec, so the spec decides.
+ const fresh = choiceClient(tableWithoutColumn);
+ assert.deepStrictEqual((await preflight(spec('Gold'), fresh)).problems, []);
+ assert.match(describeProblems((await preflight(spec('Platinum'), fresh)).problems), /Valid labels: Silver, Gold, Bronze\./);
+ // The set already exists with other options: createGlobalOptionSet reuses it unchanged, so it decides. A label
+ // only the live set has is NOT a problem — halting on the spec's list there would stop a good build.
+ const live = choiceClient(tableWithoutColumn, { globalSets: { new_tierset: opts([1, [1033, 'Platinum']], [2, [1033, 'Gold']]) } });
+ assert.deepStrictEqual((await preflight(spec('Platinum'), live)).problems, []);
+ assert.match(describeProblems((await preflight(spec('Silver'), live)).problems), /"Silver" is not an option of new_customer\.new_tier\. Valid labels: Platinum, Gold\./);
+});
+
+test('ADO 6691114 pre-flight: what cannot be known yet is not a problem — the views phase asks again after the build', async () => {
+ const declaredSet = (label) => specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', label)])]);
+ const onTable = { new_customer: { Picklist: { new_other: TIER } } };
+ // The global set could not be read.
+ assert.deepStrictEqual((await preflight(declaredSet('Platinum'), choiceClient(onTable, { failGlobal: true }))).problems, []);
+ // The table could not be read (or not completely), so a column might be there.
+ const inline = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver'] }])], [view('new_customer', [eq('new_tier', 'Platinum')])]);
+ assert.deepStrictEqual((await preflight(inline, choiceClient(onTable, { failCast: 'Status' }))).problems, []);
+ assert.deepStrictEqual((await preflight(inline, choiceClient({}, { failCast: 'Status' }))).problems, [], 'one cast failing makes the answer incomplete');
+ // A column the spec does not declare, on a table that is not there yet: a system column of a table the build creates.
+ assert.deepStrictEqual((await preflight(specOf([customer([])], [view('new_customer', [eq('statuscode', 'Escalated')])]), choiceClient({}))).problems, []);
+ // …and on a table that is, where it is not a choice column at all: a plain value.
+ assert.deepStrictEqual((await preflight(specOf([customer([])], [view('new_customer', [eq('new_legalname', 'Contoso Ltd')])]), choiceClient(onTable))).problems, []);
+ // With no environment to ask there is nothing to check ahead of the build.
+ assert.deepStrictEqual((await preflight(inline, null)).problems, []);
+});
+
+test('ADO 6691114 pre-flight: a status reason the build inserts itself is not a problem, a typo of it is', async () => {
+ // statusReasons[] are inserted into the table's statuscode by the data-model phase, so before it runs the environment lists none.
+ const withReason = { ...ACCOUNT, statusReasons: [{ label: 'Passed QA', state: 'Active' }] };
+ const client = choiceClient({ account: { Status: { statuscode: opts([1, [1033, 'Active']], [2, [1033, 'Inactive']]) } } });
+ assert.deepStrictEqual((await preflight(specOf([withReason], [view('account', [eq('statuscode', 'Passed QA')])]), client)).problems, []);
+ assert.deepStrictEqual((await preflight(specOf([withReason], [view('account', [eq('statuscode', 'Active')])]), client)).problems, []);
+ const typo = await preflight(specOf([withReason], [view('account', [eq('statuscode', 'Passed Q')], 'QA')]), client);
+ assert.match(describeProblems(typo.problems), /"Passed Q" is not an option of account\.statuscode\. Valid labels: Active, Inactive\./);
+});
+
+test('ADO 6691114 pre-flight: an ambiguous alias in the environment is a problem, and every problem of every view is reported', async () => {
+ const clash = opts([1, [1033, 'Open'], [3082, 'Abierto']], [2, [1033, 'Abierto'], [3082, 'Cerrado']]);
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [
+ view('new_customer', [eq('new_tier', 'Abierto')], 'First'),
+ view('new_customer', [eq('new_tier', 'Diamond')], 'Second'),
+ ]);
+ const r = await preflight(spec, choiceClient({ new_customer: { Picklist: { new_tier: clash } } }));
+ assert.deepStrictEqual(r.problems.map((p) => [p.view, p.reason]), [['First', 'ambiguous'], ['Second', 'unknown']]);
+});
+
+// ── 4. the reader itself ──────────────────────────────────────────────────────────────────────────
+
+test('ADO 6691114: the reader asks one narrow cast read per choice kind and keeps every language of every option', async () => {
+ const client = choiceClient({ new_customer: { Picklist: { new_tier: TIER } } });
+ const got = await readChoiceAttributes(client, 'new_customer');
+ assert.strictEqual(got.state, 'ok');
+ assert.deepStrictEqual(client.paths.map((p) => /Microsoft\.Dynamics\.CRM\.(\w+)AttributeMetadata/.exec(p)[1]).sort(), ['MultiSelectPicklist', 'Picklist', 'State', 'Status']);
+ assert.ok(client.paths.every((p) => p.endsWith('?$select=LogicalName&$expand=OptionSet($select=Options)')), JSON.stringify(client.paths));
+ const tier = got.attributes.get('new_tier');
+ assert.strictEqual(tier.kind, 'Picklist');
+ assert.deepStrictEqual(tier.options.map((o) => [o.value, o.labels]), [[227350000, ['Silver', 'Plata']], [227350001, ['Gold', 'Oro']], [227350002, ['Bronze']]]);
+});
+
+test('ADO 6691114: a table every cast answers 404 for is absent, and one failing cast makes the answer incomplete', async () => {
+ assert.deepStrictEqual(await readChoiceAttributes(choiceClient({}), 'new_customer'), { state: 'absent' });
+ const part = await readChoiceAttributes(choiceClient({ new_customer: { Picklist: { new_tier: TIER } } }, { failCast: 'Status' }), 'new_customer');
+ assert.strictEqual(part.state, 'ok');
+ assert.strictEqual(part.complete, false, 'an attribute that is missing from an incomplete read is unknown, not "not a choice"');
+ assert.ok(part.attributes.has('new_tier'), 'but what the other casts returned is still usable');
+});
+
+test('ADO 6691114: a transport failure on any cast is an error, never an empty answer', async () => {
+ const client = { get: async () => { throw new Error('socket hang up'); } };
+ const got = await readChoiceAttributes(client, 'new_customer');
+ assert.strictEqual(got.state, 'error');
+ assert.match(got.why, /socket hang up/);
+});
+
+test('ADO 6691114: the memoizing reader reads a table once, however it is asked', async () => {
+ const client = choiceClient({ new_customer: { Picklist: { new_tier: TIER } } });
+ const read = makeChoiceReader({ client });
+ await Promise.all([read('new_customer'), read('NEW_CUSTOMER'), read('new_customer')]);
+ assert.strictEqual(client.paths.length, 4);
+ assert.strictEqual(makeChoiceReader({ client: null }), null, 'no client, no reader');
+ assert.strictEqual(makeChoiceReader({ client: {} }), null);
+});
+
+test('ADO 6691114: the global choice reader reads the set by its lower-cased name and keeps every language of every option', async () => {
+ const client = choiceClient({}, { globalSets: { new_tierset: TIER } });
+ const got = await readGlobalChoiceOptions(client, 'NEW_TierSet');
+ assert.deepStrictEqual(client.paths, ["/GlobalOptionSetDefinitions(Name='new_tierset')"]);
+ assert.strictEqual(got.state, 'ok');
+ assert.deepStrictEqual(got.options.map((o) => [o.value, o.labels]), [[227350000, ['Silver', 'Plata']], [227350001, ['Gold', 'Oro']], [227350002, ['Bronze']]]);
+});
+
+test('ADO 6691114: a global choice that is not there is absent, and one that could not be read is an error — never an empty set', async () => {
+ assert.deepStrictEqual(await readGlobalChoiceOptions(choiceClient({}), 'new_tierset'), { state: 'absent' });
+ const failed = await readGlobalChoiceOptions(choiceClient({}, { failGlobal: true, status: 503 }), 'new_tierset');
+ assert.strictEqual(failed.state, 'error');
+ assert.match(failed.why, /503/);
+ const thrown = await readGlobalChoiceOptions({ get: async () => { throw new Error('socket hang up'); } }, 'new_tierset');
+ assert.strictEqual(thrown.state, 'error');
+ assert.match(thrown.why, /socket hang up/);
+ const shapeless = await readGlobalChoiceOptions({ get: async () => ({ status: 200, headers: {}, body: { Name: 'new_tierset' } }) }, 'new_tierset');
+ assert.strictEqual(shapeless.state, 'error', 'a 200 that carries no Options is not an empty set');
+});
+
+test('ADO 6691114: the memoizing global choice reader reads a set once, however it is asked', async () => {
+ const client = choiceClient({}, { globalSets: { new_tierset: TIER } });
+ const read = makeGlobalChoiceReader({ client });
+ await Promise.all([read('new_tierset'), read('NEW_TIERSET'), read('new_tierset')]);
+ assert.strictEqual(client.paths.length, 1);
+ assert.strictEqual(makeGlobalChoiceReader({ client: null }), null);
+});
+
+// ── 5. REAL bundle: the reader through the SDK's own client ───────────────────────────────────────
+
+const dirs = [];
+test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+async function realClient(routes) {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'filter-labels-'));
+ dirs.push(dir);
+ const reads = [];
+ const httpClient = {
+ get: async (url) => {
+ const u = decodeURIComponent(url);
+ reads.push(u);
+ for (const [re, answer] of routes) if (re.test(u)) return answer;
+ return { status: 404, headers: {}, body: {} };
+ },
+ post: async () => ({ status: 204, headers: {}, body: {} }),
+ patch: async () => ({ status: 204, headers: {}, body: {} }),
+ put: 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, reads };
+}
+
+test('REAL BUNDLE (ADO 6691114): the SDK client carries the cast read and returns the option set a global choice shares', async () => {
+ const { sdk, reads } = await realClient([
+ [/Attributes\/Microsoft\.Dynamics\.CRM\.PicklistAttributeMetadata/, { status: 200, headers: {}, body: { value: [{
+ LogicalName: 'new_tier',
+ MetadataId: '11111111-1111-1111-1111-111111111111',
+ // A column bound to a global choice carries the shared set in OptionSet, as an inline one does.
+ OptionSet: { Name: 'new_tierset', IsGlobal: true, Options: TIER },
+ }] } }],
+ [/Attributes\/Microsoft\.Dynamics\.CRM\.(MultiSelectPicklist|State|Status)AttributeMetadata/, { status: 200, headers: {}, body: { value: [] } }],
+ ]);
+ const got = await readChoiceAttributes(sdk.dataverse, 'new_customer');
+ assert.strictEqual(got.state, 'ok');
+ assert.strictEqual(got.complete, true);
+ assert.deepStrictEqual(got.attributes.get('new_tier').options.map((o) => o.value), [227350000, 227350001, 227350002]);
+ assert.strictEqual(reads.length, 4);
+ assert.ok(reads.every((r) => /EntityDefinitions\(LogicalName='new_customer'\)\/Attributes\/Microsoft\.Dynamics\.CRM\.\w+AttributeMetadata\?\$select=LogicalName&\$expand=OptionSet\(\$select=Options\)$/.test(r)), JSON.stringify(reads));
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Oro')])]);
+ const r = await resolveViewFilterLabels(spec, spec.views, { read: makeChoiceReader({ client: sdk.dataverse }) });
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Oro'), 227350001);
+});
+
+test('REAL BUNDLE (ADO 6691114): the SDK client carries the global option set read, by name, and returns its options', async () => {
+ const { sdk, reads } = await realClient([
+ [/GlobalOptionSetDefinitions\(Name='new_tierset'\)$/, { status: 200, headers: {}, body: { MetadataId: '11111111-1111-1111-1111-111111111111', Name: 'new_tierset', IsGlobal: true, Options: TIER } }],
+ ]);
+ const got = await readGlobalChoiceOptions(sdk.dataverse, 'new_tierset');
+ assert.strictEqual(reads.length, 1);
+ assert.match(reads[0], /\/GlobalOptionSetDefinitions\(Name='new_tierset'\)$/);
+ assert.strictEqual(got.state, 'ok');
+ assert.deepStrictEqual(got.options.map((o) => o.value), [227350000, 227350001, 227350002]);
+ assert.strictEqual((await readGlobalChoiceOptions(sdk.dataverse, 'new_missing')).state, 'absent');
+});
+
+test('REAL BUNDLE (ADO 6691114): a renamed option of a declared global choice, read through the SDK\'s own client, keeps the spec\'s number — a set numbered otherwise does not', async () => {
+ const route = (rows) => [
+ [/Attributes\/Microsoft\.Dynamics\.CRM\.PicklistAttributeMetadata/, { status: 200, headers: {}, body: { value: [{
+ LogicalName: 'new_tier',
+ MetadataId: '11111111-1111-1111-1111-111111111111',
+ OptionSet: { Name: 'new_tierset', IsGlobal: true, Options: rows },
+ }] } }],
+ [/Attributes\/Microsoft\.Dynamics\.CRM\.(MultiSelectPicklist|State|Status)AttributeMetadata/, { status: 200, headers: {}, body: { value: [] } }],
+ ];
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const resolveWith = async (rows) => {
+ const { sdk } = await realClient(route(rows));
+ return resolveViewFilterLabels(spec, spec.views, { read: makeChoiceReader({ client: sdk.dataverse }) });
+ };
+ const renamed = await resolveWith(opts([100000000, [1033, 'Silver']], [100000001, [1033, 'Gold Tier']], [100000002, [1033, 'Bronze']]));
+ assert.deepStrictEqual(renamed.problems, []);
+ assert.strictEqual(renamed.value('new_customer', 'new_tier', 'Gold'), 100000001);
+ assert.strictEqual(renamed.warnings.length, 1);
+ assert.match(renamed.warnings[0], /on the assumption that it is the same option under another label/);
+ const otherOrder = await resolveWith(opts([100000000, [1033, 'Bronze']], [100000001, [1033, 'Silver']], [100000002, [1033, 'Gold Tier']]));
+ assert.strictEqual(otherOrder.value('new_customer', 'new_tier', 'Gold'), undefined);
+ assert.strictEqual(otherOrder.problems.length, 1);
+ assert.deepStrictEqual(otherOrder.warnings, []);
+});
+
+// ── 6. the views phase: resolve before ANY view is written ─────────────────────────────────────────
+
+// `record: true` wraps the SDK so every method the build calls is noted by name (`names`): "nothing was written"
+// is then asserted by what was NOT called, not by a list of the writes someone remembered.
+function viewsEngine({ byTable, existingViews = [], failCast, status, globalSets, failGlobal, record = false } = {}) {
+ const { sdk, calls } = makeSimpleMockSdk();
+ const defs = [];
+ const createArtifact = sdk.createArtifact;
+ sdk.createArtifact = (type, def) => { defs.push([type, def]); return createArtifact(type, def); };
+ const pushed = [];
+ const push = sdk.pushArtifact;
+ sdk.pushArtifact = async (type, id) => { pushed.push([type, id]); return push(type, id); };
+ sdk.findArtifact = async (kind, identity) => (kind === 'view' && existingViews.includes(identity.name) ? `existing-${identity.name}` : null);
+ const client = byTable ? choiceClient(byTable, { failCast, globalSets, failGlobal, ...(status ? { status } : {}) }) : null;
+ if (client) sdk.dataverse = client;
+ const names = [];
+ // The raw reads join the SDK calls in ONE ordered trace, so "this read came before that write" can be asserted.
+ if (client && record) { const get = client.get; client.get = async (p) => { names.push(`GET ${p}`); return get(p); }; }
+ const used = record
+ ? new Proxy(sdk, { get: (target, key) => (typeof target[key] === 'function' ? (...args) => { names.push(String(key)); return target[key](...args); } : target[key]) })
+ : sdk;
+ const run = (spec, extra = {}) => {
+ const warnings = [];
+ return runSdkBuild(spec, { sdk: used, apply: true, phases: ['views'], preResolvedLanguageCode: 1033, warn: (w) => warnings.push(w), ...extra }).then(
+ (result) => ({ result, warnings }),
+ (error) => ({ error, warnings }),
+ );
+ };
+ return { sdk, calls, defs, pushed, client, names, run };
+}
+
+// What counts as writing: a create, an insert, an update, a push… — never a find, a query, a get or a fetch.
+const WRITE_CALL = /^(create|insert|update|add|remove|set|push|publish|seed|delete|enrich|configure)/;
+const writesOf = (names) => names.filter((n) => WRITE_CALL.test(n));
+
+const viewCondition = (defs, name, attribute) => {
+ const def = defs.find(([type, d]) => type === 'view' && d.name === name)[1];
+ const all = [...def.filters.conditions, ...def.filters.groups.flatMap((g) => g.conditions)];
+ return all.filter((c) => c.attribute === attribute).map((c) => c.value);
+};
+
+test('ADO 6691114 build: a filter on a local option set of an existing table the spec does not declare reaches the FetchXML as its value (gap 1)', async () => {
+ // The reproduced failure: the label used to go to Dataverse as text, and the saved view was rejected.
+ const e = viewsEngine({ byTable: { account: { Picklist: { industrycode: INDUSTRY } } } });
+ const spec = specOf([ACCOUNT], [view('account', [eq('industrycode', 'Accounting')], 'Accounts')]);
+ const { error } = await e.run(spec);
+ assert.ifError(error);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Accounts', 'industrycode'), ['1']);
+});
+
+test('ADO 6691114 build: the same on a column bound to a system global choice (gap 2)', async () => {
+ const incident = { ...ACCOUNT, schemaName: 'incident', displayName: 'Case' };
+ const e = viewsEngine({ byTable: { incident: { Picklist: { caseorigincode: opts([1, [1033, 'Phone']], [3, [1033, 'Web']]) } } } });
+ const spec = specOf([incident], [view('incident', [eq('caseorigincode', 'Web')], 'Web cases')]);
+ const { error } = await e.run(spec);
+ assert.ifError(error);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Web cases', 'caseorigincode'), ['3']);
+});
+
+test('ADO 6691114 build: a declared global choice that already existed with other values filters on the live value (gap 3)', async () => {
+ // The spec numbers Silver/Gold/Bronze from 100000000; createGlobalOptionSet REUSES an existing set unchanged,
+ // so on this environment Gold is 227350001 and the spec's number would select nothing.
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: TIER } } } });
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const { error } = await e.run(spec);
+ assert.ifError(error);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Gold customers', 'new_tier'), ['227350001']);
+});
+
+test('ADO 6691114 build: in / not-in values resolve through the same rule', async () => {
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: TIER } } } });
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [{ attr: 'new_tier', op: 'not-in', values: ['Gold', 'Oro', '227350002'] }])]);
+ const { error } = await e.run(spec);
+ assert.ifError(error);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Gold customers', 'new_tier'), ['227350001', '227350001', '227350002']);
+});
+
+test('ADO 6691114 build: an unknown label halts BEFORE any view is written, naming the view, the column and the valid labels', async () => {
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: TIER } } } });
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [
+ view('new_customer', [eq('new_tier', 'Gold')], 'Fine view'),
+ view('new_customer', [eq('new_tier', 'Platinum')], 'Top customers'),
+ ]);
+ const { error, result } = await e.run(spec);
+ assert.strictEqual(result, undefined, 'the build did not complete');
+ assert.ok(error instanceof BuildHalt, String(error && error.stack));
+ assert.strictEqual(error.code, 'view-filter-label-unresolved');
+ assert.strictEqual(error.phase, 'views');
+ assert.match(error.message, /view "Top customers"/);
+ assert.match(error.message, /new_customer\.new_tier/);
+ assert.match(error.message, /Silver, Gold, Bronze/);
+ assert.match(error.message, /no view was written/i);
+ assert.strictEqual(error.transient, false);
+ // The CLI retries a halt it judges transient; this one quotes a metadata read's own words, which can look like one.
+ assert.strictEqual(isTransientHalt(error), false, 'a rerun cannot change the answer, so the build must not auto-retry it');
+ assert.deepStrictEqual(e.defs.filter(([type]) => type === 'view'), [], 'not even the VALID view before it was created');
+ assert.deepStrictEqual(e.pushed, []);
+});
+
+// A label an unanswered option read left undecided is not wrong — the read may answer next time — so that halt keeps the
+// read's HTTP status for the CLI's retry check: a throttled or unavailable read is run again, anything else is final.
+const PRIORITY = { schemaName: 'new_priority', type: 'Choice', options: ['Low', 'High'] };
+
+test('ADO 6691114 build: a halt that only an unanswered option read left undecided is run again on a 503 or a 429, not on a 400', async () => {
+ for (const [status, again] of [[503, true], [429, true], [400, false]]) {
+ const e = viewsEngine({ byTable: { new_customer: {} }, failCast: 'Picklist', status });
+ const spec = specOf([customer([PRIORITY])], [view('new_customer', [eq('new_priority', 'Medium')], 'Medium customers')]);
+ const { error } = await e.run(spec);
+ assert.ok(error instanceof BuildHalt, String(error && error.stack));
+ assert.strictEqual(error.code, 'view-filter-label-unresolved');
+ assert.match(error.message, new RegExp(`could not read the options of new_customer\\.new_priority \\(HTTP ${status}`));
+ assert.strictEqual(isTransientHalt(error), again, `HTTP ${status}`);
+ assert.deepStrictEqual(e.defs.filter(([type]) => type === 'view'), [], 'no view was written');
+ }
+ // The message quotes the filter label itself, so a label that reads like a transient error must not make a final
+ // read look like one: only the read's own status (429, 503) can.
+ const e = viewsEngine({ byTable: { new_customer: {} }, failCast: 'Picklist', status: 403 });
+ const { error } = await e.run(specOf([customer([PRIORITY])], [view('new_customer', [eq('new_priority', 'SQL Timeout')], 'Odd label')]));
+ assert.strictEqual(error && error.code, 'view-filter-label-unresolved', String(error && error.stack));
+ assert.match(error.message, /"SQL Timeout"/);
+ assert.strictEqual(isTransientHalt(error), false, 'a 403 is final, whatever the label says');
+});
+
+test('ADO 6691114 build: a halt that also names a label the environment shows to be wrong is never run again', async () => {
+ const e = viewsEngine({ byTable: { new_customer: {} }, failCast: 'Picklist', status: 503, globalSets: { new_tierset: TIER } });
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN, PRIORITY])], [
+ view('new_customer', [eq('new_priority', 'Medium')], 'Medium customers'),
+ view('new_customer', [eq('new_tier', 'Platinum')], 'Top customers'),
+ ]);
+ const { error } = await e.run(spec);
+ assert.strictEqual(error && error.code, 'view-filter-label-unresolved', String(error && error.stack));
+ assert.match(error.message, /"Platinum" is not an option of new_customer\.new_tier/);
+ assert.match(error.message, /could not read the options of new_customer\.new_priority \(HTTP 503/);
+ assert.strictEqual(error.transient, false);
+ assert.strictEqual(isTransientHalt(error), false, 'a re-run cannot fix the wrong label, whatever the other read answers next time');
+});
+
+test('ADO 6691114 build: every bad label in every view is reported at once', async () => {
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: TIER } } } });
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [
+ view('new_customer', [eq('new_tier', 'Platinum')], 'First'),
+ view('new_customer', [eq('new_tier', 'Diamond')], 'Second'),
+ ]);
+ const { error } = await e.run(spec);
+ assert.match(error.message, /view "First"[\s\S]*"Platinum"/);
+ assert.match(error.message, /view "Second"[\s\S]*"Diamond"/);
+});
+
+test('ADO 6691114 build: an EXISTING view\'s filters are never reapplied, so a label it cannot resolve does not halt the build', async () => {
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: TIER } } }, existingViews: ['Top customers'] });
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Platinum')], 'Top customers')]);
+ const { error, result } = await e.run(spec);
+ assert.ifError(error);
+ assert.ok(result && result.ok);
+});
+
+test('ADO 6691114 build: a bad label on an existing view does not hide one on a view the build creates', async () => {
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: TIER } } }, existingViews: ['Old view'] });
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [
+ view('new_customer', [eq('new_tier', 'Platinum')], 'Old view'),
+ view('new_customer', [eq('new_tier', 'Diamond')], 'New view'),
+ ]);
+ const { error } = await e.run(spec);
+ assert.match(error.message, /view "New view"/);
+ assert.doesNotMatch(error.message, /Old view/);
+});
+
+test('ADO 6691114 build: a view with no label in its filters costs no read of the environment', async () => {
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: TIER } } } });
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [{ attr: 'ownerid', op: 'eq-userid' }, eq('new_tier', '227350001')])]);
+ const { error } = await e.run(spec);
+ assert.ifError(error);
+ assert.deepStrictEqual(e.client.paths, []);
+});
+
+test('ADO 6691114 build: a filter on an id or a date, on a column the spec does not declare, costs no read of the environment', async () => {
+ const e = viewsEngine({ byTable: { account: { Picklist: {} } } });
+ const spec = specOf([{ schemaName: 'account', displayName: 'Account', existing: true, primaryAttribute: { schemaName: 'name' }, columns: [] }], [
+ view('account', [eq('parentaccountid', '11111111-2222-3333-4444-555555555555'), eq('createdon', '2024-01-31')], 'Accounts'),
+ ]);
+ const { error } = await e.run(spec);
+ assert.ifError(error);
+ assert.deepStrictEqual(e.client.paths, []);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Accounts', 'parentaccountid'), ['11111111-2222-3333-4444-555555555555']);
+});
+
+test('ADO 6691114 build: when no view names a label, every other string value reaches the FetchXML exactly as written', async () => {
+ // No label use anywhere, so no resolution exists — which must leave a pattern, a date and a raw option value alone.
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: TIER } } } });
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [
+ { attr: 'new_name', op: 'like', value: 'A%' },
+ { attr: 'createdon', op: 'on', value: '2024-01-31' },
+ eq('new_tier', '227350001'),
+ ])]);
+ const { error } = await e.run(spec);
+ assert.ifError(error);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Gold customers', 'new_name'), ['A%']);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Gold customers', 'createdon'), ['2024-01-31']);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Gold customers', 'new_tier'), ['227350001']);
+ assert.deepStrictEqual(e.client.paths, []);
+});
+
+test('ADO 6691114 build: each table is read once for the whole phase, however many views name it', async () => {
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: TIER } } } });
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [
+ view('new_customer', [eq('new_tier', 'Gold')], 'One'),
+ view('new_customer', [eq('new_tier', 'Silver')], 'Two'),
+ view('new_customer', [eq('new_tier', 'Bronze')], 'Three'),
+ ]);
+ const { error } = await e.run(spec);
+ assert.ifError(error);
+ assert.strictEqual(e.client.paths.length, 4);
+});
+
+// ── 6b. the build's pre-flight: a label the environment already shows to be wrong stops the build first ──
+//
+// The reproduced failure left a half-built app: the tables and columns were written and THEN Dataverse rejected the
+// view. So the labels are checked before the first write; the views phase checks again, once the build has run.
+
+const FULL = ['solution', 'data-model', 'views'];
+
+test('ADO 6691114 pre-flight: a typo on a local option set of an existing table stops the build before ANYTHING is written', async () => {
+ const e = viewsEngine({ byTable: { account: { Picklist: { industrycode: INDUSTRY } } }, record: true });
+ const spec = specOf([ACCOUNT], [view('account', [eq('industrycode', 'Accountig')], 'Accounts')]);
+ const { error, result } = await e.run(spec, { phases: FULL });
+ assert.strictEqual(result, undefined, 'the build did not complete');
+ assert.ok(error instanceof BuildHalt, String(error && error.stack));
+ assert.strictEqual(error.code, 'view-filter-label-unresolved');
+ assert.strictEqual(error.phase, 'preflight', 'tagged like the CLI\'s own pre-flight halts: the views phase has not started');
+ assert.strictEqual(error.recoverable, false);
+ assert.strictEqual(error.transient, false);
+ assert.strictEqual(isTransientHalt(error), false);
+ assert.match(error.message, /before writing anything/i);
+ assert.match(error.message, /view "Accounts" \(account\): filter on industrycode — "Accountig" is not an option of account\.industrycode\. Valid labels: Accounting, Retail, Consulting\./);
+ assert.deepStrictEqual(writesOf(e.names), [], `a half-built app is what this prevents: ${JSON.stringify(e.names)}`);
+});
+
+test('ADO 6691114 pre-flight: the reproduced scenario with the RIGHT label builds, and the view carries the option value', async () => {
+ const e = viewsEngine({ byTable: { account: { Picklist: { industrycode: INDUSTRY } } }, record: true });
+ const spec = specOf([ACCOUNT], [view('account', [eq('industrycode', 'Accounting')], 'Accounts')]);
+ const { error } = await e.run(spec, { phases: FULL });
+ assert.ifError(error);
+ assert.ok(writesOf(e.names).length > 0, 'the build went on to write');
+ assert.deepStrictEqual(viewCondition(e.defs, 'Accounts', 'industrycode'), ['1']);
+});
+
+test('ADO 6691114 pre-flight: it runs for the data stage too, so the staged flow fails before it writes the data model', async () => {
+ const e = viewsEngine({ byTable: { account: { Picklist: { industrycode: INDUSTRY } } }, record: true });
+ const spec = specOf([ACCOUNT], [view('account', [eq('industrycode', 'Accountig')], 'Accounts')]);
+ const { error } = await e.run(spec, { phases: ['solution', 'data-model', 'sample-data'] });
+ assert.strictEqual(error && error.code, 'view-filter-label-unresolved');
+ assert.deepStrictEqual(writesOf(e.names), []);
+});
+
+test('ADO 6691114 pre-flight: a typo on a column the build is about to create is the spec\'s to catch, before the table is created', async () => {
+ const e = viewsEngine({ byTable: {}, record: true });
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] }])], [view('new_customer', [eq('new_tier', 'Platinum')], 'Top customers')]);
+ const { error } = await e.run(spec, { phases: FULL });
+ assert.strictEqual(error && error.code, 'view-filter-label-unresolved');
+ assert.match(error.message, /"Platinum" is not an option of new_customer\.new_tier\. Valid labels: Silver, Gold\./);
+ assert.deepStrictEqual(writesOf(e.names), []);
+});
+
+test('ADO 6691114 pre-flight: a label only the environment\'s copy of a declared global choice has does not stop a good build', async () => {
+ // The set already exists with Platinum, which the spec does not list. The environment decides, so this builds,
+ // and the views phase — after the data model — writes the live value.
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: opts([5, [1033, 'Platinum']], [6, [1033, 'Gold']]) } } }, globalSets: { new_tierset: opts([5, [1033, 'Platinum']], [6, [1033, 'Gold']]) }, record: true });
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Platinum')], 'Top customers')]);
+ const { error } = await e.run(spec, { phases: FULL });
+ assert.ifError(error);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Top customers', 'new_tier'), ['5']);
+});
+
+test('ADO 6691114 pre-flight: a status reason the build inserts is resolved by the views phase, after the data model has added it', async () => {
+ // Before the build the environment lists no "Passed QA"; the data-model phase inserts it; the views phase reads it back.
+ const byTable = { account: { Status: { statuscode: opts([1, [1033, 'Active']], [2, [1033, 'Inactive']]) } } };
+ const e = viewsEngine({ byTable, record: true });
+ e.sdk.insertStatusValue = async (logical, o) => { byTable.account.Status.statuscode.push({ Value: 100000000, Label: lbl([1033, o.label]) }); return 100000000; };
+ const spec = specOf([{ ...ACCOUNT, statusReasons: [{ label: 'Passed QA', state: 'Active' }] }], [view('account', [eq('statuscode', 'Passed QA')], 'Passed accounts')]);
+ const { error } = await e.run(spec, { phases: FULL });
+ assert.ifError(error);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Passed accounts', 'statuscode'), ['100000000']);
+});
+
+test('ADO 6691114 pre-flight: what the environment already held is final and not asked again; what the build creates is asked about after it', async () => {
+ const castReads = (e) => e.client.paths.filter((p) => /AttributeMetadata\?/.test(p)).length;
+ // The column exists, so the pre-flight's answer stands: four cast reads in all, and the view carries that value.
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const had = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: TIER } } } });
+ assert.ifError((await had.run(spec, { phases: FULL })).error);
+ assert.strictEqual(castReads(had), 4, 'read once, before the build; the views phase took that answer');
+ assert.deepStrictEqual(viewCondition(had.defs, 'Gold customers', 'new_tier'), ['227350001']);
+ // A status reason the build inserts is not there to read until it has run, so the views phase asks again: eight.
+ const byTable = { account: { Status: { statuscode: opts([1, [1033, 'Active']], [2, [1033, 'Inactive']]) } } };
+ const made = viewsEngine({ byTable });
+ made.sdk.insertStatusValue = async (logical, o) => { byTable.account.Status.statuscode.push({ Value: 100000000, Label: lbl([1033, o.label]) }); return 100000000; };
+ const withReason = specOf([{ ...ACCOUNT, statusReasons: [{ label: 'Passed QA', state: 'Active' }] }], [view('account', [eq('statuscode', 'Passed QA')], 'Passed accounts')]);
+ assert.ifError((await made.run(withReason, { phases: FULL })).error);
+ assert.strictEqual(castReads(made), 8, 'four cast reads before the build, four after it');
+ // A run with nothing written before the views phase has no pre-flight, so its own check is the only one.
+ const only = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: TIER } } } });
+ assert.ifError((await only.run(spec, { phases: ['views'] })).error);
+ assert.strictEqual(castReads(only), 4);
+});
+
+test('ADO 6691114 pre-flight: an existing view is not judged, in the pre-flight any more than in the views phase — and is said once', async () => {
+ const e = viewsEngine({ byTable: { account: { Picklist: { industrycode: INDUSTRY } } }, existingViews: ['Accounts'], record: true });
+ const spec = specOf([ACCOUNT], [view('account', [eq('industrycode', 'Accountig')], 'Accounts')]);
+ const { error, warnings } = await e.run(spec, { phases: FULL });
+ assert.ifError(error);
+ assert.strictEqual(warnings.filter((w) => /view "Accounts" \(account\) already exists/.test(w)).length, 1, JSON.stringify(warnings));
+});
+
+test('ADO 6691114 pre-flight: a read that fails does not stop the build there — what cannot be known is the views phase\'s to say', async () => {
+ const e = viewsEngine({ byTable: { account: { Picklist: { industrycode: INDUSTRY } } }, failCast: 'Picklist', record: true });
+ const spec = specOf([ACCOUNT], [view('account', [eq('industrycode', 'Accounting')], 'Accounts')]);
+ const { error, warnings } = await e.run(spec, { phases: FULL });
+ assert.ifError(error);
+ assert.ok(warnings.some((w) => /could not be read completely/.test(w) && /industrycode/.test(w) && /503/.test(w)), JSON.stringify(warnings));
+});
+
+test('ADO 6691114 pre-flight: with no metadata client there is nothing to check ahead of the build', async () => {
+ const e = viewsEngine({ record: true });
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver'] }])], [view('new_customer', [eq('new_tier', 'Platinum')])]);
+ const { error } = await e.run(spec, { phases: ['solution', 'data-model'] });
+ assert.ifError(error);
+ assert.ok(writesOf(e.names).length > 0);
+});
+
+test('ADO 6691114 build: with no metadata client the spec\'s own options still resolve, exactly as before', async () => {
+ const e = viewsEngine({});
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] }])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const { error } = await e.run(spec);
+ assert.ifError(error);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Gold customers', 'new_tier'), ['100000001']);
+});
+
+test('ADO 6691114: viewDef without a resolution is the old spec-only rule, unchanged', () => {
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] }])], [view('new_customer', [eq('new_tier', 'Gold'), eq('industrycode', 'Retail')])]);
+ const def = viewDef(spec, spec.views[0]);
+ assert.deepStrictEqual(def.filters.conditions.map((c) => [c.attribute, c.value]), [['new_tier', '100000001'], ['industrycode', 'Retail']]);
+});
+
+// ── 6c. a spec with a LOCALIZED label: no label-bearing read before the data model is written ───────
+//
+// The pre-flight reads option labels (every language of every option) and whole global choices. The plugin's own
+// measurement (AB#6686428) is that a label-bearing metadata read made ahead of a create leaves Dataverse with only
+// the base-language label of a multi-language one — silently. Nothing says those reads are exempt, so a build that
+// may CREATE a localized label does not run them before the data-model writes. The views phase runs after every
+// create, so the check still happens before any view is written; the dry run creates nothing and keeps its report.
+
+const isLabelRead = (name) => /^GET .*(AttributeMetadata\?|GlobalOptionSetDefinitions)/.test(name);
+const isDataModelWrite = (name) => /^(createTable|createColumn|createCustomerColumn|createGlobalOptionSet|createRelationship|createAlternateKey|insertStatusValue)$/.test(name);
+const indexesOf = (names, test) => names.map((n, i) => (test(n) ? i : -1)).filter((i) => i >= 0);
+const NOTE = { 1033: 'Note', 3082: 'Nota' };
+
+// A table the build creates, beside a view on a column of the EXISTING account table — the label the pre-flight
+// would read the environment for. `localize` puts a localized label somewhere in the data model.
+const localizedSpec = (filterLabel, localize) => {
+ const created = customer([{ schemaName: 'new_note', type: 'Text', displayName: 'Note' }]);
+ const spec = specOf([ACCOUNT, created], [view('account', [eq('industrycode', filterLabel)], 'Accounts')]);
+ return localize ? localize(spec) : spec;
+};
+const onCustomer = (change) => (spec) => ({ ...spec, entities: spec.entities.map((e) => (e.schemaName === 'new_customer' ? change(e) : e)) });
+const PLACEMENTS = {
+ 'a table\'s name': onCustomer((e) => ({ ...e, displayName: NOTE, pluralName: { 1033: 'Customers', 3082: 'Clientes' } })),
+ 'a primary column\'s name': onCustomer((e) => ({ ...e, primaryAttribute: { schemaName: 'new_name', displayName: NOTE } })),
+ 'a column\'s name': onCustomer((e) => ({ ...e, columns: [{ schemaName: 'new_note', type: 'Text', displayName: NOTE }] })),
+ 'an inline choice option': onCustomer((e) => ({ ...e, columns: [{ schemaName: 'new_tier', type: 'Choice', options: [NOTE, 'Other'] }] })),
+ 'an alternate key\'s name': onCustomer((e) => ({ ...e, alternateKeys: [{ schemaName: 'new_key', displayName: NOTE, columns: ['new_name'] }] })),
+ 'a relationship lookup\'s name': (spec) => ({
+ ...spec,
+ entities: [...spec.entities, { ...customer([]), schemaName: 'new_order', displayName: 'Order' }],
+ relationships: [{ type: 'OneToMany', referenced: 'new_customer', referencing: 'new_order', lookup: { schemaName: 'new_CustomerId', displayName: NOTE } }],
+ }),
+};
+const ACCOUNT_TABLES = () => ({ account: { Picklist: { industrycode: INDUSTRY } } });
+
+for (const [where, localize] of Object.entries(PLACEMENTS)) {
+ test(`ADO 6691114 localized: with a localized label on ${where}, no label-bearing read precedes the data-model writes — the views phase checks after them`, async () => {
+ const e = viewsEngine({ byTable: ACCOUNT_TABLES(), record: true });
+ const { error } = await e.run(localizedSpec('Accounting', localize), { phases: FULL });
+ assert.ifError(error);
+ const reads = indexesOf(e.names, isLabelRead);
+ const creates = indexesOf(e.names, isDataModelWrite);
+ assert.ok(creates.length > 0, `the build created the data model: ${JSON.stringify(e.names)}`);
+ assert.ok(reads.length > 0, 'the label was still resolved, by the views phase');
+ assert.ok(Math.min(...reads) > Math.max(...creates), `a label-bearing read ran ahead of a create: ${JSON.stringify(e.names)}`);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Accounts', 'industrycode'), ['1']);
+ });
+}
+
+test('ADO 6691114 localized: a typo still stops the build before any VIEW is written — after the data model, since nothing was read ahead of it', async () => {
+ const e = viewsEngine({ byTable: ACCOUNT_TABLES(), record: true });
+ const { error, result } = await e.run(localizedSpec('Accountig', PLACEMENTS['a column\'s name']), { phases: FULL });
+ assert.strictEqual(result, undefined);
+ assert.ok(error instanceof BuildHalt, String(error && error.stack));
+ assert.strictEqual(error.code, 'view-filter-label-unresolved');
+ assert.strictEqual(error.phase, 'views');
+ assert.match(error.message, /No view was written/);
+ assert.match(error.message, /"Accountig" is not an option of account\.industrycode\. Valid labels: Accounting, Retail, Consulting\./);
+ assert.ok(e.names.includes('createTable'), 'the data model went first');
+ assert.deepStrictEqual(e.defs.filter(([type]) => type === 'view'), []);
+ assert.deepStrictEqual(e.pushed, []);
+});
+
+test('ADO 6691114 localized: a spec with NO localized label keeps the pre-flight — its reads come before the first write', async () => {
+ const e = viewsEngine({ byTable: ACCOUNT_TABLES(), record: true });
+ const { error } = await e.run(localizedSpec('Accounting'), { phases: FULL });
+ assert.ifError(error);
+ const reads = indexesOf(e.names, isLabelRead);
+ const writes = indexesOf(e.names, (n) => WRITE_CALL.test(n));
+ assert.ok(reads.length > 0 && writes.length > 0);
+ assert.ok(Math.min(...reads) < Math.min(...writes), JSON.stringify(e.names));
+});
+
+test('ADO 6691114 localized: a localized label with no label in any view filter costs no label read at all', async () => {
+ const e = viewsEngine({ byTable: ACCOUNT_TABLES(), record: true });
+ const spec = localizedSpec('Accounting', PLACEMENTS['a column\'s name']);
+ spec.views = [view('account', [{ attr: 'ownerid', op: 'eq-userid' }], 'Mine')];
+ const { error } = await e.run(spec, { phases: FULL });
+ assert.ifError(error);
+ assert.deepStrictEqual(indexesOf(e.names, isLabelRead), []);
+});
+
+// ── 6d. what the pre-flight resolved is not lost when the views phase's own read fails ───────────────
+
+// Reads of option metadata fail from the moment the build has created a column — the views phase's own.
+function failOptionReadsAfterTheDataModel(e) {
+ let written = false;
+ const createColumn = e.sdk.createColumn;
+ e.sdk.createColumn = async (...args) => { written = true; return createColumn(...args); };
+ const get = e.client.get;
+ e.client.get = async (p) => (written && /AttributeMetadata\?/.test(p) ? { status: 503, headers: {}, body: {} } : get(p));
+}
+
+test('ADO 6691114 pre-flight: an existing global choice\'s real value is handed on, so a later failed read cannot fall back to 100000000 + index', async () => {
+ // The set already exists with Gold = 227350001 (the spec numbers it 100000001). The pre-flight read it;
+ // when the views phase's own read then fails, the view must still carry what the set holds.
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_other: TIER } } }, globalSets: { new_tierset: TIER }, record: true });
+ failOptionReadsAfterTheDataModel(e);
+ const { error } = await e.run(specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Gold')])]), { phases: FULL });
+ assert.ifError(error);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Gold customers', 'new_tier'), ['227350001']);
+});
+
+test('ADO 6691114 pre-flight: the value of a label on a column bound to an EXISTING global choice is among what it resolved', async () => {
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const client = choiceClient({ new_customer: { Picklist: { new_other: TIER } } }, { globalSets: { new_tierset: opts([1, [1033, 'Platinum']], [2, [1033, 'Gold']]) } });
+ const { problems, resolved } = await preflight(spec, client);
+ assert.deepStrictEqual(problems, []);
+ assert.strictEqual(resolved.get('new_customer|new_tier|Gold'), 2, 'the set is reused unchanged, so its number is the column\'s');
+ // A set the environment lacks is created from the spec, so there is nothing final to hand on.
+ const fresh = await preflight(spec, choiceClient({ new_customer: { Picklist: { new_other: TIER } } }));
+ assert.strictEqual(fresh.resolved.size, 0);
+});
+
+test('ADO 6691114 build: when a read fails and the spec\'s own numbering is used, the build says so', async () => {
+ // No pre-flight value exists for a column the build creates from inline options, so the views phase's fallback
+ // is the only answer — right only for an option set this build created, which is what the warning says.
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_other: TIER } } }, record: true });
+ failOptionReadsAfterTheDataModel(e);
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] }])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const { error, warnings } = await e.run(spec, { phases: FULL });
+ assert.ifError(error);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Gold customers', 'new_tier'), ['100000001']);
+ const warned = warnings.filter((w) => /spec's own numbering/.test(w));
+ assert.strictEqual(warned.length, 1, JSON.stringify(warnings));
+ assert.match(warned[0], /new_customer/);
+ assert.match(warned[0], /"Gold" on 'new_tier'/);
+ assert.match(warned[0], /\(100000001\)/);
+ assert.match(warned[0], /503/);
+});
+
+test('ADO 6691114 build: no fallback warning when the environment answered, or when there was no environment to ask', async () => {
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] }])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const answered = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: opts([100000000, [1033, 'Silver']], [100000001, [1033, 'Gold']]) } } } });
+ assert.deepStrictEqual((await answered.run(spec)).warnings, []);
+ const blind = viewsEngine({});
+ assert.deepStrictEqual((await blind.run(spec)).warnings, []);
+});
+
+test('ADO 6691114: resolveViewFilterLabels lists what a failed or partial read left open, with the value the build falls back to', async () => {
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] }])], [view('new_customer', [eq('new_tier', 'Gold'), eq('industrycode', 'Retail')])]);
+ const r = await resolveAll(spec, choiceClient({ new_customer: {} }, { failCast: 'Picklist', status: 503 }));
+ assert.deepStrictEqual(r.inconclusive.map((p) => [p.attr, p.label, p.assumed, p.reason, p.why]), [
+ ['new_tier', 'Gold', 100000001, 'unreadable', 'HTTP 503'],
+ ['industrycode', 'Retail', 'Retail', 'unreadable', 'HTTP 503'],
+ ]);
+ const whole = await resolveAll(spec, choiceClient({ new_customer: { Picklist: { new_tier: opts([5, [1033, 'Gold']]) } } }));
+ assert.deepStrictEqual(whole.inconclusive, [], 'an answered read leaves nothing open');
+});
+
+// ── 6e. a column whose options the spec numbers keeps the spec's number — where the environment has that option ──
+//
+// A maker renames an option ("Gold" -> "Gold Tier"), or a translation never reached the environment. The option's
+// VALUE did not change, so a view filtered on the spec's label still has a well-defined meaning — and builds before
+// labels were resolved against the environment built it, with the spec's number. Halting those builds would be a
+// regression, so the spec's number stands where the environment still has that option, and the build says so.
+// (Section 6g is the other half: the spec's number is NOT used where the environment shows another numbering.)
+
+const INLINE_TIER = { schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] };
+const RENAMED = opts([100000000, [1033, 'Silver']], [100000001, [1033, 'Gold Tier']]);
+const LOCALIZED_TIER = { schemaName: 'new_tier', type: 'Choice', options: [{ 1033: 'Silver', 3082: 'Plata' }, { 1033: 'Gold', 3082: 'Oro' }] };
+const BASE_LANGUAGE_ONLY = opts([100000000, [1033, 'Silver']], [100000001, [1033, 'Gold']]);
+const inlineSpec = (label = 'Gold', column = INLINE_TIER) => specOf([customer([column])], [view('new_customer', [eq('new_tier', label)])]);
+const inlineEnv = (rows) => choiceClient({ new_customer: { Picklist: { new_tier: rows } } });
+
+test('ADO 6691114 inline: an option a maker RENAMED still resolves to the spec\'s own number — with a warning — instead of halting', async () => {
+ const r = await resolveAll(inlineSpec('Gold'), inlineEnv(RENAMED));
+ assert.deepStrictEqual(r.problems, []);
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Gold'), 100000001);
+ assert.strictEqual(r.warnings.length, 1, JSON.stringify(r.warnings));
+ assert.match(r.warnings[0], /lists no option labelled "Gold" on 'new_customer'\.'new_tier'/);
+});
+
+test('ADO 6691114 inline: the warning says what was ASSUMED — it does not claim the option on that number is the label\'s own', async () => {
+ // The environment shows only that SOME option carries the number; that it is the option the label named is the
+ // build's assumption, so the warning must say so, and say how to take the choice out of the build's hands.
+ const [warning] = (await resolveAll(inlineSpec('Gold'), inlineEnv(RENAMED))).warnings;
+ assert.match(warning, /The spec numbers "Gold" 100000001/);
+ assert.match(warning, /option with that number, labelled "Gold Tier"/);
+ assert.match(warning, /on the assumption that it is the same option under another label/);
+ assert.match(warning, /use the integer value of the option you mean/);
+ assert.doesNotMatch(warning, /the spec's own number for it — is there/, 'that wording stated the identity as a fact');
+});
+
+test('ADO 6691114 inline: a LOCALIZED option whose translation the environment lacks resolves to the spec\'s number, in the language it has', async () => {
+ const r = await resolveAll(inlineSpec('Oro', LOCALIZED_TIER), inlineEnv(BASE_LANGUAGE_ONLY));
+ assert.deepStrictEqual(r.problems, []);
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Oro'), 100000001);
+ assert.match(r.warnings[0], /"Oro"/);
+ // The language the environment DOES hold resolves on its own, with nothing to say.
+ const known = await resolveAll(inlineSpec('Gold', LOCALIZED_TIER), inlineEnv(BASE_LANGUAGE_ONLY));
+ assert.strictEqual(known.value('new_customer', 'new_tier', 'Gold'), 100000001);
+ assert.deepStrictEqual(known.warnings, []);
+});
+
+test('ADO 6691114 inline: it still halts when nothing vouches for the spec\'s number', async () => {
+ // The environment no longer has option 100000001 at all: "Gold" names nothing there.
+ const gone = await resolveAll(inlineSpec('Gold'), inlineEnv(opts([100000000, [1033, 'Silver']], [5, [1033, 'Gold Tier']])));
+ assert.strictEqual(gone.problems.length, 1);
+ assert.strictEqual(gone.problems[0].reason, 'unknown');
+ assert.match(describeProblems(gone.problems), /"Gold" is not an option of new_customer\.new_tier\. Valid labels: Silver, Gold Tier\./);
+ assert.strictEqual(gone.value('new_customer', 'new_tier', 'Gold'), undefined);
+ // A label the spec does not have is a typo, whatever the environment holds.
+ const typo = await resolveAll(inlineSpec('Platinum'), inlineEnv(RENAMED));
+ assert.strictEqual(typo.problems.length, 1);
+ assert.deepStrictEqual(typo.warnings, []);
+});
+
+test('ADO 6691114 global: a column bound to a global choice the spec DECLARES keeps the spec\'s numbering as an inline one does — a renamed option still resolves, with a warning', async () => {
+ // 2.13.0 numbered a declared global choice 100000000 + index and built the view with that, so an app it built
+ // must not stop on the rename of an option in the set. The numbering of a set that is another app's is a
+ // different matter — see 6g: nothing is bound where the environment shows it.
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const r = await resolveAll(spec, inlineEnv(opts([100000000, [1033, 'Silver']], [100000001, [1033, 'Gold Tier']], [100000002, [1033, 'Bronze']])));
+ assert.deepStrictEqual(r.problems, []);
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Gold'), 100000001);
+ assert.strictEqual(r.warnings.length, 1, JSON.stringify(r.warnings));
+ assert.match(r.warnings[0], /lists no option labelled "Gold" on 'new_customer'\.'new_tier'/);
+});
+
+test('ADO 6691114 global: a global choice the spec does NOT declare has no numbering to fall back on', async () => {
+ // Lint rejects such a column; were it to reach the build, the spec has no number for the label at all.
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Gold')])], { globalChoices: [] });
+ const r = await resolveAll(spec, inlineEnv(RENAMED));
+ assert.strictEqual(r.problems.length, 1);
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Gold'), undefined);
+});
+
+test('ADO 6691114 inline: with two options carrying the label, the spec\'s number settles it only where it is one of them', async () => {
+ const settled = await resolveAll(inlineSpec('Gold'), inlineEnv(opts([100000000, [1033, 'Silver']], [100000001, [1033, 'Gold']], [227350001, [1033, 'Gold']])));
+ assert.deepStrictEqual(settled.problems, []);
+ assert.strictEqual(settled.value('new_customer', 'new_tier', 'Gold'), 100000001);
+ assert.match(settled.warnings[0], /lists more than one option labelled "Gold"/);
+ assert.match(settled.warnings[0], /the spec numbers "Gold" 100000001, which is one of them/);
+ const unsettled = await resolveAll(inlineSpec('Gold'), inlineEnv(opts([5, [1033, 'Gold']], [6, [1033, 'Gold']])));
+ assert.strictEqual(unsettled.problems.length, 1);
+ assert.strictEqual(unsettled.problems[0].reason, 'ambiguous');
+});
+
+test('ADO 6691114 inline: two options carry the label and the spec\'s number is NOT one of them — it is not used, though the environment has an option on it', async () => {
+ // The only thing that stops this is the check that the spec's number is among the options carrying the label:
+ // option 100000001 EXISTS (as "Gold Tier"), so "no such option" cannot be what rejects it.
+ const rows = opts([100000000, [1033, 'Silver']], [100000001, [1033, 'Gold Tier']], [5, [1033, 'Gold']], [6, [1033, 'Gold']]);
+ const r = await resolveAll(inlineSpec('Gold'), inlineEnv(rows));
+ assert.deepStrictEqual(r.problems.map((p) => [p.reason, p.values]), [['ambiguous', [5, 6]]]);
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Gold'), undefined);
+ assert.deepStrictEqual(r.warnings, []);
+ const pre = await preflight(inlineSpec('Gold'), inlineEnv(rows));
+ assert.deepStrictEqual(pre.problems.map((p) => p.reason), ['ambiguous']);
+});
+
+test('ADO 6691114 inline pre-flight: a renamed option is no problem — and is left to the views phase to resolve and warn about', async () => {
+ const spec = inlineSpec('Gold');
+ const renamed = await preflight(spec, inlineEnv(RENAMED));
+ assert.deepStrictEqual(renamed.problems, []);
+ assert.strictEqual(renamed.resolved.size, 0, 'not handed on as final: the warning is the views phase\'s to give');
+ const gone = await preflight(spec, inlineEnv(opts([100000000, [1033, 'Silver']], [5, [1033, 'Gold Tier']])));
+ assert.strictEqual(gone.problems.length, 1);
+});
+
+test('ADO 6691114 inline build: a spec that built before — an option renamed in the environment — still builds, with the spec\'s number and a warning', async () => {
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: RENAMED } } }, record: true });
+ const { error, warnings } = await e.run(inlineSpec('Gold'), { phases: FULL });
+ assert.ifError(error);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Gold customers', 'new_tier'), ['100000001']);
+ assert.strictEqual(warnings.filter((w) => /lists no option labelled "Gold"/.test(w)).length, 1, JSON.stringify(warnings));
+});
+
+test('ADO 6691114 inline build: a localized option the environment holds in one language only still builds, filtered on the other', async () => {
+ // A localized spec has no pre-flight, so this is the views phase alone.
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: BASE_LANGUAGE_ONLY } } }, record: true });
+ const { error, warnings } = await e.run(inlineSpec('Oro', LOCALIZED_TIER), { phases: FULL });
+ assert.ifError(error);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Gold customers', 'new_tier'), ['100000001']);
+ assert.ok(warnings.some((w) => /"Oro"/.test(w) && /100000001/.test(w)), JSON.stringify(warnings));
+});
+
+test('ADO 6691114 inline build: with nothing vouching for the spec\'s number it halts, before anything is written', async () => {
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: opts([100000000, [1033, 'Silver']], [5, [1033, 'Gold Tier']]) } } }, record: true });
+ const { error } = await e.run(inlineSpec('Gold'), { phases: FULL });
+ assert.strictEqual(error && error.code, 'view-filter-label-unresolved');
+ assert.strictEqual(error.phase, 'preflight');
+ assert.match(error.message, /"Gold" is not an option of new_customer\.new_tier\. Valid labels: Silver, Gold Tier\./);
+ assert.deepStrictEqual(writesOf(e.names), []);
+});
+
+test('ADO 6691114 inline dry run: a renamed option leaves the view as create — the build would not stop on it', async () => {
+ const { plan } = await dryRun(inlineSpec('Gold'), { new_customer: { Picklist: { new_tier: RENAMED } } });
+ const item = plan.find((p) => /^view "Gold customers"/.test(p.label));
+ assert.strictEqual(item.state, 'create');
+ assert.strictEqual(item.wouldHalt, undefined);
+});
+
+test('ADO 6691114 inline verify: a view built with the spec\'s number for a renamed option verifies', async () => {
+ const spec = inlineSpec('Gold');
+ const read = makeChoiceReader({ client: inlineEnv(RENAMED) });
+ const check = filterCheck(await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('new_tier', '100000001'), choiceAttributes: read }), { phases: ['views'] }));
+ assert.strictEqual(check.present, true, JSON.stringify(check));
+});
+
+// ── 6g. …but never a number the environment shows belongs to ANOTHER option ──────────────────────────
+//
+// The spec's 100000000 + index is the environment's numbering only for an option set the build created from this
+// very list. A rebuild never changes an existing column's options and does not create a column it finds, so options
+// the author inserted or reordered since — or a column another app made, in another order — leave the two
+// numberings apart, and the spec's number then names ANOTHER option. 2.13.0 bound it blindly. The sign is a label
+// of the spec that the environment carries only on a different number (or the option on the spec's number going by
+// another label of the spec): then the spec's number is not used, the label is simply an option the environment
+// does not have, and the build says so before it writes anything.
+
+const PENDING_COLUMN = { schemaName: 'new_tier', type: 'Choice', options: ['Pending', 'Open', 'Closed'] };
+// The column as it was built, before "Pending" was put at the top of the spec's list.
+const BUILT_WITHOUT_PENDING = opts([100000000, [1033, 'Open']], [100000001, [1033, 'Closed']]);
+
+test('ADO 6691114 numbering: an option the spec gained at the top AFTER the column was built is not bound to the option now on its number', async () => {
+ const spec = inlineSpec('Pending', PENDING_COLUMN);
+ const r = await resolveAll(spec, inlineEnv(BUILT_WITHOUT_PENDING));
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Pending'), undefined);
+ assert.strictEqual(r.problems.length, 1);
+ assert.strictEqual(r.problems[0].reason, 'unknown');
+ assert.match(describeProblems(r.problems), /"Pending" is not an option of new_customer\.new_tier\. Valid labels: Open, Closed\./);
+ assert.deepStrictEqual(r.warnings, [], 'nothing was bound, so there is nothing to warn of');
+ // The pre-flight finds it too, before anything is written…
+ const pre = await preflight(spec, inlineEnv(BUILT_WITHOUT_PENDING));
+ assert.strictEqual(pre.problems.length, 1);
+ assert.deepStrictEqual(pre.notes, []);
+ // …and a label the environment DOES carry is the environment's: Open is 100000000 there, not the spec's 100000001.
+ const open = await resolveAll(inlineSpec('Open', PENDING_COLUMN), inlineEnv(BUILT_WITHOUT_PENDING));
+ assert.strictEqual(open.value('new_customer', 'new_tier', 'Open'), 100000000);
+ assert.deepStrictEqual(open.warnings, []);
+});
+
+test('ADO 6691114 numbering: another label of the spec on a different number refuses the spec\'s number, even when the option on it goes by a name the spec never had', async () => {
+ // The spec lists [Pending, Open, Closed], so Pending is 100000000 and Closed 100000002. The environment was built from
+ // [Open, Closed] and Open has since been renamed "Opened": nothing the environment calls 100000000 is a label of the
+ // spec — but Closed is on 100000001, where the spec has Open, so the two numberings are not the same.
+ const rows = opts([100000000, [1033, 'Opened']], [100000001, [1033, 'Closed']]);
+ const r = await resolveAll(inlineSpec('Pending', PENDING_COLUMN), inlineEnv(rows));
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Pending'), undefined);
+ assert.strictEqual(r.problems.length, 1);
+ assert.deepStrictEqual(r.warnings, []);
+ assert.strictEqual((await preflight(inlineSpec('Pending', PENDING_COLUMN), inlineEnv(rows))).problems.length, 1);
+});
+
+test('ADO 6691114 numbering: options reordered in the spec and one renamed in the environment — the renamed label is not bound to its neighbour', async () => {
+ // Built from [Silver, Gold, Bronze]. The spec now lists [Bronze, Silver, Gold], which numbers Gold 100000002 — the
+ // number the environment's column gives Bronze — and a maker has renamed Gold there to "Gold Tier".
+ const reordered = (label) => inlineSpec(label, { schemaName: 'new_tier', type: 'Choice', options: ['Bronze', 'Silver', 'Gold'] });
+ const env = () => inlineEnv(opts([100000000, [1033, 'Silver']], [100000001, [1033, 'Gold Tier']], [100000002, [1033, 'Bronze']]));
+ const gold = await resolveAll(reordered('Gold'), env());
+ assert.strictEqual(gold.value('new_customer', 'new_tier', 'Gold'), undefined);
+ assert.strictEqual(gold.problems.length, 1);
+ assert.match(describeProblems(gold.problems), /"Gold" is not an option of new_customer\.new_tier\. Valid labels: Silver, Gold Tier, Bronze\./);
+ assert.deepStrictEqual(gold.warnings, []);
+ assert.strictEqual((await preflight(reordered('Gold'), env())).problems.length, 1);
+ const bronze = await resolveAll(reordered('Bronze'), env());
+ assert.strictEqual(bronze.value('new_customer', 'new_tier', 'Bronze'), 100000002, 'what the environment names, it names');
+});
+
+test('ADO 6691114 numbering: a localized label the environment lacks is not bound to a number the environment gives another option', async () => {
+ // The environment's column was built in the other order, in the base language only: its 100000001 is Silver,
+ // which the spec numbers 100000000. "Oro" is Gold's Spanish label, so it must not become Silver.
+ const swapped = opts([100000000, [1033, 'Gold']], [100000001, [1033, 'Silver']]);
+ const r = await resolveAll(inlineSpec('Oro', LOCALIZED_TIER), inlineEnv(swapped));
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Oro'), undefined);
+ assert.strictEqual(r.problems.length, 1);
+ assert.match(describeProblems(r.problems), /"Oro" is not an option of new_customer\.new_tier\. Valid labels: Gold, Silver\./);
+ assert.deepStrictEqual(r.warnings, []);
+});
+
+test('ADO 6691114 numbering: a label of the spec the environment carries in ANOTHER language of an option on a different number counts as carried there', async () => {
+ // "Plata" (Silver's Spanish label, 100000000 in the spec) is on 100000001 in the environment, as that option's second
+ // language — so the numberings differ, whichever language the label is read in.
+ const column = { schemaName: 'new_tier', type: 'Choice', options: [{ 1033: 'Silver', 3082: 'Plata' }, { 1033: 'Gold', 3082: 'Oro' }, { 1033: 'Bronze', 3082: 'Bronce' }] };
+ const rows = opts([100000000, [1033, 'Silver']], [100000001, [1033, 'Gold Tier'], [3082, 'Plata']], [100000002, [1033, 'Bronze']]);
+ const r = await resolveAll(inlineSpec('Bronce', column), inlineEnv(rows));
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Bronce'), undefined);
+ assert.strictEqual(r.problems.length, 1);
+ assert.deepStrictEqual(r.warnings, []);
+});
+
+test('ADO 6691114 numbering: an inline column of a table the build did not create, numbered otherwise there, is not bound by the spec\'s numbers', async () => {
+ const priority = { schemaName: 'new_priority', type: 'Choice', options: ['Low', 'Medium', 'High', 'Critical'] };
+ const spec = (label) => specOf([customer([priority], { existing: true })], [view('new_customer', [eq('new_priority', label)])]);
+ // The column came from elsewhere, in another order, and has no "Critical": its 100000003 is Medium.
+ const there = () => choiceClient({ new_customer: { Picklist: { new_priority: opts([100000000, [1033, 'Low']], [100000001, [1033, 'High']], [100000002, [1033, 'Urgent']], [100000003, [1033, 'Medium']]) } } });
+ const r = await resolveAll(spec('Critical'), there());
+ assert.strictEqual(r.value('new_customer', 'new_priority', 'Critical'), undefined);
+ assert.strictEqual(r.problems.length, 1);
+ assert.deepStrictEqual(r.warnings, []);
+ assert.strictEqual((await preflight(spec('Critical'), there())).problems.length, 1);
+});
+
+test('ADO 6691114 numbering: the option on the spec\'s number must not go by the name of another option of the spec — even one that is also on its own number', async () => {
+ const tiers = { schemaName: 'new_tier', type: 'Choice', options: ['Gold', 'Silver', 'Bronze'] };
+ // Silver is on 100000001 as the spec says, but ALSO on 100000000 — the number the spec gives Gold. Every label of the
+ // spec the environment carries is on its own number, so only the name the option on 100000000 goes by gives it away.
+ const rows = opts([100000000, [1033, 'Silver']], [100000001, [1033, 'Silver']], [100000002, [1033, 'Bronze']]);
+ const r = await resolveAll(inlineSpec('Gold', tiers), inlineEnv(rows));
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Gold'), undefined);
+ assert.strictEqual(r.problems.length, 1);
+ assert.deepStrictEqual(r.warnings, []);
+});
+
+test('ADO 6691114 numbering: a multi-select column is judged the same way — a renamed option keeps the spec\'s number, a shifted numbering halts', async () => {
+ const tags = { schemaName: 'new_tags', type: 'MultiChoice', options: ['Silver', 'Gold'] };
+ const spec = (label) => specOf([customer([tags])], [{ entity: 'new_customer', name: 'Tagged', columns: ['new_name'], filters: [{ attr: 'new_tags', op: 'contain-values', value: label }] }]);
+ const env = (rows) => choiceClient({ new_customer: { MultiSelectPicklist: { new_tags: rows } } });
+ const renamed = await resolveAll(spec('Gold'), env(RENAMED));
+ assert.deepStrictEqual(renamed.problems, []);
+ assert.strictEqual(renamed.value('new_customer', 'new_tags', 'Gold'), 100000001);
+ assert.strictEqual(renamed.warnings.length, 1);
+ const shifted = await resolveAll(spec('Gold'), env(opts([100000000, [1033, 'Gold Tier']], [100000001, [1033, 'Silver']])));
+ assert.strictEqual(shifted.value('new_customer', 'new_tags', 'Gold'), undefined);
+ assert.strictEqual(shifted.problems.length, 1);
+});
+
+test('ADO 6691114 numbering pre-flight: a renamed option is a NOTE — for the dry run to say — and still no problem', async () => {
+ const pre = await preflight(inlineSpec('Gold'), inlineEnv(RENAMED));
+ assert.deepStrictEqual(pre.problems, []);
+ assert.strictEqual(pre.notes.length, 1);
+ assert.match(pre.notes[0], /lists no option labelled "Gold" on 'new_customer'\.'new_tier'/);
+ assert.match(pre.notes[0], /100000001/);
+ const named = await preflight(inlineSpec('Silver'), inlineEnv(RENAMED));
+ assert.deepStrictEqual(named.notes, [], 'a label the environment names has nothing to note');
+});
+
+test('ADO 6691114 numbering build: options inserted in the spec after the column was built halt before anything is written', async () => {
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: BUILT_WITHOUT_PENDING } } }, record: true });
+ const { error, warnings } = await e.run(inlineSpec('Pending', PENDING_COLUMN), { phases: FULL });
+ assert.strictEqual(error && error.code, 'view-filter-label-unresolved');
+ assert.strictEqual(error.phase, 'preflight');
+ assert.match(error.message, /"Pending" is not an option of new_customer\.new_tier\. Valid labels: Open, Closed\./);
+ assert.deepStrictEqual(writesOf(e.names), []);
+ assert.deepStrictEqual(warnings, []);
+});
+
+test('ADO 6691114 numbering build: a localized spec has no pre-flight, so the views phase halts — still before any view is written', async () => {
+ const swapped = opts([100000000, [1033, 'Gold']], [100000001, [1033, 'Silver']]);
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: swapped } } }, record: true });
+ const { error } = await e.run(inlineSpec('Oro', LOCALIZED_TIER), { phases: FULL });
+ assert.strictEqual(error && error.code, 'view-filter-label-unresolved');
+ assert.strictEqual(error.phase, 'views');
+ assert.match(error.message, /"Oro" is not an option of new_customer\.new_tier\. Valid labels: Gold, Silver\./);
+ assert.deepStrictEqual(e.defs.filter(([type]) => type === 'view'), []);
+ assert.deepStrictEqual(e.pushed, []);
+});
+
+test('ADO 6691114 numbering dry run: a label the build would stop on is unknown — one it would bind is create, and the note is said', async () => {
+ const warned = [];
+ const stop = await dryRun(inlineSpec('Pending', PENDING_COLUMN), { new_customer: { Picklist: { new_tier: BUILT_WITHOUT_PENDING } } }, [], { warn: (m) => warned.push(m) });
+ const item = stop.plan.find((p) => /^view "Gold customers"/.test(p.label));
+ assert.strictEqual(item.state, 'unknown');
+ assert.strictEqual(item.wouldHalt, true);
+ assert.match(item.stateWhy, /"Pending" is not an option of new_customer\.new_tier\. Valid labels: Open, Closed\./);
+ assert.deepStrictEqual(warned, []);
+ const bound = await dryRun(inlineSpec('Gold'), { new_customer: { Picklist: { new_tier: RENAMED } } }, [], { warn: (m) => warned.push(m) });
+ assert.strictEqual(bound.plan.find((p) => /^view "Gold customers"/.test(p.label)).state, 'create');
+ assert.strictEqual(warned.length, 1, JSON.stringify(warned));
+ assert.match(warned[0], /lists no option labelled "Gold" on 'new_customer'\.'new_tier'/);
+ assert.match(warned[0], /100000001/);
+});
+
+test('ADO 6691114 numbering dry run: a note several views would give is said once', async () => {
+ const warned = [];
+ const spec = specOf([customer([INLINE_TIER])], [view('new_customer', [eq('new_tier', 'Gold')], 'One'), view('new_customer', [eq('new_tier', 'Gold')], 'Two')]);
+ const { plan } = await dryRun(spec, { new_customer: { Picklist: { new_tier: RENAMED } } }, [], { warn: (m) => warned.push(m) });
+ assert.deepStrictEqual(plan.filter((p) => /^view /.test(p.label)).map((p) => p.state), ['create', 'create']);
+ assert.strictEqual(warned.length, 1, JSON.stringify(warned));
+});
+
+test('ADO 6691114 numbering verify: the spec\'s number is not what verify expects where the environment shows another numbering', async () => {
+ const spec = inlineSpec('Pending', PENDING_COLUMN);
+ const read = makeChoiceReader({ client: inlineEnv(BUILT_WITHOUT_PENDING) });
+ // 100000000 is what 2.13.0 would have deployed for "Pending" — and is Open in this environment.
+ const check = filterCheck(await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('new_tier', '100000000'), choiceAttributes: read }), { phases: ['views'] }));
+ assert.strictEqual(check.present, false);
+ assert.match(check.detail, /"Pending" is not an option of new_customer\.new_tier\. Valid labels: Open, Closed\./);
+});
+
+// ── 6f. a column bound to a global choice, whose own options could not be read ───────────────────────
+
+test('ADO 6691114 global: when a column\'s own options cannot be read, the global choice is read itself — not guessed at from the spec\'s numbering', async () => {
+ const spec = (label) => specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', label)])]);
+ const resolve = (label, options) => {
+ const client = choiceClient({ new_customer: {} }, { failCast: 'Picklist', status: 503, ...options });
+ return resolveViewFilterLabels(spec(label), spec(label).views, { read: makeChoiceReader({ client }), readGlobalChoice: makeGlobalChoiceReader({ client }) });
+ };
+ // The set exists with Gold = 227350001; the spec numbers it 100000001.
+ const r = await resolve('Gold', { globalSets: { new_tierset: TIER } });
+ assert.deepStrictEqual(r.problems, []);
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Gold'), 227350001);
+ assert.deepStrictEqual(r.warnings, [], 'nothing was guessed, so nothing to warn of');
+ assert.deepStrictEqual(r.inconclusive, []);
+ // A label the set does not have is the set's problem, naming its labels.
+ const typo = await resolve('Platinum', { globalSets: { new_tierset: TIER } });
+ assert.strictEqual(typo.problems.length, 1);
+ assert.match(describeProblems(typo.problems), /Valid labels: Silver, Gold, Bronze\./);
+ // With no set to read either, the spec's numbering is the fallback it always was — with its warning.
+ const none = await resolve('Gold', { failGlobal: true });
+ assert.strictEqual(none.value('new_customer', 'new_tier', 'Gold'), 100000001);
+ assert.match(none.warnings[0], /spec's own numbering \(100000001\)/);
+});
+
+test('ADO 6691114 global build: in a spec with a localized label — so no pre-flight, nothing handed on — a failed views-phase read resolves from the global choice', async () => {
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_other: TIER } } }, globalSets: { new_tierset: TIER }, record: true });
+ failOptionReadsAfterTheDataModel(e);
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN, { schemaName: 'new_note', type: 'Text', displayName: NOTE }])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const { error, warnings } = await e.run(spec, { phases: FULL });
+ assert.ifError(error);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Gold customers', 'new_tier'), ['227350001']);
+ assert.deepStrictEqual(warnings.filter((w) => /numbering/.test(w)), []);
+});
+
+// ── 6h. a renamed option in a global choice the spec DECLARES ────────────────────────────────────────
+//
+// 2.13.0 numbered a declared global choice 100000000 + index and built the view with that, with no read — so an app
+// it built, whose maker later renamed an option of the set, built and verified. Halting it now would be a regression
+// the maker could not see coming (nobody touched the spec), and `build --apply --verify` would fail on every run.
+// What protects against a set that is ANOTHER app's is what protects an inline column: the check of the environment
+// (6g) — a set numbered in another order or from another publisher's range is not bound.
+
+const GLOBAL_RENAMED = opts([100000000, [1033, 'Silver']], [100000001, [1033, 'Gold Tier']], [100000002, [1033, 'Bronze']]);
+// The set as another app made it: another order, so the environment's 100000001 is Silver — and, separately, from
+// another publisher's range, where nothing sits on the spec's numbers at all.
+const GLOBAL_OTHER_ORDER = opts([100000000, [1033, 'Bronze']], [100000001, [1033, 'Silver']], [100000002, [1033, 'Gold Tier']]);
+const GLOBAL_OTHER_RANGE = opts([727000000, [1033, 'Silver']], [727000001, [1033, 'Gold Tier']], [727000002, [1033, 'Bronze']]);
+const globalSpec = (label = 'Gold', extra) => specOf([customer([GLOBAL_TIER_COLUMN, ...(extra || [])])], [view('new_customer', [eq('new_tier', label)])]);
+const withTierColumn = (rows) => ({ new_customer: { Picklist: { new_tier: rows } } });
+const withoutTierColumn = { new_customer: { Picklist: { new_other: TIER } } };
+
+test('ADO 6691114 global: a renamed option of a declared global choice is no problem in the pre-flight — a note, handed on to the views phase to resolve', async () => {
+ // The column is there: its own options say it.
+ const there = await preflight(globalSpec('Gold'), choiceClient(withTierColumn(GLOBAL_RENAMED)));
+ assert.deepStrictEqual(there.problems, []);
+ assert.strictEqual(there.resolved.size, 0, 'the warning is the views phase\'s to give');
+ assert.strictEqual(there.notes.length, 1);
+ // The column is not: the build creates it against the set that exists, so the SET is what says.
+ const creating = await preflight(globalSpec('Gold'), choiceClient(withoutTierColumn, { globalSets: { new_tierset: GLOBAL_RENAMED } }));
+ assert.deepStrictEqual(creating.problems, []);
+ assert.strictEqual(creating.resolved.size, 0);
+ assert.strictEqual(creating.notes.length, 1);
+ assert.match(creating.notes[0], /lists no option labelled "Gold" on 'new_customer'\.'new_tier'/);
+ // A label the set does name is final, as it was.
+ const named = await preflight(globalSpec('Silver'), choiceClient(withoutTierColumn, { globalSets: { new_tierset: GLOBAL_RENAMED } }));
+ assert.strictEqual(named.resolved.get('new_customer|new_tier|Silver'), 100000000);
+ assert.deepStrictEqual(named.notes, []);
+});
+
+test('ADO 6691114 global: a set another app numbered otherwise is not bound by the spec\'s numbers — in another order or another range, column there or not', async () => {
+ for (const rows of [GLOBAL_OTHER_ORDER, GLOBAL_OTHER_RANGE]) {
+ const label = JSON.stringify(rows.map((r) => r.Value));
+ const resolved = await resolveAll(globalSpec('Gold'), choiceClient(withTierColumn(rows)));
+ assert.strictEqual(resolved.value('new_customer', 'new_tier', 'Gold'), undefined, label);
+ assert.strictEqual(resolved.problems.length, 1, label);
+ assert.deepStrictEqual(resolved.warnings, [], label);
+ const column = await preflight(globalSpec('Gold'), choiceClient(withTierColumn(rows)));
+ assert.strictEqual(column.problems.length, 1, label);
+ const set = await preflight(globalSpec('Gold'), choiceClient(withoutTierColumn, { globalSets: { new_tierset: rows } }));
+ assert.strictEqual(set.problems.length, 1, label);
+ assert.deepStrictEqual(set.notes, [], label);
+ }
+});
+
+test('ADO 6691114 global: when the column\'s own options cannot be read, the set read for the views phase follows the same rule', async () => {
+ const resolve = (label, rows) => {
+ const client = choiceClient({ new_customer: {} }, { failCast: 'Picklist', status: 503, globalSets: { new_tierset: rows } });
+ const spec = globalSpec(label);
+ return resolveViewFilterLabels(spec, spec.views, { read: makeChoiceReader({ client }), readGlobalChoice: makeGlobalChoiceReader({ client }) });
+ };
+ const renamed = await resolve('Gold', GLOBAL_RENAMED);
+ assert.deepStrictEqual(renamed.problems, []);
+ assert.strictEqual(renamed.value('new_customer', 'new_tier', 'Gold'), 100000001);
+ assert.strictEqual(renamed.warnings.length, 1, JSON.stringify(renamed.warnings));
+ assert.match(renamed.warnings[0], /lists no option labelled "Gold" on 'new_customer'\.'new_tier'/);
+ for (const rows of [GLOBAL_OTHER_ORDER, GLOBAL_OTHER_RANGE]) {
+ const other = await resolve('Gold', rows);
+ assert.strictEqual(other.value('new_customer', 'new_tier', 'Gold'), undefined);
+ assert.strictEqual(other.problems.length, 1);
+ }
+});
+
+test('ADO 6691114 global build: an app 2.13.0 built, a maker having renamed an option of the set since, still builds — the spec\'s number and a warning', async () => {
+ const e = viewsEngine({ byTable: withTierColumn(GLOBAL_RENAMED), globalSets: { new_tierset: GLOBAL_RENAMED }, record: true });
+ const { error, warnings } = await e.run(globalSpec('Gold'), { phases: FULL });
+ assert.ifError(error);
+ assert.ok(writesOf(e.names).length > 0, 'the build went on to write');
+ assert.deepStrictEqual(viewCondition(e.defs, 'Gold customers', 'new_tier'), ['100000001']);
+ assert.strictEqual(warnings.filter((w) => /lists no option labelled "Gold"/.test(w)).length, 1, JSON.stringify(warnings));
+});
+
+test('ADO 6691114 global build: a column the build creates against an existing set whose option was renamed builds too', async () => {
+ // Nothing in the environment carries the column yet, so the pre-flight reads the set — and the views phase, whose
+ // column read finds nothing in this stub environment either, reads it again.
+ const e = viewsEngine({ byTable: withoutTierColumn, globalSets: { new_tierset: GLOBAL_RENAMED }, record: true });
+ const { error, warnings } = await e.run(globalSpec('Gold'), { phases: FULL });
+ assert.ifError(error);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Gold customers', 'new_tier'), ['100000001']);
+ assert.strictEqual(warnings.filter((w) => /lists no option labelled "Gold"/.test(w)).length, 1, JSON.stringify(warnings));
+});
+
+test('ADO 6691114 global build: a spec with a localized label — no pre-flight — builds the same way, instead of halting after the data model', async () => {
+ const e = viewsEngine({ byTable: withTierColumn(GLOBAL_RENAMED), globalSets: { new_tierset: GLOBAL_RENAMED }, record: true });
+ const { error, warnings } = await e.run(globalSpec('Gold', [{ schemaName: 'new_note', type: 'Text', displayName: NOTE }]), { phases: FULL });
+ assert.ifError(error);
+ assert.deepStrictEqual(viewCondition(e.defs, 'Gold customers', 'new_tier'), ['100000001']);
+ assert.strictEqual(warnings.filter((w) => /lists no option labelled "Gold"/.test(w)).length, 1, JSON.stringify(warnings));
+});
+
+test('ADO 6691114 global build: a set another app numbered otherwise halts before anything is written', async () => {
+ const e = viewsEngine({ byTable: withTierColumn(GLOBAL_OTHER_ORDER), globalSets: { new_tierset: GLOBAL_OTHER_ORDER }, record: true });
+ const { error, warnings } = await e.run(globalSpec('Gold'), { phases: FULL });
+ assert.strictEqual(error && error.code, 'view-filter-label-unresolved');
+ assert.strictEqual(error.phase, 'preflight');
+ assert.match(error.message, /"Gold" is not an option of new_customer\.new_tier\. Valid labels: Bronze, Silver, Gold Tier\./);
+ assert.deepStrictEqual(writesOf(e.names), []);
+ assert.deepStrictEqual(warnings, []);
+});
+
+test('ADO 6691114 global build: a view that already exists, over a set whose option was renamed, neither says verify will fail nor halts', async () => {
+ const e = viewsEngine({ byTable: withTierColumn(GLOBAL_RENAMED), globalSets: { new_tierset: GLOBAL_RENAMED }, existingViews: ['Gold customers'], record: true });
+ const { error, warnings } = await e.run(globalSpec('Gold'), { phases: FULL });
+ assert.ifError(error);
+ assert.deepStrictEqual(warnings.filter((w) => /verify will report/.test(w)), []);
+});
+
+test('ADO 6691114 global verify: a view built with the spec\'s number over a renamed option of a declared global choice verifies — as under 2.13.0', async () => {
+ const spec = globalSpec('Gold');
+ const read = () => makeChoiceReader({ client: choiceClient(withTierColumn(GLOBAL_RENAMED)) });
+ const check = filterCheck(await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('new_tier', '100000001'), choiceAttributes: read() }), { phases: ['views'] }));
+ assert.strictEqual(check.present, true, JSON.stringify(check));
+ // A set numbered otherwise is still what verify reports against, with the valid labels.
+ const foreign = () => makeChoiceReader({ client: choiceClient(withTierColumn(GLOBAL_OTHER_ORDER)) });
+ const bad = filterCheck(await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('new_tier', '100000001'), choiceAttributes: foreign() }), { phases: ['views'] }));
+ assert.strictEqual(bad.present, false);
+ assert.match(bad.detail, /"Gold" is not an option of new_customer\.new_tier\. Valid labels: Bronze, Silver, Gold Tier\./);
+});
+
+test('ADO 6691114 global dry run: a renamed option of the set leaves the view as create, with the note said; another app\'s numbering is unknown', async () => {
+ const warned = [];
+ const bound = await dryRun(globalSpec('Gold'), withoutTierColumn, [], { globalSets: { new_tierset: GLOBAL_RENAMED }, warn: (m) => warned.push(m) });
+ const item = bound.plan.find((p) => /^view "Gold customers"/.test(p.label));
+ assert.strictEqual(item.state, 'create');
+ assert.strictEqual(item.wouldHalt, undefined);
+ assert.strictEqual(warned.length, 1, JSON.stringify(warned));
+ assert.match(warned[0], /lists no option labelled "Gold"/);
+ const stop = await dryRun(globalSpec('Gold'), withoutTierColumn, [], { globalSets: { new_tierset: GLOBAL_OTHER_RANGE } });
+ const refused = stop.plan.find((p) => /^view "Gold customers"/.test(p.label));
+ assert.strictEqual(refused.state, 'unknown');
+ assert.strictEqual(refused.wouldHalt, true);
+});
+
+// ── 6i. a maker's OWN edits are not another numbering — and every refusal says why ───────────────────
+//
+// 6g refuses the spec's number when the environment shows the numbering MOVED. A maker's own edits do not move it:
+// an option added in the Default solution takes another publisher's range, and one deleted and re-created takes the
+// next free number, so every number the spec has stays where it was. A spec that 2.13.0 built right after such edits
+// plus a rename of the filtered option must still build — with the warning — instead of stopping on an option the spec
+// merely did not know about. A refusal, where there still is one, says why the spec's number was not used.
+
+const THREE_TIERS = { schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold', 'Bronze'] };
+const FOUR_TIERS = { schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold', 'Bronze', 'Platinum'] };
+// What 2.13.0 sent for the spec's filter: its own number, with no look at the environment.
+const sentBy213 = (spec) => String(viewDef(spec, spec.views[0]).filters.conditions.find((c) => c.attribute === 'new_tier').value);
+// [shape, the spec's column, what the environment holds] — "Gold" was renamed "Gold Tier" in each.
+const MAKER_EDITS = [
+ ['an option added in another publisher\'s range', FOUR_TIERS, opts([100000000, [1033, 'Silver']], [100000001, [1033, 'Gold Tier']], [100000002, [1033, 'Bronze']], [797700000, [1033, 'Platinum']])],
+ ['an option deleted and re-created at the next free number', THREE_TIERS, opts([100000000, [1033, 'Silver']], [100000001, [1033, 'Gold Tier']], [100000003, [1033, 'Bronze']])],
+ ['an option re-created in another publisher\'s range', THREE_TIERS, opts([100000000, [1033, 'Silver']], [100000001, [1033, 'Gold Tier']], [797700000, [1033, 'Bronze']])],
+];
+
+test('ADO 6691114 maker edits: an option a maker added or re-made elsewhere, and another renamed, still resolve to the spec\'s number — what 2.13.0 sent — with a warning', async () => {
+ for (const [shape, column, rows] of MAKER_EDITS) {
+ const spec = inlineSpec('Gold', column);
+ const r = await resolveAll(spec, inlineEnv(rows));
+ assert.deepStrictEqual(r.problems, [], shape);
+ assert.strictEqual(String(r.value('new_customer', 'new_tier', 'Gold')), sentBy213(spec), shape);
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Gold'), 100000001, shape);
+ assert.strictEqual(r.warnings.length, 1, `${shape}: ${JSON.stringify(r.warnings)}`);
+ assert.match(r.warnings[0], /labelled "Gold Tier"/, shape);
+ const pre = await preflight(spec, inlineEnv(rows));
+ assert.deepStrictEqual(pre.problems, [], shape);
+ assert.strictEqual(pre.notes.length, 1, shape);
+ }
+});
+
+test('ADO 6691114 maker edits build: it goes on, writes the spec\'s number and warns once — for a new view and for one that already exists', async () => {
+ for (const [shape, column, rows] of MAKER_EDITS) {
+ const spec = inlineSpec('Gold', column);
+ for (const existingViews of [[], ['Gold customers']]) {
+ const what = `${shape}${existingViews.length ? ', the view exists' : ''}`;
+ const e = viewsEngine({ byTable: withTierColumn(rows), existingViews, record: true });
+ const { error, warnings } = await e.run(spec, { phases: FULL });
+ assert.ok(!error, `${what}: ${error && error.message}`);
+ assert.ok(writesOf(e.names).length > 0, `${what}: the build went on to write`);
+ if (!existingViews.length) assert.deepStrictEqual(viewCondition(e.defs, 'Gold customers', 'new_tier'), [sentBy213(spec)], what);
+ assert.strictEqual(warnings.filter((w) => /lists no option labelled "Gold"/.test(w)).length, 1, `${what}: ${JSON.stringify(warnings)}`);
+ assert.deepStrictEqual(warnings.filter((w) => /verify will report/.test(w)), [], what);
+ }
+ }
+});
+
+test('ADO 6691114 maker edits verify and dry run: a view built that way verifies, and the dry run leaves a new one as create — with the assumption said', async () => {
+ for (const [shape, column, rows] of MAKER_EDITS) {
+ const spec = inlineSpec('Gold', column);
+ const read = makeChoiceReader({ client: inlineEnv(rows) });
+ const check = filterCheck(await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('new_tier', sentBy213(spec)), choiceAttributes: read }), { phases: ['views'] }));
+ assert.strictEqual(check.present, true, `${shape}: ${JSON.stringify(check)}`);
+ const warned = [];
+ const { plan } = await dryRun(spec, withTierColumn(rows), [], { warn: (m) => warned.push(m) });
+ const item = plan.find((p) => /^view "Gold customers"/.test(p.label));
+ assert.strictEqual(item.state, 'create', shape);
+ assert.strictEqual(item.wouldHalt, undefined, shape);
+ assert.strictEqual(warned.length, 1, `${shape}: ${JSON.stringify(warned)}`);
+ }
+});
+
+test('ADO 6691114 maker edits: the filtered option\'s OWN label found on another number is still a sign the numbering moved — in whatever range that number is', async () => {
+ // "Oro" is Gold's Spanish label and the spec numbers Gold 100000000. The environment carries "Oro" on an option in another
+ // publisher's range, so the option the spec calls Gold is THERE: 100000000, which is called "Gold Tier", is not it.
+ const column = { schemaName: 'new_tier', type: 'Choice', options: [{ 1033: 'Gold', 3082: 'Oro' }, { 1033: 'Silver', 3082: 'Plata' }] };
+ const rows = opts([100000000, [1033, 'Gold Tier']], [100000001, [1033, 'Silver'], [3082, 'Plata']], [797700000, [3082, 'Oro']]);
+ const spec = inlineSpec('Gold', column);
+ const r = await resolveAll(spec, inlineEnv(rows));
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Gold'), undefined);
+ assert.strictEqual(r.problems.length, 1);
+ assert.match(describeProblems(r.problems), /\("Oro" is numbered 797700000 there, 100000000 in the spec\), so that number is not used\./);
+ assert.deepStrictEqual(r.warnings, []);
+ assert.strictEqual((await preflight(spec, inlineEnv(rows))).problems.length, 1);
+});
+
+test('ADO 6691114 maker edits: the price of the rule — a column made elsewhere with an extra option, whose filtered option was renamed, binds the spec\'s number as 2.13.0 did, and never silently', async () => {
+ // The spec lists [Silver, Gold]. The environment's column was made elsewhere — [Gold Tier, Platinum, Silver] — so its
+ // 100000001, the spec's number for Gold, is "Platinum". Silver is on 100000002, a number the spec does not use: that reads
+ // as an option added elsewhere, not as a shift, so nothing contradicts the spec's number (nor confirms it). The value is
+ // the one 2.13.0 sent, and every place that binds it says what it landed on.
+ const spec = inlineSpec('Gold');
+ const rows = opts([100000000, [1033, 'Gold Tier']], [100000001, [1033, 'Platinum']], [100000002, [1033, 'Silver']]);
+ const r = await resolveAll(spec, inlineEnv(rows));
+ assert.deepStrictEqual(r.problems, []);
+ assert.strictEqual(String(r.value('new_customer', 'new_tier', 'Gold')), sentBy213(spec), 'never a different value than 2.13.0 sent');
+ assert.strictEqual(r.warnings.length, 1);
+ assert.match(r.warnings[0], /option with that number, labelled "Platinum"/);
+ assert.match(r.warnings[0], /on the assumption that it is the same option under another label/);
+ for (const existingViews of [[], ['Gold customers']]) {
+ const e = viewsEngine({ byTable: withTierColumn(rows), existingViews, record: true });
+ const { error, warnings } = await e.run(spec, { phases: FULL });
+ assert.ok(!error, error && error.message);
+ assert.strictEqual(warnings.filter((w) => /labelled "Platinum"/.test(w)).length, 1, `${existingViews.length ? 'view exists' : 'new view'}: ${JSON.stringify(warnings)}`);
+ if (!existingViews.length) assert.deepStrictEqual(viewCondition(e.defs, 'Gold customers', 'new_tier'), [sentBy213(spec)]);
+ const said = [];
+ await dryRun(spec, withTierColumn(rows), existingViews, { warn: (m) => said.push(m) });
+ assert.strictEqual(said.filter((w) => /labelled "Platinum"/.test(w)).length, 1, `dry run, ${existingViews.length ? 'view exists' : 'new view'}: ${JSON.stringify(said)}`);
+ }
+});
+
+test('ADO 6691114 refusal: every refusal of the spec\'s number says why — and a label the spec never numbered does not pretend to have had one', async () => {
+ const oroColumn = { schemaName: 'new_tier', type: 'Choice', options: [{ 1033: 'Gold', 3082: 'Oro' }, { 1033: 'Silver', 3082: 'Plata' }] };
+ const cases = [
+ ['no option on the number', inlineSpec('Gold'), opts([100000000, [1033, 'Silver']], [5, [1033, 'Gold Tier']]),
+ /The spec numbers "Gold" 100000001, but the environment has no option numbered 100000001, so that number is not used\./],
+ ['the option on the number goes by another option of the spec', inlineSpec('Pending', PENDING_COLUMN), BUILT_WITHOUT_PENDING,
+ /The spec numbers "Pending" 100000000, but the environment shows another numbering \(the option numbered 100000000 there is labelled "Open", which the spec numbers 100000001\), so that number is not used\./],
+ ['a label of the spec moved to a number the spec gives another option', inlineSpec('Pending', PENDING_COLUMN), opts([100000000, [1033, 'Opened']], [100000001, [1033, 'Closed']]),
+ /but the environment shows another numbering \("Closed" is numbered 100000001 there, 100000002 in the spec\), so that number is not used\./],
+ ['the filtered option\'s own alias moved', inlineSpec('Gold', oroColumn), opts([100000000, [1033, 'Gold Tier']], [100000001, [1033, 'Silver'], [3082, 'Plata']], [797700000, [3082, 'Oro']]),
+ /but the environment shows another numbering \("Oro" is numbered 797700000 there, 100000000 in the spec\), so that number is not used\./],
+ ['two options carry the label and neither is on the spec\'s number', inlineSpec('Gold'), opts([100000000, [1033, 'Silver']], [100000001, [1033, 'Gold Tier']], [5, [1033, 'Gold']], [6, [1033, 'Gold']]),
+ /names more than one option \(5, 6\), so it cannot choose between them\. The spec numbers "Gold" 100000001, but the environment shows another numbering \("Gold" is numbered 5 and 6 there, 100000001 in the spec\), so that number is not used\. Use the integer value of the one you mean\./],
+ ];
+ for (const [shape, spec, rows, said] of cases) {
+ const r = await resolveAll(spec, inlineEnv(rows));
+ assert.strictEqual(r.problems.length, 1, shape);
+ assert.match(describeProblems(r.problems), said, shape);
+ const pre = await preflight(spec, inlineEnv(rows));
+ assert.match(describeProblems(pre.problems), said, `${shape}: the pre-flight says it too`);
+ }
+ // A typo has no number to refuse; neither does a column the spec does not number at all.
+ const typo = await resolveAll(inlineSpec('Platinum'), inlineEnv(RENAMED));
+ assert.strictEqual(typo.problems.length, 1);
+ assert.doesNotMatch(describeProblems(typo.problems), /The spec numbers/);
+ const industry = await resolveAll(specOf([ACCOUNT], [view('account', [eq('industrycode', 'Accountig')], 'Accounts')]), choiceClient({ account: { Picklist: { industrycode: INDUSTRY } } }));
+ assert.strictEqual(industry.problems.length, 1);
+ assert.doesNotMatch(describeProblems(industry.problems), /The spec numbers/);
+});
+
+test('ADO 6691114 refusal: the reason reaches every place the problem is reported — both halts, the dry run, verify, and the line for a view that already exists', async () => {
+ const REASON = /The spec numbers "Pending" 100000000, but the environment shows another numbering \(the option numbered 100000000 there is labelled "Open", which the spec numbers 100000001\), so that number is not used\./;
+ const spec = inlineSpec('Pending', PENDING_COLUMN);
+ const byTable = withTierColumn(BUILT_WITHOUT_PENDING);
+ const preflightHalt = await viewsEngine({ byTable, record: true }).run(spec, { phases: FULL });
+ assert.strictEqual(preflightHalt.error && preflightHalt.error.phase, 'preflight');
+ assert.match(preflightHalt.error.message, REASON);
+ const viewsHalt = await viewsEngine({ byTable }).run(spec, { phases: ['views'] });
+ assert.strictEqual(viewsHalt.error && viewsHalt.error.phase, 'views');
+ assert.match(viewsHalt.error.message, REASON);
+ const { plan } = await dryRun(spec, byTable);
+ assert.match(plan.find((p) => /^view "Gold customers"/.test(p.label)).stateWhy, REASON);
+ const read = makeChoiceReader({ client: inlineEnv(BUILT_WITHOUT_PENDING) });
+ const check = filterCheck(await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('new_tier', '100000000'), choiceAttributes: read }), { phases: ['views'] }));
+ assert.match(check.detail, REASON);
+ // A view that exists is not stopped on, so the line that says verify will report it carries the reason too.
+ const existing = await viewsEngine({ byTable, existingViews: ['Gold customers'], record: true }).run(spec, { phases: FULL });
+ assert.ok(!existing.error, existing.error && existing.error.message);
+ const line = existing.warnings.find((w) => /already exists/.test(w));
+ assert.match(line, /verify will report that\. The spec numbers "Pending" 100000000, but the environment shows another numbering/);
+ assert.match(line, REASON);
+});
+
+test('ADO 6691114 refusal: a declared global choice says why too — from the column\'s own read, and from the set itself', async () => {
+ const noOption = /but the environment has no option numbered 100000001, so that number is not used\./;
+ const otherOrder = /\(the option numbered 100000001 there is labelled "Silver", which the spec numbers 100000000\), so that number is not used\./;
+ for (const [rows, said] of [[GLOBAL_OTHER_RANGE, noOption], [GLOBAL_OTHER_ORDER, otherOrder]]) {
+ const spec = globalSpec('Gold');
+ const column = await resolveAll(spec, choiceClient(withTierColumn(rows)));
+ assert.match(describeProblems(column.problems), said, 'the views phase, the column read');
+ const set = await preflight(spec, choiceClient(withoutTierColumn, { globalSets: { new_tierset: rows } }));
+ assert.match(describeProblems(set.problems), said, 'the pre-flight, the set read');
+ const failing = choiceClient({ new_customer: {} }, { failCast: 'Picklist', status: 503, globalSets: { new_tierset: rows } });
+ const viaSet = await resolveViewFilterLabels(spec, spec.views, { read: makeChoiceReader({ client: failing }), readGlobalChoice: makeGlobalChoiceReader({ client: failing }) });
+ assert.match(describeProblems(viaSet.problems), said, 'the views phase, the set read');
+ }
+});
+
+test('ADO 6691114 numbering: the option on the spec\'s number is read in EVERY language — the second-language label of another option gives it away', async () => {
+ // 100000000 is "Gold Tier" in English and "Silver" in Spanish — the spec's Silver, which is 100000001 — and Silver itself IS on
+ // 100000001. Every label of the spec the environment carries is on its own number, so only the other language of the option on
+ // Gold's number shows that it is another option's.
+ const tiers = { schemaName: 'new_tier', type: 'Choice', options: ['Gold', 'Silver', 'Bronze'] };
+ const rows = opts([100000000, [1033, 'Gold Tier'], [3082, 'Silver']], [100000001, [1033, 'Silver']], [100000002, [1033, 'Bronze']]);
+ const spec = inlineSpec('Gold', tiers);
+ const r = await resolveAll(spec, inlineEnv(rows));
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Gold'), undefined);
+ assert.strictEqual(r.problems.length, 1);
+ assert.match(describeProblems(r.problems), /labelled "Silver", which the spec numbers 100000001/);
+ assert.deepStrictEqual(r.warnings, []);
+ assert.strictEqual((await preflight(spec, inlineEnv(rows))).problems.length, 1);
+});
+
+// The case of a label is the environment's to change: "Open" -> "open" renumbers nothing, and an environment that differs
+// from the spec only in case must not hide that its numbering differs. Comparing without regard to case is the guard's
+// alone — a label still RESOLVES by its exact text — and refusing more is the safe direction: the integer value works.
+
+const CASED = { schemaName: 'new_tier', type: 'Choice', options: ['Pending', 'Open', 'Closed'] };
+
+test('ADO 6691114 case: an environment whose labels differ from the spec\'s only in case does not hide that its numbering differs', async () => {
+ // Built from ['open', 'closed'] (in whatever case the environment holds them); the spec has since been re-cased and
+ // gained "Pending" at the top.
+ for (const [open, closed] of [['open', 'closed'], ['OPEN', 'CLOSED'], ['oPeN', 'cLoSeD']]) {
+ const rows = opts([100000000, [1033, open]], [100000001, [1033, closed]]);
+ for (const label of ['Pending', 'Open']) {
+ const what = `${label} over ${open}/${closed}`;
+ const spec = inlineSpec(label, CASED);
+ const r = await resolveAll(spec, inlineEnv(rows));
+ assert.strictEqual(r.value('new_customer', 'new_tier', label), undefined, what);
+ assert.strictEqual(r.problems.length, 1, what);
+ assert.match(describeProblems(r.problems), new RegExp(`Valid labels: ${open}, ${closed}\\.`), what);
+ assert.deepStrictEqual(r.warnings, [], what);
+ const e = viewsEngine({ byTable: withTierColumn(rows), record: true });
+ const { error } = await e.run(spec, { phases: FULL });
+ assert.strictEqual(error && error.code, 'view-filter-label-unresolved', what);
+ assert.strictEqual(error.phase, 'preflight', what);
+ assert.deepStrictEqual(writesOf(e.names), [], what);
+ }
+ const asked = await resolveAll(inlineSpec('Open', CASED), inlineEnv(rows));
+ assert.match(describeProblems(asked.problems), new RegExp(`labelled "${closed}", which the spec numbers 100000002`));
+ }
+});
+
+test('ADO 6691114 case: a label of the spec carried on another number in another case is carried there', async () => {
+ // "Open" was renamed "Opened", and "Closed" is now "closed" on 100000001 — the number the spec gives Open. The refusal quotes the
+ // environment's spelling beside the spec's; where the environment spells it the spec's way it says nothing more.
+ for (const closed of ['closed', 'CLOSED', 'Closed']) {
+ const rows = opts([100000000, [1033, 'Opened']], [100000001, [1033, closed]]);
+ const r = await resolveAll(inlineSpec('Pending', CASED), inlineEnv(rows));
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Pending'), undefined, closed);
+ assert.strictEqual(r.problems.length, 1, closed);
+ assert.match(describeProblems(r.problems), closed === 'Closed'
+ ? /\("Closed" is numbered 100000001 there, 100000002 in the spec\)/
+ : new RegExp(`\\("Closed" \\(as "${closed}"\\) is numbered 100000001 there, 100000002 in the spec\\)`), closed);
+ }
+});
+
+test('ADO 6691114 case: a refusal found through case folding quotes the environment\'s spelling beside the spec\'s — the environment has no "Gold", it has "GOLD"', async () => {
+ // Spec [Silver, Gold]: Gold is 100000001. The environment's Gold is "GOLD", on 100000002, and it has no option on Gold's number
+ // that goes by another name of the spec's, so it is the folded label that shows the numbering moved.
+ const rows = opts([100000000, [1033, 'Silver']], [100000001, [1033, 'Bronze']], [100000002, [1033, 'GOLD']]);
+ const r = await resolveAll(inlineSpec('Gold'), inlineEnv(rows));
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Gold'), undefined);
+ assert.match(describeProblems(r.problems), /\("Gold" \(as "GOLD"\) is numbered 100000002 there, 100000001 in the spec\)/);
+ // Two spellings are both shown, with every number they sit on.
+ const twins = opts([100000000, [1033, 'Silver']], [100000001, [1033, 'Bronze']], [100000002, [1033, 'GOLD']], [100000003, [1033, 'gold']]);
+ const both = await resolveAll(inlineSpec('Gold'), inlineEnv(twins));
+ assert.match(describeProblems(both.problems), /\("Gold" \(as "GOLD" and "gold"\) is numbered 100000002 and 100000003 there, 100000001 in the spec\)/);
+});
+
+test('ADO 6691114 case: a rename that only changes case keeps the spec\'s number — and a label still resolves by its exact text alone', async () => {
+ const rows = opts([100000000, [1033, 'Silver']], [100000001, [1033, 'GOLD']], [100000002, [1033, 'Bronze']]);
+ const r = await resolveAll(inlineSpec('Gold', THREE_TIERS), inlineEnv(rows));
+ assert.deepStrictEqual(r.problems, []);
+ assert.strictEqual(r.value('new_customer', 'new_tier', 'Gold'), 100000001);
+ assert.strictEqual(r.warnings.length, 1, 'not matched by name — matching stays exact — so the build says it used the spec\'s number');
+ assert.match(r.warnings[0], /labelled "GOLD"/);
+ // A spec written in another case over a renamed option keeps its number too.
+ const lower = { schemaName: 'new_tier', type: 'Choice', options: ['silver', 'gold', 'bronze'] };
+ const renamed = opts([100000000, [1033, 'Silver']], [100000001, [1033, 'Gold Tier']], [100000002, [1033, 'Bronze']]);
+ const kept = await resolveAll(inlineSpec('gold', lower), inlineEnv(renamed));
+ assert.deepStrictEqual(kept.problems, []);
+ assert.strictEqual(kept.value('new_customer', 'new_tier', 'gold'), 100000001);
+});
+
+test('ADO 6691114 dry run, a view that already exists: it stays reuse, and the dry run says the assumption the apply will warn of — once', async () => {
+ const spec = specOf([customer([INLINE_TIER])], [view('new_customer', [eq('new_tier', 'Gold')], 'Old'), view('new_customer', [eq('new_tier', 'Gold')], 'New')]);
+ const warned = [];
+ const { plan } = await dryRun(spec, withTierColumn(RENAMED), ['Old'], { warn: (m) => warned.push(m) });
+ assert.strictEqual(plan.find((p) => /^view "Old"/.test(p.label)).state, 'reuse');
+ assert.strictEqual(plan.find((p) => /^view "New"/.test(p.label)).state, 'create');
+ assert.strictEqual(warned.length, 1, JSON.stringify(warned));
+ assert.match(warned[0], /on the assumption that it is the same option under another label/);
+ // Said for the existing view alone, too — the apply warns whether or not the view is there.
+ const alone = [];
+ await dryRun(inlineSpec('Gold'), withTierColumn(RENAMED), ['Gold customers'], { warn: (m) => alone.push(m) });
+ assert.strictEqual(alone.length, 1, JSON.stringify(alone));
+ // A view whose labels resolve cleanly has nothing to say.
+ const clean = [];
+ await dryRun(inlineSpec('Silver'), withTierColumn(RENAMED), ['Gold customers'], { warn: (m) => clean.push(m) });
+ assert.deepStrictEqual(clean, []);
+});
+
+test('ADO 6691114 dry run, a view that already exists: a label no option answers to is said — verify will report it — and does not stop the build', async () => {
+ const spec = inlineSpec('Pending', PENDING_COLUMN);
+ const warned = [];
+ const { plan } = await dryRun(spec, withTierColumn(BUILT_WITHOUT_PENDING), ['Gold customers'], { warn: (m) => warned.push(m) });
+ const item = plan.find((p) => /^view "Gold customers"/.test(p.label));
+ assert.strictEqual(item.state, 'reuse', 'the apply leaves the view as it is, so it is not a view the dry run says would stop');
+ assert.strictEqual(item.wouldHalt, undefined);
+ assert.strictEqual(warned.length, 1, JSON.stringify(warned));
+ assert.match(warned[0], /view "Gold customers" \(new_customer\) already exists, so its filters are left as they are — but "Pending" is not an option of new_customer\.new_tier, and verify will report that\. The spec numbers "Pending" 100000000, but/);
+});
+
+test('ADO 6691114 dry run, a view that already exists: the dry run and the apply say the same words', async () => {
+ for (const [shape, spec, rows] of [['the assumption', inlineSpec('Gold'), RENAMED], ['verify will report', inlineSpec('Pending', PENDING_COLUMN), BUILT_WITHOUT_PENDING]]) {
+ const applied = await viewsEngine({ byTable: withTierColumn(rows), existingViews: ['Gold customers'], record: true }).run(spec, { phases: FULL });
+ assert.ok(!applied.error, shape);
+ const dry = [];
+ await dryRun(spec, withTierColumn(rows), ['Gold customers'], { warn: (m) => dry.push(m) });
+ const aboutTheLabel = (list) => list.filter((w) => /"Gold"|"Pending"/.test(w));
+ assert.strictEqual(aboutTheLabel(dry).length, 1, `${shape}: ${JSON.stringify(dry)}`);
+ assert.deepStrictEqual(aboutTheLabel(dry), aboutTheLabel(applied.warnings), shape);
+ }
+});
+
+test('ADO 6691114 dry run, a view that already exists: a label that names more than one option is said as that, not as "is not an option" — in the dry run and in the apply', async () => {
+ // Two options labelled "Gold", and the environment has no option on the number the spec gives Gold (100000001): the label is ambiguous, and the
+ // reason that follows it is that the spec's number is not used — a first sentence that said Gold is not an option would contradict both.
+ const rows = opts([100000000, [1033, 'Silver']], [100000003, [1033, 'Gold']], [100000004, [1033, 'Gold']]);
+ const spec = inlineSpec('Gold');
+ const said = /^view "Gold customers" \(new_customer\) already exists, so its filters are left as they are — but "Gold" names more than one option of new_customer\.new_tier \(100000003, 100000004\), and verify will report that\. The spec numbers "Gold" 100000001, but the environment has no option numbered 100000001, so that number is not used\.$/;
+ const dry = [];
+ await dryRun(spec, withTierColumn(rows), ['Gold customers'], { warn: (m) => dry.push(m) });
+ const aboutGold = (list) => list.filter((w) => /"Gold"/.test(w));
+ assert.strictEqual(aboutGold(dry).length, 1, JSON.stringify(dry));
+ assert.match(aboutGold(dry)[0], said);
+ const applied = await viewsEngine({ byTable: withTierColumn(rows), existingViews: ['Gold customers'], record: true }).run(spec, { phases: FULL });
+ assert.ok(!applied.error);
+ assert.deepStrictEqual(aboutGold(applied.warnings), aboutGold(dry));
+ // A label that names no option keeps its words.
+ const none = [];
+ await dryRun(inlineSpec('Platinum'), withTierColumn(rows), ['Gold customers'], { warn: (m) => none.push(m) });
+ assert.match(none.find((w) => /"Platinum"/.test(w)), /but "Platinum" is not an option of new_customer\.new_tier, and verify will report that\./);
+});
+
+// ── 7. the dry run ────────────────────────────────────────────────────────────────────────────────
+
+async function dryRun(spec, byTable, existingViews = [], { warn, globalSets } = {}) {
+ const client = choiceClient(byTable, { globalSets });
+ const provision = {
+ dataverse: client,
+ queryRecords: async () => [],
+ findArtifact: async (kind, identity) => (kind === 'view' && existingViews.includes(identity.name) ? 'existing' : null),
+ };
+ const plan = planFor(spec, { phases: ['views'] });
+ await annotateLivePlan(plan, { spec, provision, warn });
+ return { plan, client };
+}
+
+test('ADO 6691114 dry run: an unresolvable label on a view the build would create is reported as unknown, with the reason', async () => {
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Platinum')], 'Top customers')]);
+ const { plan } = await dryRun(spec, { new_customer: { Picklist: { new_tier: TIER } } });
+ const item = plan.find((p) => /^view "Top customers"/.test(p.label));
+ assert.strictEqual(item.state, 'unknown');
+ assert.match(item.stateWhy, /"Platinum"/);
+ assert.match(item.stateWhy, /new_customer\.new_tier/);
+ assert.match(item.stateWhy, /Silver, Gold, Bronze/);
+});
+
+test('ADO 6691114 dry run: a label that resolves leaves the view as create', async () => {
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Gold')], 'Gold customers')]);
+ const { plan } = await dryRun(spec, { new_customer: { Picklist: { new_tier: TIER } } });
+ assert.strictEqual(plan.find((p) => /^view "Gold customers"/.test(p.label)).state, 'create');
+});
+
+test('ADO 6691114 dry run: a view that already exists stays reuse whatever its labels — its filters are never reapplied (what the dry run says of it is tested with the numbering)', async () => {
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Platinum')], 'Top customers')]);
+ const { plan } = await dryRun(spec, { new_customer: { Picklist: { new_tier: TIER } } }, ['Top customers']);
+ assert.strictEqual(plan.find((p) => /^view "Top customers"/.test(p.label)).state, 'reuse');
+});
+
+test('ADO 6691114 dry run: a table that does not exist yet is judged by what the spec declares', async () => {
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] }])], [
+ view('new_customer', [eq('new_tier', 'Gold')], 'Good'),
+ view('new_customer', [eq('new_tier', 'Platinum')], 'Bad'),
+ ]);
+ const { plan } = await dryRun(spec, {});
+ assert.strictEqual(plan.find((p) => /^view "Good"/.test(p.label)).state, 'create');
+ const bad = plan.find((p) => /^view "Bad"/.test(p.label));
+ assert.strictEqual(bad.state, 'unknown');
+ assert.match(bad.stateWhy, /Silver, Gold/);
+});
+
+test('ADO 6691114 dry run: the reproduced failure is reported as unknown, and the right label is not', async () => {
+ const spec = specOf([ACCOUNT], [view('account', [eq('industrycode', 'Accountig')], 'Typo'), view('account', [eq('industrycode', 'Accounting')], 'Right')]);
+ const { plan } = await dryRun(spec, { account: { Picklist: { industrycode: INDUSTRY } } });
+ const typo = plan.find((p) => /^view "Typo"/.test(p.label));
+ assert.strictEqual(typo.state, 'unknown');
+ assert.match(typo.stateWhy, /"Accountig" is not an option of account\.industrycode\. Valid labels: Accounting, Retail, Consulting\./);
+ assert.strictEqual(plan.find((p) => /^view "Right"/.test(p.label)).state, 'create');
+});
+
+test('ADO 6691114 dry run: the dry run judges what the build would, so a status reason the build inserts is not unknown', async () => {
+ const spec = specOf([{ ...ACCOUNT, statusReasons: [{ label: 'Passed QA', state: 'Active' }] }], [view('account', [eq('statuscode', 'Passed QA')], 'Passed')]);
+ const { plan } = await dryRun(spec, { account: { Status: { statuscode: opts([1, [1033, 'Active']], [2, [1033, 'Inactive']]) } } });
+ assert.strictEqual(plan.find((p) => /^view "Passed"/.test(p.label)).state, 'create');
+});
+
+test('ADO 6691114 dry run: a declared global choice that already exists with other options is judged by those, not by the spec', async () => {
+ const spec = (label) => specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', label)], 'Tier')]);
+ const onTable = { new_customer: { Picklist: { new_other: TIER } } };
+ const live = opts([1, [1033, 'Platinum']], [2, [1033, 'Gold']]);
+ const run = async (label) => {
+ const client = choiceClient(onTable, { globalSets: { new_tierset: live } });
+ const provision = { dataverse: client, queryRecords: async () => [], findArtifact: async () => null };
+ const plan = planFor(spec(label), { phases: ['views'] });
+ await annotateLivePlan(plan, { spec: spec(label), provision });
+ return plan.find((p) => /^view "Tier"/.test(p.label));
+ };
+ assert.strictEqual((await run('Platinum')).state, 'create');
+ assert.strictEqual((await run('Silver')).state, 'unknown');
+});
+
+// ── 8. verify expects the value the build wrote ───────────────────────────────────────────────────
+
+test('ADO 6691114 dry run: the plan item for a label known to be bad says the apply would stop on it — it was read, not unreadable', async () => {
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Platinum')], 'Top customers'), view('new_customer', [eq('new_tier', 'Gold')], 'Gold customers')]);
+ const { plan } = await dryRun(spec, { new_customer: { Picklist: { new_tier: TIER } } });
+ const bad = plan.find((p) => /^view "Top customers"/.test(p.label));
+ assert.strictEqual(bad.state, 'unknown', 'still marked `? unknown`: the view will not be created as planned');
+ assert.strictEqual(bad.wouldHalt, true);
+ assert.deepStrictEqual(plan.filter((p) => p.wouldHalt), [bad], 'no other item carries the mark');
+});
+
+test('ADO 6691114 dry run: the engine\'s dry-run result carries the mark in planItems, for the CLI summary to count', async () => {
+ const e = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: TIER } } } });
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Platinum')], 'Top customers'), view('new_customer', [eq('new_tier', 'Gold')], 'Gold customers')]);
+ const r = await runSdkBuild(spec, { sdk: e.sdk, apply: false, phases: ['views'], preResolvedLanguageCode: 1033 });
+ const byLabel = (frag) => r.planItems.find((p) => p.label.includes(frag));
+ assert.strictEqual(byLabel('Top customers').wouldHalt, true);
+ assert.strictEqual(byLabel('Top customers').state, 'unknown');
+ assert.strictEqual(byLabel('Gold customers').wouldHalt, undefined);
+ assert.strictEqual(byLabel('Gold customers').state, 'create');
+});
+
+test('ADO 6691114 dry run: the CLI summary counts a label known to be bad as one that would STOP the build, not as one it could not read', async () => {
+ const planItems = [
+ { phase: 'views', label: 'view "Fine" for new_customer', state: 'create' },
+ { phase: 'views', label: 'view "Unread" for new_customer', state: 'unknown', stateWhy: 'the table\'s attributes could not be read' },
+ { phase: 'views', label: 'view "Bad" for new_customer', state: 'unknown', stateWhy: '"Platinum" is not an option of new_customer.new_tier.', wouldHalt: true },
+ ];
+ const logs = [];
+ await buildModelApp(specOf([customer([])], []), { apply: false, env: 'https://x', profile: 'structural' }, {
+ log: (m) => logs.push(m),
+ runBuild: async () => ({ ok: true, dryRun: true, livePlan: true, plan: [], planItems }),
+ });
+ const summary = logs.find((l) => /dry run —/.test(l));
+ assert.match(summary, /1 to create, 0 already present, 1 could not be read, 1 would stop the build \(3 steps\)/, summary);
+ // Alone, the bad label is not "could not be read" at all.
+ const alone = [];
+ await buildModelApp(specOf([customer([])], []), { apply: false, env: 'https://x', profile: 'structural' }, {
+ log: (m) => alone.push(m),
+ runBuild: async () => ({ ok: true, dryRun: true, livePlan: true, plan: [], planItems: [planItems[2]] }),
+ });
+ assert.doesNotMatch(alone.find((l) => /dry run —/.test(l)), /could not be read/);
+ assert.match(alone.find((l) => /dry run —/.test(l)), /1 would stop the build/);
+});
+
+test('ADO 6691114 localized: the dry run keeps its report — it creates nothing, so its reads precede no create', async () => {
+ const spec = localizedSpec('Accountig', PLACEMENTS['a column\'s name']);
+ const { plan } = await dryRun(spec, ACCOUNT_TABLES());
+ const typo = plan.find((p) => /^view "Accounts"/.test(p.label));
+ assert.strictEqual(typo.state, 'unknown');
+ assert.match(typo.stateWhy, /"Accountig" is not an option of account\.industrycode/);
+});
+
+const fetchXmlWith = (attribute, value) => `<fetch><entity name="new_customer"><filter type="and"><condition attribute="${attribute}" operator="eq" value="${value}" /></filter></entity></fetch>`;
+
+function verifyReader(spec, { fetchxml, choiceAttributes }) {
+ const row = { savedqueryid: 'v1', layoutxml: '<grid><row><cell name="new_name"/></row></grid>', fetchxml };
+ return {
+ findTable: async () => ({ logicalName: 'new_customer' }),
+ findColumns: async () => [{ logicalName: 'new_name' }, { logicalName: 'new_tier' }],
+ queryRecords: async (set) => (set === 'savedquery' ? [row] : []),
+ sitemapXml: async () => '',
+ ...(choiceAttributes ? { choiceAttributes } : {}),
+ };
+}
+
+const verifySpecOf = () => specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Gold')])], { solution: { uniqueName: 'S', publisherPrefix: 'new' } });
+const filterCheck = (result) => result.checks.find((c) => c.kind === 'view-filters');
+
+test('ADO 6691114 verify: the deployed value the build resolved from the environment verifies, when the reader can resolve it too', async () => {
+ const spec = verifySpecOf();
+ const read = makeChoiceReader({ client: choiceClient({ new_customer: { Picklist: { new_tier: TIER } } }) });
+ const ok = await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('new_tier', '227350001'), choiceAttributes: read }), { phases: ['views'] });
+ const check = filterCheck(ok);
+ assert.ok(check, JSON.stringify(ok.checks.map((c) => c.name || c.kind)));
+ assert.strictEqual(check.present, true, JSON.stringify(check));
+});
+
+test('ADO 6691114 verify: a deployed value that is not the environment\'s fails, naming what was expected', async () => {
+ const spec = verifySpecOf();
+ const read = makeChoiceReader({ client: choiceClient({ new_customer: { Picklist: { new_tier: TIER } } }) });
+ const bad = await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('new_tier', '100000001'), choiceAttributes: read }), { phases: ['views'] });
+ const check = filterCheck(bad);
+ assert.strictEqual(check.present, false);
+ assert.match(JSON.stringify(check), /227350001/);
+});
+
+test('ADO 6691114 verify: a label the environment cannot resolve is reported, not silently compared as text', async () => {
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Platinum')])]);
+ const read = makeChoiceReader({ client: choiceClient({ new_customer: { Picklist: { new_tier: TIER } } }) });
+ const bad = await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('new_tier', 'Platinum'), choiceAttributes: read }), { phases: ['views'] });
+ const check = filterCheck(bad);
+ assert.strictEqual(check.present, false);
+ assert.match(JSON.stringify(check), /Platinum/);
+ assert.match(JSON.stringify(check), /Silver, Gold, Bronze/);
+});
+
+test('ADO 6691114 verify: a reader without the capability keeps the old spec-only expectation', async () => {
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] }])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const ok = await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('new_tier', '100000001') }), { phases: ['views'] });
+ assert.strictEqual(filterCheck(ok).present, true);
+});
+
+test('ADO 6691114 verify: one read per table for the whole pass, however many views name it', async () => {
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [
+ view('new_customer', [eq('new_tier', 'Gold')], 'One'),
+ view('new_customer', [eq('new_tier', 'Silver')], 'Two'),
+ ]);
+ const calls = [];
+ const choiceAttributes = (entity, o) => { calls.push([entity, o]); return makeChoiceReader({ client: choiceClient({ new_customer: { Picklist: { new_tier: TIER } } }) })(entity); };
+ const result = await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('new_tier', '227350001'), choiceAttributes }), { phases: ['views'] });
+ assert.strictEqual(calls.length, 1, 'verify memoizes the reader for the pass');
+ assert.deepStrictEqual(calls[0], ['new_customer', { languageCode: undefined }]);
+ assert.strictEqual(result.checks.filter((c) => c.kind === 'view-filters').length, 2);
+});
+
+test('ADO 6691114 verify: a reader that throws leaves a declared option to the spec and a missing one reported, never a crash', async () => {
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] }])], [
+ view('new_customer', [eq('new_tier', 'Gold')], 'Fine'),
+ view('new_customer', [eq('new_tier', 'Platinum')], 'Broken'),
+ ]);
+ const choiceAttributes = async () => { throw new Error('metadata is down'); };
+ const result = await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('new_tier', '100000001'), choiceAttributes }), { phases: ['views'] });
+ const [fine, broken] = result.checks.filter((c) => c.kind === 'view-filters');
+ assert.strictEqual(fine.present, true);
+ assert.strictEqual(broken.present, false);
+ assert.match(broken.detail, /Platinum/);
+ assert.match(broken.detail, /metadata is down/);
+});
+
+test('ADO 6691114 verify: a failed metadata read reports the label as UNRESOLVED, with the reason — never as a missing filter', async () => {
+ // account.industrycode: the deployed view holds 1 (Accounting), which is right. The read that would have said
+ // so failed — and that is a fact about the read, not about the view.
+ const spec = specOf([ACCOUNT], [view('account', [eq('industrycode', 'Accounting')], 'Accounts')]);
+ const failing = makeChoiceReader({ client: choiceClient({ account: {} }, { failCast: 'Picklist', status: 503 }) });
+ const result = await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('industrycode', '1'), choiceAttributes: failing }), { phases: ['views'] });
+ const check = filterCheck(result);
+ assert.strictEqual(check.present, false, 'it cannot be proven, so it is not reported as proven');
+ assert.match(check.detail, /could not read the options of account\.industrycode \(HTTP 503\)/);
+ assert.match(check.detail, /"Accounting"/);
+ assert.doesNotMatch(check.detail, /missing filter/);
+});
+
+test('ADO 6691114 verify: a reader that throws leaves an undeclared column\'s label UNRESOLVED too — with the thrown reason', async () => {
+ const spec = specOf([ACCOUNT], [view('account', [eq('industrycode', 'Accounting')], 'Accounts')]);
+ const choiceAttributes = async () => { throw new Error('metadata is down'); };
+ const check = filterCheck(await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('industrycode', '1'), choiceAttributes }), { phases: ['views'] }));
+ assert.strictEqual(check.present, false);
+ assert.match(check.detail, /metadata is down/);
+ assert.doesNotMatch(check.detail, /missing filter/);
+});
+
+test('ADO 6691114 verify: a plain-text filter on a column the spec does not declare still verifies when the read fails — what is deployed is what was written', async () => {
+ const spec = specOf([ACCOUNT], [view('account', [eq('name', 'Contoso')], 'Accounts')]);
+ const failing = makeChoiceReader({ client: choiceClient({ account: {} }, { failCast: 'Picklist', status: 503 }) });
+ const result = await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('name', 'Contoso'), choiceAttributes: failing }), { phases: ['views'] });
+ assert.strictEqual(filterCheck(result).present, true, JSON.stringify(filterCheck(result)));
+});
+
+test('ADO 6691114 verify: a declared column\'s value that differs from the spec\'s numbering is unresolved — not missing — when the read failed', async () => {
+ // The set existed with Gold = 227350001, so the view rightly holds that and not the spec's 100000001.
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const failing = () => makeChoiceReader({ client: choiceClient({ new_customer: {} }, { failCast: 'Picklist', status: 503 }) });
+ const differs = filterCheck(await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('new_tier', '227350001'), choiceAttributes: failing() }), { phases: ['views'] }));
+ assert.strictEqual(differs.present, false);
+ assert.match(differs.detail, /could not read the options of new_customer\.new_tier \(HTTP 503\)/);
+ assert.doesNotMatch(differs.detail, /missing filter/);
+ // Where the deployed value IS the spec's numbering, the fallback was right and the view verifies.
+ const same = filterCheck(await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('new_tier', '100000001'), choiceAttributes: failing() }), { phases: ['views'] }));
+ assert.strictEqual(same.present, true, JSON.stringify(same));
+});
+
+test('ADO 6691114 verify: a failed metadata read does not hide a filter that is missing from the view altogether', async () => {
+ // The read failure explains a DIFFERENT value on a condition that is there; it explains nothing where the view has
+ // no condition on that attribute (or none with that operator) — there the filter is simply not deployed.
+ const spec = specOf([ACCOUNT], [view('account', [eq('industrycode', 'Accounting')], 'Accounts')]);
+ const failing = () => makeChoiceReader({ client: choiceClient({ account: {} }, { failCast: 'Picklist', status: 503 }) });
+ const check = async (fetchxml) => filterCheck(await verifySpec(spec, verifyReader(spec, { fetchxml, choiceAttributes: failing() }), { phases: ['views'] }));
+ const absent = await check(fetchXmlWith('name', 'Contoso'));
+ assert.strictEqual(absent.present, false);
+ assert.match(absent.detail, /missing filter\(s\): industrycode eq Accounting/);
+ assert.doesNotMatch(absent.detail, /could not read the options/);
+ const otherOperator = await check('<fetch><entity name="account"><filter type="and"><condition attribute="industrycode" operator="ne" value="1" /></filter></entity></fetch>');
+ assert.match(otherOperator.detail, /missing filter\(s\): industrycode eq Accounting/);
+ assert.doesNotMatch(otherOperator.detail, /could not read the options/);
+ // A condition on the attribute with the same operator is the one the failed read would have named: unresolved.
+ const sameOperator = await check(fetchXmlWith('industrycode', '2'));
+ assert.match(sameOperator.detail, /could not read the options of account\.industrycode \(HTTP 503\)/);
+ assert.doesNotMatch(sameOperator.detail, /missing filter/);
+});
+
+test('ADO 6691114 verify: with two guessed labels, only the one the view has no condition for is called missing', async () => {
+ const spec = specOf([ACCOUNT], [view('account', [eq('industrycode', 'Accounting'), eq('customertypecode', 'Competitor')], 'Accounts')]);
+ const failing = makeChoiceReader({ client: choiceClient({ account: {} }, { failCast: 'Picklist', status: 503 }) });
+ const check = filterCheck(await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('industrycode', '2'), choiceAttributes: failing }), { phases: ['views'] }));
+ assert.strictEqual(check.present, false);
+ assert.match(check.detail, /could not read the options of account\.industrycode \(HTTP 503\)/);
+ assert.match(check.detail, /missing filter\(s\): customertypecode eq Competitor/);
+});
+
+test('ADO 6691114 verify: with the environment readable, a wrong deployed value is still a missing filter', async () => {
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ const read = makeChoiceReader({ client: choiceClient({ new_customer: { Picklist: { new_tier: TIER } } }) });
+ const check = filterCheck(await verifySpec(spec, verifyReader(spec, { fetchxml: fetchXmlWith('new_tier', '100000001'), choiceAttributes: read }), { phases: ['views'] }));
+ assert.strictEqual(check.present, false);
+ assert.match(check.detail, /missing filter\(s\): new_tier eq 227350001/);
+});
+
+test('ADO 6691114 verify: the CLI\'s own reader supplies choiceAttributes through the SDK\'s raw client, and never throws', async () => {
+ const { readerFor } = require('../verify-model-app.js');
+ const client = choiceClient({ new_customer: { Picklist: { new_tier: TIER } } });
+ const sdk = {
+ queryRecords: async (set) => (set === 'savedquery'
+ ? [{ savedqueryid: 'v1', layoutxml: '<grid><row><cell name="new_name"/></row></grid>', fetchxml: fetchXmlWith('new_tier', '227350001') }]
+ : []),
+ findTables: async () => [{ logicalName: 'new_customer' }],
+ findColumns: async () => [{ logicalName: 'new_name' }, { logicalName: 'new_tier' }],
+ dataverse: client,
+ };
+ const reader = readerFor(sdk, 'new_app', {});
+ const answer = await reader.choiceAttributes('new_customer', { languageCode: 1033 });
+ assert.strictEqual(answer.state, 'ok');
+ assert.deepStrictEqual(answer.attributes.get('new_tier').options.map((o) => o.shown), ['Silver', 'Gold', 'Bronze']);
+ const result = await verifySpec(verifySpecOf(), reader, { phases: ['views'] });
+ assert.strictEqual(filterCheck(result).present, true, JSON.stringify(filterCheck(result)));
+ // No raw client at all: the capability answers `error` instead of throwing into verify.
+ const blind = readerFor({ ...sdk, dataverse: undefined }, 'new_app', {});
+ assert.strictEqual((await blind.choiceAttributes('new_customer')).state, 'error');
+});
+
+// ── 9. lint: offline can only check what the spec declares, and says so ────────────────────────────
+
+const lint = (spec) => lintAppSpec(spec).warnings.filter((w) => /checked against the environment/.test(w));
+
+test('ADO 6691114 lint: a label the spec declares is checked offline and says nothing', () => {
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] }])], [view('new_customer', [eq('new_tier', 'Gold')])]);
+ assert.deepStrictEqual(lint(spec), []);
+ // …and so is one on a column bound to a global choice the spec declares.
+ assert.deepStrictEqual(lint(specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Gold')])])), []);
+});
+
+test('ADO 6691114 lint: a column bound to a global choice the spec does not declare stays the existing lint ERROR, with no second warning', () => {
+ // The build creates such a column with no options at all, so it is refused rather than resolved from the
+ // environment: lint reports it once, as an error, and has nothing to add about the labels filtered on it.
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Gold')], 'Gold customers')], { globalChoices: [] });
+ const result = lintAppSpec(spec);
+ assert.ok(result.errors.some((e) => /Column new_customer\.new_tier references unknown globalChoice 'new_tierset'/.test(e)), JSON.stringify(result.errors));
+ assert.deepStrictEqual(lint(spec), []);
+});
+
+test('ADO 6691114 lint: a label that is not among the declared options warns that the environment decides', () => {
+ const spec = specOf([customer([{ schemaName: 'new_tier', type: 'Choice', options: ['Silver', 'Gold'] }])], [view('new_customer', [eq('new_tier', 'Platinum')], 'Top customers')]);
+ const [w] = lint(spec);
+ assert.match(w, /Top customers/);
+ assert.match(w, /Platinum/);
+ assert.match(w, /Silver, Gold/);
+ assert.match(w, /halts/);
+});
+
+test('ADO 6691114 lint: a label that is not among a declared global choice\'s options warns the same way, naming the set\'s labels', () => {
+ const spec = specOf([customer([GLOBAL_TIER_COLUMN])], [view('new_customer', [eq('new_tier', 'Platinum')], 'Top customers')]);
+ const [w] = lint(spec);
+ assert.match(w, /Platinum/);
+ assert.match(w, /Silver, Gold, Bronze/);
+});
+
+test('ADO 6691114 lint: the reproduced failure — a label on a column of an existing table the spec does not declare — is flagged, and an integer or no-value filter is not', () => {
+ // This spec passed lint silently, and the build then failed mid-way.
+ const spec = specOf([ACCOUNT], [
+ view('account', [eq('industrycode', 'Accounting'), eq('industrycode', '1'), { attr: 'ownerid', op: 'eq-userid' }, { attr: 'createdon', op: 'this-week' }], 'Accounts'),
+ ]);
+ const found = lint(spec);
+ assert.strictEqual(found.length, 1, JSON.stringify(found));
+ assert.match(found[0], /industrycode/);
+ assert.match(found[0], /Accounting/);
+ assert.match(found[0], /halts/);
+});
+
+test('ADO 6691114 lint: a value that cannot be a label (a GUID, a date, a pattern) is not flagged', () => {
+ const spec = specOf([{ schemaName: 'account', displayName: 'Account', existing: true, primaryAttribute: { schemaName: 'name' }, columns: [] }], [
+ view('account', [eq('parentaccountid', '11111111-2222-3333-4444-555555555555'), { attr: 'createdon', op: 'on', value: '2024-01-31' }, { attr: 'name', op: 'like', value: 'A%' }], 'Odd ones'),
+ ]);
+ assert.deepStrictEqual(lint(spec), []);
+});
+
+test('ADO 6691114 lint: a spec with a localized label keeps the warning — the check merely moves to the views phase', () => {
+ const found = lint(localizedSpec('Accounting', PLACEMENTS['a column\'s name']));
+ assert.strictEqual(found.length, 1, JSON.stringify(found));
+ assert.match(found[0], /before any view is written/, 'still true: the views phase halts before it writes a view');
+});
diff --git a/plugins/model-apps/scripts/tests/workspace-binding.test.js b/plugins/model-apps/scripts/tests/workspace-binding.test.js
new file mode 100644
index 000000000..655d789aa
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/workspace-binding.test.js
@@ -0,0 +1,1013 @@
+'use strict';
+// A persistent `.maker-workspace` belongs to the ONE environment it was first opened for: the vendored SDK
+// records that environment in the workspace manifest and refuses an SDK for another one
+// (`WORKSPACE_ORG_MISMATCH`) before it reads or writes anything. The plugin can be pointed at another
+// environment from the same app folder, so the one entry point that opens the app folder's workspace — a build
+// with --apply — has to turn that refusal into a halt an operator can act on. A dry run and the standalone verify
+// never open it: their SDKs read only the server, in a throwaway workspace of their own, so a preview creates and
+// binds nothing, and from a folder that belongs to another environment it previews as normal and only warns that an
+// --apply would stop.
+//
+// What is pinned here, and why each part drives the REAL bundle rather than a stub:
+// - the halt names both environments (normalized origins only) and the safe remedies, and never offers to
+// clear or re-bind the workspace itself — the SDK's saved copies in it can hold unpushed edits, and the
+// receipts and baseline beside them are the other environment's;
+// - a workspace that was only ever OPENED for another environment (the SDK's empty folders and manifest, nothing
+// saved) is told apart from one a build saved into: nothing was built there, so there is no environment to go
+// back to and nothing for a teardown to remove;
+// - the teardown remedy clears the folder the halt names, and is offered only for ANOTHER environment: two
+// spellings of one environment (the `.api.` host, a manifest with a path or port) get a halt of their own;
+// - the folder is printed on its own line and the teardown command refers to it, never embeds it: no quoting of
+// a path is right for every shell;
+// - a manifest the JSON parser rejects gets a halt of its own, not the parser's message — and only a MANIFEST does: a saved
+// copy that is not JSON throws the same error when the SDK lists, so the dry run asks the folder for its manifest and
+// nothing else, and an --apply that opens the folder is not halted by a copy;
+// - nothing is read from or written to the foreign workspace, and no request is sent;
+// - a spelling of the SAME environment the bundle accepts is not a mismatch, so no run is halted that did not
+// need to be.
+// The bundle's own decision (which URLs name one environment) is deliberately NOT re-implemented in the plugin:
+// a stub that mimicked it would stay green if the SDK changed it.
+const test = require('node:test');
+const assert = require('node:assert');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { loadCli } = require('./helpers/cli-harness.js');
+const { scriptsMatching } = require('./helpers/production-scripts.js');
+const { isWorkspaceOrgMismatch, workspaceBindingError, workspaceBindingNote } = require('../lib/workspace-binding.js');
+const { recordPageCreation } = require('../lib/page-ownership-records.js');
+
+const scriptsDir = path.join(__dirname, '..');
+const BUNDLE = path.join(scriptsDir, 'vendor', 'cds-maker-sdk.cjs');
+const WORKSPACE_ENV = 'https://contoso.crm.dynamics.com';
+const RUN_ENV = 'https://fabrikam.crm.dynamics.com';
+// A folder that does not exist, for halts built from a hand-made error: nothing in the plugin looks inside it.
+const NO_SUCH_FOLDER = path.join(os.tmpdir(), 'binding-no-such-workspace', '.maker-workspace');
+// What `fs.symlinkSync` is given to link a folder without needing a privilege: a junction on Windows (a symbolic link needs
+// one there), a symbolic link elsewhere. Node's directory listing reports either as a link, never as a directory.
+const FOLDER_LINK = process.platform === 'win32' ? 'junction' : 'dir';
+
+const tempDirs = [];
+function tempDir(prefix) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
+ tempDirs.push(dir);
+ return dir;
+}
+test.after(() => { for (const d of tempDirs) fs.rmSync(d, { recursive: true, force: true }); });
+
+// An HttpClient that fails the test the moment anything is sent: a refusal must come before any request.
+function inertClient(requests = []) {
+ const refuse = (verb) => async (url) => { requests.push(`${verb} ${url}`); throw new Error(`unexpected ${verb} ${url}`); };
+ return { get: refuse('GET'), post: refuse('POST'), patch: refuse('PATCH'), delete: refuse('DELETE'), put: refuse('PUT'), postRaw: refuse('POST') };
+}
+
+// A workspace the real bundle created for `instanceUrl`. Alone it is exactly what OPENING a workspace leaves: the SDK's
+// manifest and its empty folders, nothing saved. `built` adds the baseline a build that finished writes beside them, so
+// the folder holds something, as one a build was run in does.
+async function workspaceFor(instanceUrl, dir = tempDir('binding-ws-'), { built = false } = {}) {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl, httpClient: inertClient() });
+ await sdk.initWorkspace();
+ if (built) fs.writeFileSync(path.join(dir, 'last-applied.json'), '{}\n');
+ return dir;
+}
+
+// The error the bundle raises when an SDK for `instanceUrl` opens `dir` — the refusal of another environment's
+// workspace, or whatever else it throws (a manifest that is not JSON surfaces the parser's SyntaxError).
+async function mismatchFrom(dir, instanceUrl) {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl, httpClient: inertClient() });
+ try {
+ await sdk.initWorkspace();
+ } catch (err) {
+ return err;
+ }
+ throw new Error('expected the bundle to refuse this workspace');
+}
+
+// Every file under `dir` with the hash of its bytes, so "nothing was written" is a comparison, not a hope.
+function treeOf(dir) {
+ const out = {};
+ const walk = (current) => {
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
+ const full = path.join(current, entry.name);
+ if (entry.isDirectory()) { out[`${path.relative(dir, full)}/`] = 'dir'; walk(full); }
+ else out[path.relative(dir, full)] = crypto.createHash('sha256').update(fs.readFileSync(full)).digest('hex');
+ }
+ };
+ walk(dir);
+ return out;
+}
+
+// --- the helper ------------------------------------------------------------------------------------
+
+test('isWorkspaceOrgMismatch recognizes the bundle\u2019s refusal and nothing else', async () => {
+ const dir = await workspaceFor(WORKSPACE_ENV);
+ const err = await mismatchFrom(dir, RUN_ENV);
+ assert.strictEqual(err.code, 'WORKSPACE_ORG_MISMATCH', 'the bundle still reports the refusal by this code');
+ assert.strictEqual(isWorkspaceOrgMismatch(err), true);
+ for (const other of [null, undefined, 'WORKSPACE_ORG_MISMATCH', new Error('boom'), new TypeError('boom'), Object.assign(new Error('x'), { code: 'WORKSPACE_NOT_INITIALIZED' }), Object.assign(new Error('Unexpected token } in JSON at position 3'), { code: 'EACCES' })]) {
+ assert.strictEqual(isWorkspaceOrgMismatch(other), false, String(other));
+ assert.strictEqual(workspaceBindingError(other, { env: RUN_ENV, workspaceDir: dir }), null, 'any other error is left for the caller to rethrow as it is');
+ }
+});
+
+test('the halt names both environments as normalized origins and the three safe remedies', async () => {
+ // The workspace was opened with a trailing slash and capitals; the run's --env is spelled plainly.
+ const dir = await workspaceFor('https://Contoso.crm.dynamics.com/', undefined, { built: true });
+ const halt = workspaceBindingError(await mismatchFrom(dir, RUN_ENV), { env: RUN_ENV, workspaceDir: dir });
+ assert.ok(halt instanceof Error);
+ assert.strictEqual(halt.code, 'WORKSPACE_ORG_MISMATCH');
+ assert.strictEqual(halt.workspaceEnvironment, WORKSPACE_ENV, 'normalized: lower case, no trailing slash');
+ assert.strictEqual(halt.environment, RUN_ENV);
+ const text = halt.message;
+ assert.match(text, /belongs to a different environment/);
+ assert.ok(text.includes(WORKSPACE_ENV) && text.includes(RUN_ENV), `both environments are named: ${text}`);
+ assert.ok(text.split('\n').some((line) => line.trim() === dir), 'the workspace folder is printed alone on a line, so the operator knows which folder it is and can copy it exactly');
+ assert.ok(!/Contoso/.test(text), 'only the normalized spelling is shown, never the manifest\u2019s text');
+ // Remedy 1: the environment it belongs to, as an exact --env the operator can paste.
+ assert.ok(text.includes(`--env ${WORKSPACE_ENV}`), text);
+ // Remedy 2: a fresh app folder or --workspace.
+ assert.match(text, /fresh app folder/);
+ assert.match(text, /--workspace <a new folder>/);
+ // Remedy 3: the teardown that retires the old copy — said plainly to DELETE from the other environment — with the
+ // rule that already protects the receipts. It names the folder it clears: teardown clears `--workspace`, else the
+ // folder beside its spec, and without the flag it would clear a different one than the folder this halt is about.
+ // The folder is the line above, not an argument: see the test of a path no shell would read back as it is.
+ assert.match(text, /teardown-model-app\.js --env https:\/\/contoso\.crm\.dynamics\.com .*--clear-workspace/);
+ assert.ok(text.includes('--workspace <the folder printed above> --apply --allow-destructive --clear-workspace'), text);
+ assert.match(text, /only if that environment's copy of the app is no longer wanted/);
+ assert.match(text, /DELETES what the spec declares from https:\/\/contoso\.crm\.dynamics\.com/);
+ assert.match(text, /page-ownership receipt/);
+ // The SDK's own advice is an API call this plugin's operator cannot make — and one the plugin must never make for them.
+ assert.ok(!/cleanWorkspace/.test(text), text);
+ assert.match(text, /never clears or re-binds/);
+});
+
+test('the halt says precisely what is in the folder and what clearing it would cost', async () => {
+ // The SDK's own remedy discards ITS saved copies, metadata and baselines — only its own folders. What is at risk is
+ // therefore those copies (an edit in one that was never pushed is lost with it); the page-ownership receipts and the
+ // plugin's baseline live beside them and are the other environment's too. Neither more nor less is claimed.
+ const dir = await workspaceFor(WORKSPACE_ENV, undefined, { built: true });
+ const text = workspaceBindingError(await mismatchFrom(dir, RUN_ENV), { env: RUN_ENV, workspaceDir: dir }).message;
+ assert.match(text, /saved copies of this app's artifacts, their metadata and baselines in that folder are https:\/\/contoso\.crm\.dynamics\.com's/);
+ assert.match(text, /discards those saved copies, including any edit made in them that was never pushed/);
+ assert.match(text, /page-ownership receipts and the baseline \(last-applied\.json\) kept beside them are https:\/\/contoso\.crm\.dynamics\.com's too/);
+ assert.ok(!/which no re-run can rebuild|its page-ownership receipts and its baseline, and the ids/.test(text), 'the claim that clearing deletes the receipts and the baseline is not made');
+});
+
+test('a folder given relative is named by its absolute path, alone on its line', () => {
+ const err = Object.assign(new Error('sdk'), { code: 'WORKSPACE_ORG_MISMATCH', workspaceInstanceUrl: WORKSPACE_ENV, instanceUrl: RUN_ENV });
+ const relative = path.join('my app', '.maker-workspace');
+ const text = workspaceBindingError(err, { env: RUN_ENV, workspaceDir: relative }).message;
+ const absolute = path.resolve(relative);
+ assert.ok(text.split('\n').includes(` ${absolute}`), text);
+ assert.ok(!text.includes(`"${absolute}"`), 'and it is not wrapped in quotes a shell would read');
+});
+
+test('the teardown command refers to the folder instead of embedding it: a $ in a path is expanded inside double quotes by PowerShell and POSIX shells', () => {
+ // `--workspace "C:\apps\$work\.maker-workspace"` reads `$work` as a variable in PowerShell and in bash/zsh, so teardown
+ // would clear whatever folder the expansion names — or none, and then the build halts again. Single quotes avoid that
+ // there but are not quotes in cmd.exe, so no quoting of the path is right for every shell. The folder is therefore
+ // printed on its own line, and the operator is told to pass it as --workspace, quoted for the shell they use.
+ const folder = path.join(path.resolve(os.tmpdir()), 'apps', '$work', 'it\u0027s `mine`', '.maker-workspace');
+ const err = Object.assign(new Error('sdk'), { code: 'WORKSPACE_ORG_MISMATCH', workspaceInstanceUrl: WORKSPACE_ENV, instanceUrl: RUN_ENV });
+ const text = workspaceBindingError(err, { env: RUN_ENV, workspaceDir: folder }).message;
+ const lines = text.split('\n');
+ assert.ok(lines.includes(` ${folder}`), `the folder is printed alone on its line, exactly as it is: ${text}`);
+ const teardown = lines.find((line) => /teardown-model-app\.js/.test(line));
+ assert.ok(teardown, text);
+ assert.ok(!teardown.includes(folder) && !teardown.includes('$work'), `the command carries no path for a shell to expand: ${teardown}`);
+ assert.match(teardown, /--workspace <the folder printed above> --apply --allow-destructive --clear-workspace/);
+ assert.ok(!/--workspace ["']/.test(text), 'no quoted path is offered anywhere');
+ // What to do instead, and why: said where the operator reads the command.
+ assert.match(text, /quoted for your shell/);
+ assert.match(text, /single quotes in PowerShell, bash and zsh/);
+ assert.match(text, /double quotes there still expand \$/);
+ assert.match(text, /cmd\.exe/);
+ assert.match(text, /clears the folder beside its spec/, 'and why --workspace is not optional');
+});
+
+test('a `.api.` label names the same environment on a Dataverse host in any cloud, and is just a label anywhere else', () => {
+ const halt = (recorded, run) => workspaceBindingError(
+ Object.assign(new Error('sdk'), { code: 'WORKSPACE_ORG_MISMATCH', workspaceInstanceUrl: recorded, instanceUrl: run }),
+ { env: run, workspaceDir: NO_SUCH_FOLDER },
+ ).message;
+ for (const [recorded, run] of [
+ ['https://contoso.api.crm.dynamics.com', 'https://contoso.crm.dynamics.com'],
+ ['https://contoso.crm4.dynamics.com', 'https://contoso.api.crm4.dynamics.com'],
+ ['https://contoso.crm.microsoftdynamics.us', 'https://contoso.api.crm.microsoftdynamics.us'],
+ ['https://contoso.api.crm.dynamics.cn', 'https://contoso.crm.dynamics.cn'],
+ ]) {
+ assert.match(halt(recorded, run), /two host names of one environment/, `${recorded} / ${run}`);
+ }
+ for (const [recorded, run] of [
+ ['https://tools.api.example.com', 'https://tools.example.com'],
+ ['https://contoso.api.crm.dynamics.com', 'https://contoso2.crm.dynamics.com'],
+ ['https://api.crm.dynamics.com', 'https://crm.dynamics.com'],
+ ]) {
+ assert.match(halt(recorded, run), /belongs to a different environment/, `${recorded} / ${run}`);
+ }
+});
+
+test('a manifest URL carrying credentials, a path or a query is shown as its origin only', () => {
+ const err = Object.assign(new Error('sdk text that must not be echoed'), {
+ code: 'WORKSPACE_ORG_MISMATCH',
+ workspaceInstanceUrl: 'https://user:[email protected]/main.aspx?token=abc123#frag',
+ instanceUrl: RUN_ENV,
+ });
+ const halt = workspaceBindingError(err, { env: RUN_ENV, workspaceDir: 'C:\\apps\\desk\\.maker-workspace' });
+ assert.strictEqual(halt.workspaceEnvironment, WORKSPACE_ENV);
+ for (const secret of ['hunter2', 'abc123', 'main.aspx', 'frag', 'sdk text that must not be echoed']) {
+ assert.ok(!halt.message.includes(secret), `${secret} must not reach the message: ${halt.message}`);
+ }
+});
+
+test('a workspace that records no usable environment is described as such, offers no --env remedy, and is moved aside rather than deleted', () => {
+ for (const recorded of ['', undefined, 'not a url at all', 'ftp://contoso.crm.dynamics.com']) {
+ const err = Object.assign(new Error('sdk'), { code: 'WORKSPACE_ORG_MISMATCH', workspaceInstanceUrl: recorded, instanceUrl: RUN_ENV });
+ const halt = workspaceBindingError(err, { env: RUN_ENV, workspaceDir: NO_SUCH_FOLDER });
+ assert.strictEqual(halt.workspaceEnvironment, null, String(recorded));
+ assert.strictEqual(halt.code, 'WORKSPACE_ORG_MISMATCH', 'it is the SDK\u2019s refusal, so it keeps its code');
+ assert.ok(halt.message.includes(RUN_ENV), halt.message);
+ assert.match(halt.message, /records no usable environment/);
+ // No `--env` anywhere: there is no environment to go back to, and no other flag may be mistaken for one.
+ assert.ok(!/--env\b/.test(halt.message), `there is no environment to go back to: ${halt.message}`);
+ assert.ok(!/teardown-model-app|DELETES/.test(halt.message), 'and nothing to tear down');
+ assert.ok(!/not a url at all/.test(halt.message), 'unparseable text is never echoed');
+ assert.match(halt.message, /fresh app folder/);
+ assertMovedAside(halt.message);
+ }
+});
+
+// What the operator is told to do with a folder whose manifest names no environment. It is MOVED, not deleted: the folder can hold the
+// page-ownership receipts (the proof a rebuild needs to update pages it created) and the baseline (last-applied.json), and neither is
+// something a new workspace gets back.
+function assertMovedAside(text) {
+ assert.match(text, /move the folder aside \(rename it\)/);
+ assert.match(text, /do not delete it/i);
+ assert.match(text, /page-ownership receipts/);
+ assert.match(text, /last-applied\.json/);
+ assert.ok(!/remove the folder yourself|if you are sure nothing in this one is needed/.test(text), `deleting is not what is advised: ${text}`);
+ assert.match(text, /never clears or re-binds/);
+}
+
+test('a manifest the JSON parser rejects is a halt of its own: the folder named, the parser\u2019s text not echoed, moved aside rather than deleted', () => {
+ // The SDK reads manifest.json with JSON.parse and lets the SyntaxError out as it is — no code, a position, and on newer
+ // Node versions a quote of the file. It is recognized by its name, not its text, which differs between versions.
+ const folder = path.join(tempDir('binding-bad-'), '.maker-workspace');
+ for (const raw of [new SyntaxError('Unterminated string in JSON at position 36'), Object.assign(new Error('Unexpected end of JSON input'), { name: 'SyntaxError' })]) {
+ const halt = workspaceBindingError(raw, { env: RUN_ENV, workspaceDir: folder });
+ assert.ok(halt instanceof Error && halt !== raw, 'the parser\u2019s error is turned into the halt');
+ assert.strictEqual(halt.code, 'WORKSPACE_MANIFEST_INVALID');
+ assert.strictEqual(halt.workspaceEnvironment, null);
+ assert.strictEqual(halt.environment, RUN_ENV);
+ const text = halt.message;
+ assert.ok(text.split('\n').includes(` ${folder}`), `the folder is named alone on its line: ${text}`);
+ assert.match(text, /manifest\.json that is not valid JSON/);
+ assert.ok(text.includes(RUN_ENV), 'and the environment this run targets');
+ assert.ok(!/Unterminated|position 36|end of JSON input/.test(text), `the parser\u2019s text can quote the file and is never echoed: ${text}`);
+ assert.ok(!/--env\b/.test(text), `there is no environment to go back to: ${text}`);
+ assert.ok(!/teardown-model-app|DELETES/.test(text), 'and nothing to tear down');
+ assert.match(text, /fresh app folder/);
+ assertMovedAside(text);
+ }
+});
+
+// --- a workspace nothing was ever saved in -------------------------------------------------------------
+
+// What opening a workspace leaves alone: the SDK's manifest, with no artifact, and its empty folders. An earlier preview, or a
+// build that stopped at its start, leaves exactly this for the environment it ran against — and nothing was built there.
+test('a workspace that was only ever opened for another environment is described as that: nothing saved, nothing built there, nothing to tear down', async () => {
+ const dir = await workspaceFor(WORKSPACE_ENV);
+ const halt = workspaceBindingError(await mismatchFrom(dir, RUN_ENV), { env: RUN_ENV, workspaceDir: dir });
+ const text = halt.message;
+ assert.strictEqual(halt.code, 'WORKSPACE_ORG_MISMATCH');
+ assert.strictEqual(halt.workspaceEnvironment, WORKSPACE_ENV);
+ assert.ok(text.includes(WORKSPACE_ENV) && text.includes(RUN_ENV), `both environments are named: ${text}`);
+ assert.ok(text.split('\n').includes(` ${dir}`), 'the folder is named alone on its line');
+ assert.match(text, /only ever opened for https:\/\/contoso\.crm\.dynamics\.com/);
+ assert.match(text, /holds nothing a build saved/);
+ assert.match(text, /nothing was built there/);
+ // No build-there or teardown advice: there is nothing in that environment to go back to or to delete.
+ assert.ok(!text.includes(`--env ${WORKSPACE_ENV}`), `no environment to go back to: ${text}`);
+ assert.ok(!/teardown-model-app|DELETES|--clear-workspace/.test(text), text);
+ assert.ok(!/saved copies of this app's artifacts|belongs to a different environment/.test(text), 'the account of a folder with saved work is not given for one without');
+ // What is safe to do, and that the plugin leaves doing it to the operator.
+ assert.match(text, /delete the folder \(it holds nothing\), or move it aside, and run again/);
+ assert.match(text, /fresh app folder/);
+ assert.match(text, /never clears or re-binds/);
+});
+
+// Anything besides the SDK's own empty scaffold is something a build left, and the full account comes back. Each of these
+// is written by the code that really writes it; the manifest ones are what the SDK itself would record. The two links are
+// not something a build writes: they are what the check refuses to guess about. A link can lead anywhere, so it is never taken
+// for an empty folder — and these lead to one, so a check that followed links would find nothing in them and call the
+// workspace "only opened".
+const SOMETHING_SAVED = {
+ 'the baseline of a build that finished': (dir) => fs.writeFileSync(path.join(dir, 'last-applied.json'), '{}\n'),
+ 'a page-ownership receipt': (dir) => recordPageCreation(dir, 'new_app', 'overview', '11111111-1111-4111-8111-111111111111', 'Overview', WORKSPACE_ENV),
+ 'the build journal': (dir) => fs.writeFileSync(path.join(dir, 'build-log.jsonl'), '{"event":"start"}\n'),
+ 'the live progress file': (dir) => fs.writeFileSync(path.join(dir, 'build-status.json'), '{}\n'),
+ 'a destructive-approval record': (dir) => fs.writeFileSync(path.join(dir, 'destructive-approval.json'), '{}\n'),
+ 'a saved copy of an artifact': (dir) => fs.writeFileSync(path.join(dir, 'apps', '11111111-1111-4111-8111-111111111111.json'), '{}'),
+ 'the saved metadata of an artifact': (dir) => fs.writeFileSync(path.join(dir, '.metadata', 'views', 'v.meta.json'), '{}'),
+ 'cached table metadata': (dir) => fs.writeFileSync(path.join(dir, '.metadata', 'entities', 'new_ticket.json'), '{}'),
+ 'files the plugin staged for a deploy': (dir) => {
+ fs.mkdirSync(path.join(dir, '.pageref-deploy', 'run-1'), { recursive: true });
+ fs.writeFileSync(path.join(dir, '.pageref-deploy', 'run-1', 'page.tsx'), 'export {}\n');
+ },
+ 'a manifest that lists an artifact': (dir) => {
+ const file = path.join(dir, 'manifest.json');
+ const manifest = JSON.parse(fs.readFileSync(file, 'utf8'));
+ manifest.artifacts.push({ type: 'app', id: '11111111-1111-4111-8111-111111111111', name: 'Support Desk' });
+ fs.writeFileSync(file, JSON.stringify(manifest));
+ },
+ 'a manifest that does not say it lists nothing': (dir) => {
+ const file = path.join(dir, 'manifest.json');
+ const { artifacts, ...rest } = JSON.parse(fs.readFileSync(file, 'utf8'));
+ fs.writeFileSync(file, JSON.stringify(rest));
+ },
+ 'a file of the operator\u2019s own': (dir) => fs.writeFileSync(path.join(dir, 'notes.txt'), 'kept\n'),
+ // The two places the check looks at an entry's kind: the folder's own entries, and the entries inside a folder of the scaffold.
+ 'a link where one of the SDK\u2019s folders would be': (dir) => {
+ fs.rmdirSync(path.join(dir, 'apps'));
+ fs.symlinkSync(tempDir('binding-link-'), path.join(dir, 'apps'), FOLDER_LINK);
+ },
+ 'a link inside one of the SDK\u2019s folders': (dir) => {
+ fs.rmdirSync(path.join(dir, '.metadata', 'views'));
+ fs.symlinkSync(tempDir('binding-link-'), path.join(dir, '.metadata', 'views'), FOLDER_LINK);
+ },
+};
+for (const [what, add] of Object.entries(SOMETHING_SAVED)) {
+ test(`a workspace holding ${what} gets the full account, not the only-opened one`, async () => {
+ const dir = await workspaceFor(WORKSPACE_ENV);
+ add(dir);
+ const text = workspaceBindingError(await mismatchFrom(dir, RUN_ENV), { env: RUN_ENV, workspaceDir: dir }).message;
+ assert.match(text, /belongs to a different environment/);
+ assert.ok(text.includes(`--env ${WORKSPACE_ENV}`), text);
+ assert.match(text, /teardown-model-app\.js/);
+ assert.ok(!/only ever opened|holds nothing a build saved/.test(text), text);
+ });
+}
+
+// --- what a dry run says about the folder it did not use ----------------------------------------------
+
+// The read-only probe a dry run puts to the folder: a real SDK over it, which the plugin asks for its manifest and nothing else.
+function probeFor(dir, instanceUrl) {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ return createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl, httpClient: inertClient() });
+}
+
+test('the preview note: a folder that belongs to this environment, or has no workspace yet, gets none — and asking opens and writes nothing', async () => {
+ const nowhere = path.join(tempDir('binding-note-'), 'nowhere');
+ assert.strictEqual(await workspaceBindingNote(probeFor(nowhere, RUN_ENV), { env: RUN_ENV, workspaceDir: nowhere }), null);
+ assert.ok(!fs.existsSync(nowhere), 'a folder that is not there is not created');
+ const empty = tempDir('binding-note-empty-');
+ assert.strictEqual(await workspaceBindingNote(probeFor(empty, RUN_ENV), { env: RUN_ENV, workspaceDir: empty }), null);
+ assert.deepStrictEqual(fs.readdirSync(empty), [], 'a folder with no manifest is not opened');
+ // The bundle decides what is the same environment: case and trailing slashes are not a mismatch.
+ for (const spelled of [RUN_ENV, 'https://Fabrikam.crm.dynamics.com//', 'HTTPS://FABRIKAM.CRM.DYNAMICS.COM']) {
+ const own = await workspaceFor(spelled, undefined, { built: true });
+ const before = treeOf(own);
+ assert.strictEqual(await workspaceBindingNote(probeFor(own, RUN_ENV), { env: RUN_ENV, workspaceDir: own }), null, spelled);
+ assert.deepStrictEqual(treeOf(own), before, 'and nothing in it is touched');
+ }
+});
+
+test('the preview note for another environment\u2019s folder: the preview ran as normal, an --apply would stop, and no destructive remedy is offered', async () => {
+ const dir = await workspaceFor(WORKSPACE_ENV, undefined, { built: true });
+ const before = treeOf(dir);
+ const note = await workspaceBindingNote(probeFor(dir, RUN_ENV), { env: RUN_ENV, workspaceDir: dir });
+ assert.deepStrictEqual(treeOf(dir), before, 'the probe wrote nothing');
+ assert.match(note, /^this preview works in a temporary workspace, so it ran as normal; a build with --apply would stop before reading or writing anything in this app's workspace folder, which belongs to a different environment:\n/);
+ assert.ok(note.split('\n').includes(` ${dir}`), 'the folder is named alone on its line');
+ assert.ok(note.includes(WORKSPACE_ENV) && note.includes(RUN_ENV), note);
+ assert.ok(note.includes(`--env ${WORKSPACE_ENV}`), 'the way to apply here is named');
+ assert.match(note, /fresh app folder/);
+ assert.ok(!/teardown-model-app|DELETES|--clear-workspace/.test(note), 'a destructive remedy belongs to the --apply that is refused, not to a preview');
+ assert.ok(!/stopped before/.test(note), 'nothing has stopped');
+});
+
+test('the preview note for a folder that was only ever opened says so, and that it can simply go', async () => {
+ const dir = await workspaceFor(WORKSPACE_ENV);
+ const note = await workspaceBindingNote(probeFor(dir, RUN_ENV), { env: RUN_ENV, workspaceDir: dir });
+ assert.match(note, /which was only ever opened for another environment:\n/);
+ assert.match(note, /holds nothing a build saved/);
+ assert.ok(!note.includes(`--env ${WORKSPACE_ENV}`) && !/teardown-model-app|DELETES/.test(note), note);
+ assert.match(note, /delete the folder \(it holds nothing\), or move it aside/);
+});
+
+test('the preview note for a manifest the JSON parser rejects names the folder and says to move it aside', async () => {
+ const dir = await workspaceFor(WORKSPACE_ENV, undefined, { built: true });
+ const manifest = path.join(dir, 'manifest.json');
+ fs.writeFileSync(manifest, fs.readFileSync(manifest, 'utf8').slice(0, 36));
+ const before = treeOf(dir);
+ const note = await workspaceBindingNote(probeFor(dir, RUN_ENV), { env: RUN_ENV, workspaceDir: dir });
+ assert.deepStrictEqual(treeOf(dir), before, 'the probe wrote nothing');
+ assert.match(note, /this preview works in a temporary workspace/);
+ assert.match(note, /manifest\.json that is not valid JSON/);
+ assert.ok(note.split('\n').includes(` ${dir}`));
+ assert.ok(!/Unterminated|position|JSON input/.test(note.replace('not valid JSON', '')), note);
+ assertMovedAside(note);
+});
+
+// A saved copy is another matter. The preview is about which environment the folder belongs to, which only its manifest says —
+// but the bundle's listing parses every copy it lists, and the metadata beside it, to flag the ones holding unpushed edits, so a
+// copy that is not JSON throws the very SyntaxError a manifest that is not JSON throws. A probe that listed would take the one for
+// the other, and tell the operator to move aside a folder an --apply opens without trouble.
+const APP_COPY_ID = '11111111-1111-4111-8111-111111111111';
+
+// A workspace the real bundle opened for `instanceUrl` and a build saved an app into: a valid manifest that lists the app, the
+// app's saved copy, and the metadata the SDK keeps beside it. `copy` and `meta` are written as given, so a test can make either
+// one something the JSON parser rejects.
+async function workspaceWithAppCopy(instanceUrl, dir, { copy = '{"name":"Support Desk"}', meta = '{"etag":null,"snapshot":{"name":"Support Desk"}}' } = {}) {
+ const folder = await workspaceFor(instanceUrl, dir, { built: true });
+ const file = path.join(folder, 'manifest.json');
+ const manifest = JSON.parse(fs.readFileSync(file, 'utf8'));
+ manifest.artifacts.push({ type: 'app', id: APP_COPY_ID, name: 'Support Desk', isDirty: false });
+ fs.writeFileSync(file, `${JSON.stringify(manifest, null, 2)}\n`);
+ fs.writeFileSync(path.join(folder, 'apps', `${APP_COPY_ID}.json`), copy);
+ fs.writeFileSync(path.join(folder, '.metadata', 'apps', `${APP_COPY_ID}.meta.json`), meta);
+ return folder;
+}
+
+test('the preview note: a corrupt saved copy in a folder that belongs to this environment is no manifest problem, and gets no note', async () => {
+ const healthy = await workspaceWithAppCopy(RUN_ENV);
+ assert.strictEqual((await probeFor(healthy, RUN_ENV).listArtifacts('app')).length, 1, 'the fixture is a folder the bundle can list');
+ assert.strictEqual(await workspaceBindingNote(probeFor(healthy, RUN_ENV), { env: RUN_ENV, workspaceDir: healthy }), null);
+ for (const [what, damage] of [
+ ['a saved copy', { copy: '{"name": "Support' }],
+ ['the metadata saved beside a copy', { meta: '{"etag":' }],
+ ]) {
+ const dir = await workspaceWithAppCopy(RUN_ENV, undefined, damage);
+ // The bundle really does trip over it when it lists: that is what the probe must not be taken in by.
+ await assert.rejects(probeFor(dir, RUN_ENV).listArtifacts('app'), (err) => err.name === 'SyntaxError', what);
+ const before = treeOf(dir);
+ assert.strictEqual(await workspaceBindingNote(probeFor(dir, RUN_ENV), { env: RUN_ENV, workspaceDir: dir }), null, `${what} that is not JSON`);
+ assert.deepStrictEqual(treeOf(dir), before, 'and nothing in it is touched');
+ }
+});
+
+test('the preview note for another environment\u2019s folder names that environment, whatever state its saved copies are in', async () => {
+ for (const damage of [{}, { copy: '{"name": "Support' }, { meta: '{"etag":' }]) {
+ const dir = await workspaceWithAppCopy(WORKSPACE_ENV, undefined, damage);
+ const note = await workspaceBindingNote(probeFor(dir, RUN_ENV), { env: RUN_ENV, workspaceDir: dir });
+ assert.match(note, /which belongs to a different environment:\n/, JSON.stringify(damage));
+ assert.ok(note.includes(`--env ${WORKSPACE_ENV}`) && !/not valid JSON/.test(note), note);
+ }
+});
+
+test('the preview note still names a manifest.json the JSON parser rejects when a saved copy in the folder is corrupt as well', async () => {
+ const dir = await workspaceWithAppCopy(RUN_ENV, undefined, { copy: '{"name": "Support' });
+ const manifest = path.join(dir, 'manifest.json');
+ fs.writeFileSync(manifest, fs.readFileSync(manifest, 'utf8').slice(0, 36));
+ const note = await workspaceBindingNote(probeFor(dir, RUN_ENV), { env: RUN_ENV, workspaceDir: dir });
+ assert.match(note, /manifest\.json that is not valid JSON/);
+ assertMovedAside(note);
+});
+
+test('the preview note for this environment\u2019s other host name says it is the same environment', async () => {
+ const dir = await workspaceFor('https://fabrikam.api.crm.dynamics.com', undefined, { built: true });
+ const note = await workspaceBindingNote(probeFor(dir, RUN_ENV), { env: RUN_ENV, workspaceDir: dir });
+ assert.match(note, /two host names of one environment/);
+ assert.ok(note.includes('--env https://fabrikam.api.crm.dynamics.com'), note);
+ assert.ok(!/teardown-model-app|DELETES/.test(note), note);
+});
+
+test('the preview note for a URL recorded with more than an origin says no --env can match it, and names only the origin', async () => {
+ const dir = await workspaceFor(`${RUN_ENV}/api/data/v9.2`, undefined, { built: true });
+ const note = await workspaceBindingNote(probeFor(dir, RUN_ENV), { env: RUN_ENV, workspaceDir: dir });
+ assert.match(note, /records this environment's URL in a form --env cannot take/);
+ assert.match(note, /no --env value can match it/);
+ assert.ok(!note.includes('/api/data'), note);
+ assert.match(note, /fresh app folder/);
+});
+
+test('the preview note never fails a preview: a probe that breaks some other way gives no note', async () => {
+ const ctx = { env: RUN_ENV, workspaceDir: NO_SUCH_FOLDER };
+ const throwing = (err) => ({ getManifest: async () => { throw err; } });
+ assert.strictEqual(await workspaceBindingNote(throwing(Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' })), ctx), null);
+ assert.strictEqual(await workspaceBindingNote(throwing(Object.assign(new Error('not initialized'), { code: 'WORKSPACE_NOT_INITIALIZED' })), ctx), null);
+ assert.strictEqual(await workspaceBindingNote(throwing('a string'), ctx), null);
+ assert.strictEqual(await workspaceBindingNote({}, ctx), null, 'a probe without the call is no probe');
+});
+
+// --- the entry points -------------------------------------------------------------------------------
+
+// A copy of a committed sample as the app folder, so the default workspace is `<folder>/.maker-workspace`.
+function appFolder() {
+ const dir = tempDir('binding-app-');
+ fs.copyFileSync(path.join(scriptsDir, '..', 'samples', 'app-spec.support-desk.json'), path.join(dir, 'app-spec.json'));
+ return { dir, spec: path.join(dir, 'app-spec.json'), workspace: path.join(dir, '.maker-workspace') };
+}
+
+// An HttpClient for a dry run's live plan: every read is answered with no rows (so the plan finds nothing deployed), and
+// every write fails the test — a preview changes nothing in the environment.
+function readOnlyClient(requests = []) {
+ const refuse = (verb) => async (url) => { requests.push(`${verb} ${url}`); throw new Error(`a dry run must not ${verb} ${url}`); };
+ return {
+ get: async (url) => { requests.push(`GET ${url}`); return { status: 200, headers: {}, body: { value: [] } }; },
+ post: refuse('POST'), patch: refuse('PATCH'), delete: refuse('DELETE'), put: refuse('PUT'), postRaw: refuse('POST'),
+ };
+}
+
+// build-model-app.js with the real bundle and the real emitter (in its own sandbox, so exit is catchable).
+// Only authentication and the language read are stubbed — they are network, and the run must stop before
+// anything else is asked of the environment. `client` replaces the inert HTTP client, for a run that is to read.
+function loadBuild(argv, { requests = [], sdkTempDirs = [], client = null } = {}) {
+ const authCli = loadCli(path.join(scriptsDir, 'lib', 'dataverse-auth.js'));
+ const real = require(BUNDLE);
+ const cli = loadCli(path.join(scriptsDir, 'build-model-app.js'), {
+ argv,
+ env: { PATH: path.dirname(process.execPath), POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1' },
+ requires: {
+ './lib/dataverse-auth.js': { ...authCli.exports, preflightAuth: async () => ({ ok: true }) },
+ './lib/entity-provision.js': { resolveAuthoringLanguage: async () => 1033 },
+ './lib/sdk-http-client.js': { createAzHttpClient: () => client || inertClient(requests), SQL_DEADLOCK_VICTIM: /Sql Number: 1205/ },
+ './vendor/cds-maker-sdk.cjs': {
+ createMakerSdk: real.createMakerSdk,
+ createNodeWorkspaceStorage: (dir) => { sdkTempDirs.push(dir); return real.createNodeWorkspaceStorage(dir); },
+ },
+ },
+ });
+ return { cli, authCli };
+}
+
+test('build --apply against another environment\u2019s workspace halts before touching it, and says what to do', async () => {
+ const app = appFolder();
+ await workspaceFor('https://Contoso.crm.dynamics.com/', app.workspace, { built: true });
+ const before = treeOf(app.workspace);
+ const requests = [];
+ const sdkTempDirs = [];
+ const { cli } = loadBuild(['--env', RUN_ENV, '--spec', `@${app.spec}`, '--apply'], { requests, sdkTempDirs });
+
+ await assert.rejects(cli.main(), (err) => {
+ assert.strictEqual(err.code, 'WORKSPACE_ORG_MISMATCH');
+ assert.ok(err.message.includes(WORKSPACE_ENV) && err.message.includes(RUN_ENV), err.message);
+ assert.ok(err.message.includes(`--env ${WORKSPACE_ENV}`));
+ assert.ok(!/cleanWorkspace/.test(err.message));
+ return true;
+ });
+ assert.deepStrictEqual(requests, [], 'no request is sent to either environment');
+ assert.deepStrictEqual(treeOf(app.workspace), before, 'nothing is written into the foreign workspace — no journal, no baseline, no manifest change');
+ assert.ok(!fs.existsSync(path.join(app.workspace, 'build-log.jsonl')) && !fs.existsSync(path.join(app.workspace, 'build-status.json')));
+ assert.ok(sdkTempDirs.length >= 1 && sdkTempDirs.every((d) => d === app.workspace || !fs.existsSync(d)), 'the throwaway workspace the build made is removed again');
+});
+
+// --- a dry run opens nothing --------------------------------------------------------------------------
+
+// A dry run — the default mode — through the real entry point and the real bundle, resolved with what it printed: `stderr` as the
+// separate writes it was made in (the note about the folder is one of them), `stdout` the JSON result. It is offline
+// (`--no-live-plan`) unless a test passes its own `args` and a client that answers.
+async function preview(app, env, { args = ['--no-live-plan'], ...options } = {}) {
+ const { cli, authCli } = loadBuild(['--env', env, '--spec', `@${app.spec}`, ...args], options);
+ await assert.rejects(cli.main(), (err) => err.exitCode === 0, 'a dry run exits 0');
+ return { stderr: [...cli.stderr], stdout: authCli.stdoutText() };
+}
+const isFolderNote = (chunk) => chunk.startsWith('\u26a0 this preview works in a temporary workspace');
+
+test('a dry run creates no workspace, in the app folder or in the folder --workspace names', async () => {
+ // A preview builds nothing, so it has nothing to bind a folder to — and a folder it bound to the environment it only
+ // previewed would later refuse the environment the operator meant.
+ const app = appFolder();
+ const sdkTempDirs = [];
+ await preview(app, RUN_ENV, { sdkTempDirs });
+ assert.ok(!fs.existsSync(app.workspace), 'no .maker-workspace is created');
+ assert.deepStrictEqual(fs.readdirSync(app.dir), ['app-spec.json'], 'the app folder holds what it held');
+ const elsewhere = path.join(tempDir('binding-none-'), 'nowhere');
+ await preview(app, RUN_ENV, { args: ['--no-live-plan', '--workspace', elsewhere], sdkTempDirs });
+ assert.ok(!fs.existsSync(elsewhere), 'nor is the folder --workspace names');
+ assert.ok(sdkTempDirs.length >= 2, 'the SDKs were built');
+ assert.ok(sdkTempDirs.every((dir) => dir === app.workspace || dir === elsewhere || (dir.startsWith(os.tmpdir()) && !fs.existsSync(dir))),
+ `an SDK is only ever pointed at the folder to ask it a question, or at a temporary workspace that is gone again: ${JSON.stringify(sdkTempDirs)}`);
+});
+
+test('a dry run against the wrong environment does not bind the folder to it: a preview or a build against the intended one is not halted', async () => {
+ // Preview against the wrong environment, then against the intended one, then apply — the order an operator works in. Only
+ // an --apply opens the workspace, so the previews leave nothing for the next run to be refused by.
+ const app = appFolder();
+ await preview(app, WORKSPACE_ENV);
+ const second = await preview(app, RUN_ENV);
+ assert.ok(!second.stderr.some(isFolderNote), 'there is no workspace for the second preview to be warned about');
+ await opensWith(app, RUN_ENV);
+ assert.strictEqual(JSON.parse(fs.readFileSync(path.join(app.workspace, 'manifest.json'), 'utf8')).instanceUrl, RUN_ENV, 'the folder is bound by the build, to the build\u2019s environment');
+});
+
+test('a dry run from a folder that belongs to another environment previews as normal, warns that --apply would stop, and leaves the folder alone', async () => {
+ const app = appFolder();
+ await workspaceFor(WORKSPACE_ENV, app.workspace, { built: true });
+ const before = treeOf(app.workspace);
+ const plain = appFolder();
+ const reference = await preview(plain, RUN_ENV);
+ assert.ok(!reference.stderr.some(isFolderNote), 'a folder with no workspace gets no note');
+
+ const requests = [];
+ const sdkTempDirs = [];
+ const result = await preview(app, RUN_ENV, { requests, sdkTempDirs });
+ assert.deepStrictEqual(treeOf(app.workspace), before, 'the folder is exactly as the preview found it');
+ assert.deepStrictEqual(requests, [], 'no request is sent');
+ assert.ok(sdkTempDirs.every((dir) => dir === app.workspace || !fs.existsSync(dir)), 'the temporary workspaces are gone');
+ const note = result.stderr.find(isFolderNote);
+ assert.ok(note, `a warning is printed: ${JSON.stringify(result.stderr)}`);
+ assert.match(note, /^\u26a0 this preview works in a temporary workspace, so it ran as normal; a build with --apply would stop before reading or writing anything in this app's workspace folder, which belongs to a different environment:\n/);
+ assert.ok(note.includes(WORKSPACE_ENV) && note.includes(RUN_ENV) && note.includes(`--env ${WORKSPACE_ENV}`), note);
+ // Everything else it printed is what it prints from any folder: the plan it logs, and its result. (What changed since
+ // the folder's baseline is the one line that depends on the folder, and is pinned below.)
+ const logged = (run, folder) => run.stderr
+ .filter((chunk) => !isFolderNote(chunk) && !chunk.startsWith('\n\u25b8 '))
+ .map((chunk) => chunk.split(folder.dir).join('<app folder>'));
+ assert.deepStrictEqual(logged(result, app), logged(reference, plain), 'the plan it logs is the same');
+ assert.strictEqual(result.stdout.split(app.dir).join('<app folder>'), reference.stdout.split(plain.dir).join('<app folder>'), 'and so is its result');
+});
+
+test('a dry run from a folder that was only ever opened for another environment says it can simply go, and runs as normal', async () => {
+ const app = appFolder();
+ await workspaceFor(WORKSPACE_ENV, app.workspace);
+ const before = treeOf(app.workspace);
+ const { stderr } = await preview(app, RUN_ENV);
+ const note = stderr.find(isFolderNote);
+ assert.ok(note, 'warned');
+ assert.match(note, /which was only ever opened for another environment/);
+ assert.match(note, /delete the folder \(it holds nothing\), or move it aside/);
+ assert.deepStrictEqual(treeOf(app.workspace), before);
+});
+
+test('a dry run from a folder whose manifest.json is not valid JSON previews as normal and says to move the folder aside', async () => {
+ const app = appFolder();
+ await workspaceFor(WORKSPACE_ENV, app.workspace, { built: true });
+ const manifest = path.join(app.workspace, 'manifest.json');
+ fs.writeFileSync(manifest, fs.readFileSync(manifest, 'utf8').slice(0, 36));
+ const before = treeOf(app.workspace);
+ const { stderr } = await preview(app, RUN_ENV);
+ const note = stderr.find(isFolderNote);
+ assert.ok(note, `warned: ${JSON.stringify(stderr)}`);
+ assert.match(note, /manifest\.json that is not valid JSON/);
+ assertMovedAside(note);
+ assert.deepStrictEqual(treeOf(app.workspace), before);
+});
+
+test('a dry run from a folder that belongs to its own environment, under any spelling of the host, says nothing about the folder', async () => {
+ for (const spelled of [RUN_ENV, 'https://Fabrikam.crm.dynamics.com//']) {
+ const app = appFolder();
+ await workspaceFor(spelled, app.workspace, { built: true });
+ const before = treeOf(app.workspace);
+ const { stderr } = await preview(app, RUN_ENV);
+ assert.ok(!stderr.some(isFolderNote), `${spelled}: ${JSON.stringify(stderr)}`);
+ assert.deepStrictEqual(treeOf(app.workspace), before);
+ }
+});
+
+test('a dry run from a folder that belongs to its own environment says nothing about a corrupt saved copy in it', async () => {
+ // Not a binding problem, and not the manifest: the folder belongs here, and an --apply opens it (see below). The preview reads
+ // no saved copy, so it has nothing to say about one — least of all that the manifest is the trouble.
+ for (const damage of [{ copy: '{"name": "Support' }, { meta: '{"etag":' }]) {
+ const app = appFolder();
+ await workspaceWithAppCopy(RUN_ENV, app.workspace, damage);
+ const before = treeOf(app.workspace);
+ const { stderr } = await preview(app, RUN_ENV);
+ assert.ok(!stderr.some(isFolderNote), JSON.stringify(stderr));
+ assert.ok(!stderr.some((chunk) => /not valid JSON/.test(chunk)), JSON.stringify(stderr));
+ assert.deepStrictEqual(treeOf(app.workspace), before);
+ }
+});
+
+test('a dry run still reports what changed since the last apply, from the folder\u2019s baseline, without opening the folder', async () => {
+ const { writeBaseline } = require('../lib/deployed-baseline.js');
+ const { migrateAppSpec } = require('../lib/app-spec.js');
+ const { appUniqueName } = require('../lib/sdk-build.js');
+ const app = appFolder();
+ const spec = migrateAppSpec(JSON.parse(fs.readFileSync(app.spec, 'utf8')));
+ // A folder a build finished in, as far as the preview can tell: the baseline, and no SDK workspace in it.
+ fs.mkdirSync(app.workspace);
+ writeBaseline(app.workspace, spec, { appDir: app.dir, environment: RUN_ENV, appUniqueName: appUniqueName(spec) });
+ const before = treeOf(app.workspace);
+ assert.ok(Object.keys(before).includes('last-applied.json'));
+
+ const unchanged = await preview(app, RUN_ENV);
+ assert.ok(unchanged.stderr.some((chunk) => /\u25b8 No spec changes since the last apply/.test(chunk)), JSON.stringify(unchanged.stderr));
+
+ const edited = JSON.parse(fs.readFileSync(app.spec, 'utf8'));
+ edited.app.name = `${edited.app.name} (edited)`;
+ fs.writeFileSync(app.spec, JSON.stringify(edited));
+ const changed = await preview(app, RUN_ENV);
+ assert.ok(changed.stderr.some((chunk) => /\u25b8 Changed since last apply: /.test(chunk)), JSON.stringify(changed.stderr));
+
+ assert.deepStrictEqual(treeOf(app.workspace), before, 'only the baseline is in the folder: no manifest, no empty folders, nothing else was added');
+});
+
+test('a dry run\u2019s live plan reads the environment through a temporary workspace: the folder it is run from is no part of it', async () => {
+ // The live plan's reads all go to the server (it deliberately skips the metadata read that would cache into a workspace),
+ // so a folder that belongs to another environment — which the SDK would refuse to read through — is no obstacle.
+ const app = appFolder();
+ await workspaceFor(WORKSPACE_ENV, app.workspace, { built: true });
+ const before = treeOf(app.workspace);
+ const requests = [];
+ const sdkTempDirs = [];
+ const result = await preview(app, RUN_ENV, { args: [], client: readOnlyClient(requests), sdkTempDirs });
+ assert.ok(requests.length > 0 && requests.every((request) => request.startsWith('GET ')), `it reads the environment, and only reads: ${JSON.stringify(requests.slice(0, 3))}`);
+ assert.ok(requests.every((request) => request.includes('/api/data/')), JSON.stringify(requests.slice(0, 3)));
+ assert.ok(!result.stderr.some((chunk) => /no live probe/.test(chunk)), 'it is the live plan, not the offline listing');
+ assert.ok(result.stderr.some(isFolderNote), 'the folder it did not use is still reported');
+ assert.deepStrictEqual(treeOf(app.workspace), before, 'the folder is exactly as it was — nothing the live plan read was cached into it');
+ assert.ok(sdkTempDirs.every((dir) => dir === app.workspace || !fs.existsSync(dir)), 'the temporary workspaces are gone');
+});
+
+test('a dry run still refuses a link, or a file, where the workspace would be', async () => {
+ const linked = appFolder();
+ fs.symlinkSync(tempDir('binding-real-'), linked.workspace, FOLDER_LINK);
+ const viaLink = loadBuild(['--env', RUN_ENV, '--spec', `@${linked.spec}`, '--no-live-plan']);
+ await assert.rejects(viaLink.cli.main(), (err) => err.exitCode === 1);
+ assert.match(`${viaLink.authCli.stdoutText()}${viaLink.authCli.stderrText()}`, /symbolic link or junction/);
+
+ const occupied = appFolder();
+ fs.writeFileSync(occupied.workspace, 'not a folder');
+ const viaFile = loadBuild(['--env', RUN_ENV, '--spec', `@${occupied.spec}`, '--no-live-plan']);
+ await assert.rejects(viaFile.cli.main(), (err) => err.exitCode === 1);
+ assert.match(`${viaFile.authCli.stdoutText()}${viaFile.authCli.stderrText()}`, /not a directory/);
+});
+
+test('--workspace pointing at another environment\u2019s workspace is refused the same way, and the teardown it offers clears THAT folder', async () => {
+ const app = appFolder();
+ const elsewhere = await workspaceFor(WORKSPACE_ENV, undefined, { built: true });
+ const { cli } = loadBuild(['--env', RUN_ENV, '--spec', `@${app.spec}`, '--workspace', elsewhere, '--apply']);
+ await assert.rejects(cli.main(), (err) => {
+ assert.strictEqual(err.code, 'WORKSPACE_ORG_MISMATCH');
+ const lines = err.message.split('\n');
+ assert.ok(lines.includes(` ${elsewhere}`), 'the folder it was given is the one named, alone on its line');
+ assert.ok(err.message.includes(`--env ${WORKSPACE_ENV}`), err.message);
+ // Teardown clears `--workspace`, else `<spec dir>/.maker-workspace` — here a different folder. Left out, the
+ // command would clear (or find nothing to clear in) the wrong one and this build would halt again.
+ const teardown = lines.find((line) => /teardown-model-app\.js/.test(line));
+ assert.match(teardown, /--workspace <the folder printed above>/, 'the command takes the folder the halt prints');
+ assert.ok(!teardown.includes(elsewhere), 'and never embeds it');
+ assert.notStrictEqual(elsewhere, app.workspace, 'the fixture really names a folder other than the default one');
+ return true;
+ });
+});
+
+test('build --apply against a folder that was only ever opened for another environment halts, and says nothing was built there', async () => {
+ // The folder an earlier preview (or a build that stopped at its start) opened for the wrong environment: only the
+ // SDK's manifest and empty folders. The halt must not send the operator back to an environment nothing was built in,
+ // or offer to tear down what was never there.
+ const { halt } = await buildHalt({ recorded: WORKSPACE_ENV, env: RUN_ENV, built: false });
+ const text = halt.message;
+ assert.match(text, /only ever opened for https:\/\/contoso\.crm\.dynamics\.com/);
+ assert.match(text, /nothing was built there/);
+ assert.ok(!text.includes(`--env ${WORKSPACE_ENV}`) && !/teardown-model-app|DELETES/.test(text), text);
+});
+
+test('build --apply against a folder whose manifest.json is not valid JSON halts with the folder named and advice, not the parser\u2019s message', async () => {
+ const app = appFolder();
+ await workspaceFor(WORKSPACE_ENV, app.workspace, { built: true });
+ const manifest = path.join(app.workspace, 'manifest.json');
+ fs.writeFileSync(manifest, fs.readFileSync(manifest, 'utf8').slice(0, 36)); // cut inside the URL
+ const raw = await mismatchFrom(app.workspace, RUN_ENV);
+ assert.strictEqual(raw.name, 'SyntaxError', 'the bundle lets the JSON parser\u2019s own error out: that is what the plugin recognizes');
+ const before = treeOf(app.workspace);
+ const requests = [];
+ const { cli } = loadBuild(['--env', RUN_ENV, '--spec', `@${app.spec}`, '--apply'], { requests });
+ await assert.rejects(cli.main(), (err) => {
+ assert.strictEqual(err.code, 'WORKSPACE_MANIFEST_INVALID', `not the parser's message: ${err.message}`);
+ assert.ok(!err.message.includes(raw.message), 'the parser\u2019s text is not echoed');
+ assert.ok(err.message.split('\n').includes(` ${app.workspace}`), `the folder is named: ${err.message}`);
+ assert.match(err.message, /manifest\.json that is not valid JSON/);
+ assertMovedAside(err.message);
+ return true;
+ });
+ assert.deepStrictEqual(requests, [], 'no request is sent');
+ assert.deepStrictEqual(treeOf(app.workspace), before, 'the folder is exactly as it was: moved aside by the operator, never cleared by the build');
+});
+
+// The halt for a folder recorded as `recorded`, by a build run with `env`: the real bundle through the real entry point.
+// `built` is whether anything beyond the SDK's own empty folders was saved in it (see `workspaceFor`).
+async function buildHalt({ recorded, env, built = true }) {
+ const app = appFolder();
+ await workspaceFor(recorded, app.workspace, { built });
+ const before = treeOf(app.workspace);
+ const requests = [];
+ const { cli } = loadBuild(['--env', env, '--spec', `@${app.spec}`, '--apply'], { requests });
+ let halt = null;
+ await assert.rejects(cli.main(), (err) => { halt = err; return true; });
+ assert.strictEqual(halt.code, 'WORKSPACE_ORG_MISMATCH', String(halt && halt.message));
+ assert.deepStrictEqual(requests, [], 'no request is sent');
+ assert.deepStrictEqual(treeOf(app.workspace), before, 'the folder is exactly as it was');
+ return { halt, app };
+}
+
+// The same folder, built again with `--apply` and `env`: the one thing that opens a workspace, so the one thing that can meet
+// a folder that belongs elsewhere. The HTTP client is inert, so a build the workspace lets through stops at its first read of
+// the environment — the safety probe before a destructive apply — and exits 1 for that; one the workspace refuses throws the
+// halt instead, which is how the two are told apart.
+async function opensWith(app, env) {
+ const { cli, authCli } = loadBuild(['--env', env, '--spec', `@${app.spec}`, '--apply']);
+ await assert.rejects(cli.main(), (err) => err.exitCode === 1 && err.code !== 'WORKSPACE_ORG_MISMATCH', `--env ${env} opens the folder`);
+ assert.match(`${authCli.stdoutText()}${authCli.stderrText()}`, /preflight safety check could not run/, 'it got as far as its first read of the environment');
+}
+
+// Two spellings of ONE environment are not "another environment": the halt must not say so, and must not offer the
+// teardown, whose target is then this run's own environment. The bundle's decision is real here — these are the
+// recordings it refuses.
+for (const [recorded, env] of [
+ ['https://contoso.api.crm.dynamics.com', 'https://contoso.crm.dynamics.com'],
+ ['https://contoso.crm.dynamics.com', 'https://contoso.api.crm.dynamics.com'],
+]) {
+ test(`a workspace opened as ${recorded} is the same environment as ${env}: the halt says so and gives the host to go back to`, async () => {
+ const { halt, app } = await buildHalt({ recorded, env });
+ const text = halt.message;
+ assert.ok(text.includes(recorded) && text.includes(env), text);
+ assert.match(text, /two host names of one environment/);
+ assert.ok(!/different environment/.test(text), text);
+ assert.ok(!/teardown-model-app|DELETES|--clear-workspace/.test(text), `no teardown: it would delete from this run\u2019s own environment: ${text}`);
+ assert.ok(text.includes(`--env ${recorded}`), `the exact --env that matches the folder: ${text}`);
+ assert.match(text, /fresh app folder/);
+ // The promise is kept: that --env opens this very folder.
+ await opensWith(app, recorded);
+ });
+}
+
+// A manifest written by another tool can carry more than an origin. `--env` takes the origin only, so no value can
+// match it — and printing two identical origins, or offering the teardown, would be wrong.
+for (const recorded of [
+ 'https://contoso.crm.dynamics.com/api/data/v9.2',
+ 'https://contoso.crm.dynamics.com:443',
+ 'https://contoso.crm.dynamics.com:8443',
+ 'http://contoso.crm.dynamics.com',
+]) {
+ test(`a workspace recorded as ${recorded} is this environment under a spelling no --env can match: a fresh folder is the only way, and nothing is offered to delete`, async () => {
+ const { halt } = await buildHalt({ recorded, env: 'https://contoso.crm.dynamics.com' });
+ const text = halt.message;
+ assert.match(text, /records this environment's URL in a form --env cannot take/);
+ assert.match(text, /no --env value can match it/);
+ assert.ok(!/different environment/.test(text), text);
+ assert.ok(!/teardown-model-app|DELETES|--clear-workspace/.test(text), text);
+ assert.ok(!/--env https:\/\/contoso/.test(text), `no --env remedy: ${text}`);
+ assert.ok(!text.includes('/api/data') && !text.includes(':8443'), `only an origin is ever printed: ${text}`);
+ assert.match(text, /fresh app folder/);
+ assert.match(text, /this run targets: https:\/\/contoso\.crm\.dynamics\.com\b/);
+ });
+}
+
+test('the .api. host recorded together with more than an origin has no --env to go back to either', async () => {
+ const { halt } = await buildHalt({ recorded: 'https://contoso.api.crm.dynamics.com/api/data/v9.2', env: 'https://contoso.crm.dynamics.com' });
+ const text = halt.message;
+ assert.match(text, /two host names of one environment/);
+ assert.match(text, /no --env value can match it/);
+ assert.ok(!/teardown-model-app|DELETES/.test(text) && !/--env https:\/\/contoso\.api/.test(text), text);
+ assert.match(text, /fresh app folder/);
+});
+
+test('another environment recorded with more than an origin offers a fresh folder only: no --env or teardown could name it exactly', async () => {
+ const { halt } = await buildHalt({ recorded: 'https://fabrikam.crm.dynamics.com/api/data/v9.2', env: 'https://contoso.crm.dynamics.com' });
+ const text = halt.message;
+ assert.match(text, /belongs to a different environment/);
+ assert.match(text, /workspace belongs to: https:\/\/fabrikam\.crm\.dynamics\.com\n/);
+ assert.ok(!text.includes('/api/data'), text);
+ assert.match(text, /no --env value can match it/);
+ assert.ok(!/teardown-model-app|DELETES/.test(text) && !/ --env https:\/\/fabrikam/.test(text), text);
+ assert.match(text, /fresh app folder/);
+});
+
+test('a different host is another environment even when it differs from this one only by a label', async () => {
+ // `.api.` is the one label that names the same environment; any other is a different one.
+ const { halt } = await buildHalt({ recorded: 'https://contoso2.crm.dynamics.com', env: 'https://contoso.crm.dynamics.com' });
+ assert.match(halt.message, /belongs to a different environment/);
+ assert.ok(halt.message.includes('--env https://contoso2.crm.dynamics.com'));
+ assert.match(halt.message, /DELETES what the spec declares from https:\/\/contoso2\.crm\.dynamics\.com/);
+});
+
+test('the same environment spelled differently is not a mismatch', async () => {
+ // Case and a trailing slash name one environment; halting the run for it would be a false alarm. The
+ // decision is the bundle's, so this drives the real bundle through the real entry point.
+ const app = appFolder();
+ await workspaceFor(RUN_ENV, app.workspace, { built: true });
+ await opensWith(app, 'https://Fabrikam.crm.dynamics.com/');
+});
+
+test('build --apply opens a folder that belongs to its environment although a saved copy in it is corrupt: that is no halt for a manifest', async () => {
+ // Opening a workspace parses its manifest and nothing else, so a corrupt saved copy is not met here — which is what makes the
+ // parser's error name enough to recognize a corrupt MANIFEST (lib/workspace-binding.js): nothing asked of a workspace at this
+ // point can throw it for a copy. The SDK meets the copy when it first reads it, later in the build.
+ for (const damage of [{ copy: '{"name": "Support' }, { meta: '{"etag":' }]) {
+ const app = appFolder();
+ await workspaceWithAppCopy(RUN_ENV, app.workspace, damage);
+ await opensWith(app, RUN_ENV);
+ }
+});
+
+test('a fresh app folder (no workspace yet) is bound to the environment of the first build, not refused', async () => {
+ const app = appFolder();
+ await opensWith(app, RUN_ENV);
+ const manifest = JSON.parse(fs.readFileSync(path.join(app.workspace, 'manifest.json'), 'utf8'));
+ assert.strictEqual(manifest.instanceUrl, RUN_ENV);
+});
+
+test('a folder the build bound under one spelling of the host is reopened under another spelling of the same host', async () => {
+ // The build hands the SDK the `--env` text as it was typed (after the HTTP client has checked it is an https Dataverse
+ // origin), so a manifest can carry capitals or a trailing slash. The SDK compares URLs ignoring both, so the plugin
+ // does not have to canonicalize what it passes: no spelling the plugin can write meets a mismatch except the
+ // `.api.` host, which the halt above tells apart.
+ const app = appFolder();
+ const typed = 'https://Fabrikam.crm.dynamics.com//';
+ await opensWith(app, typed);
+ assert.strictEqual(JSON.parse(fs.readFileSync(path.join(app.workspace, 'manifest.json'), 'utf8')).instanceUrl, typed, 'the manifest carries what was typed');
+ await opensWith(app, RUN_ENV);
+ await opensWith(app, 'HTTPS://FABRIKAM.CRM.DYNAMICS.COM');
+});
+
+// --- verify: never the app folder's persistent workspace ---------------------------------------------
+
+// verify-model-app.js with the real bundle, and the verification itself optionally replaced to see what it is handed.
+// The HTTP client is inert: every read is refused, so a run that gets past the workspace stops at its first read,
+// with the transport failure that read raised.
+function loadVerify(argv, { requests = [], sdkDirs = [], verifySpec = null } = {}) {
+ const authCli = loadCli(path.join(scriptsDir, 'lib', 'dataverse-auth.js'));
+ const real = require(BUNDLE);
+ const requires = {
+ './lib/dataverse-auth.js': authCli.exports,
+ './lib/sdk-http-client.js': { createAzHttpClient: () => inertClient(requests) },
+ './vendor/cds-maker-sdk.cjs': {
+ createMakerSdk: real.createMakerSdk,
+ createNodeWorkspaceStorage: (dir) => { sdkDirs.push(dir); return real.createNodeWorkspaceStorage(dir); },
+ },
+ };
+ if (verifySpec) requires['./lib/verify-spec.js'] = { verifySpec };
+ const cli = loadCli(path.join(scriptsDir, 'verify-model-app.js'), { argv, requires });
+ return { cli, output: () => `${authCli.stdoutText()}${authCli.stderrText()}` };
+}
+
+test('verify runs against any environment: a folder bound to another one is neither refused nor touched', async () => {
+ // Build in one environment, import the solution into another, verify there from the same folder. Every read verify
+ // makes goes to the server, so nothing in that folder's workspace could answer one — and the SDK would refuse it.
+ const app = appFolder();
+ await workspaceFor(WORKSPACE_ENV, app.workspace);
+ const before = treeOf(app.workspace);
+ const requests = [];
+ const sdkDirs = [];
+ const { cli } = loadVerify(['--env', RUN_ENV, '--spec', `@${app.spec}`], { requests, sdkDirs });
+ await assert.rejects(cli.main(), (err) => {
+ assert.notStrictEqual(err.code, 'WORKSPACE_ORG_MISMATCH', 'verify is not halted by the folder\u2019s binding');
+ assert.match(err.message, /unexpected GET .*EntityDefinitions/, 'it got as far as its first read of the environment');
+ return true;
+ });
+ assert.ok(requests.length > 0);
+ assert.deepStrictEqual(treeOf(app.workspace), before, 'the folder is exactly as verify found it');
+ assert.ok(sdkDirs.length >= 1 && sdkDirs.every((dir) => path.dirname(dir) === os.tmpdir() && !fs.existsSync(dir)), `every SDK worked in a temporary workspace that is gone again: ${JSON.stringify(sdkDirs)}`);
+});
+
+test('verify does not bind a folder that has no workspace yet to the environment it verified', async () => {
+ const app = appFolder();
+ const { cli } = loadVerify(['--env', RUN_ENV, '--spec', `@${app.spec}`]);
+ await assert.rejects(cli.main(), /unexpected GET/);
+ assert.ok(!fs.existsSync(app.workspace), 'verify creates no .maker-workspace');
+ // ...so the first thing to open the folder, a build, binds it to ITS environment.
+ await opensWith(app, WORKSPACE_ENV);
+ assert.strictEqual(JSON.parse(fs.readFileSync(path.join(app.workspace, 'manifest.json'), 'utf8')).instanceUrl, WORKSPACE_ENV);
+});
+
+test('verify still reads the build\u2019s baseline from the folder, for the environment it describes', async () => {
+ const { writeBaseline } = require('../lib/deployed-baseline.js');
+ const { migrateAppSpec } = require('../lib/app-spec.js');
+ const { appUniqueName } = require('../lib/sdk-build.js');
+ const app = appFolder();
+ const spec = migrateAppSpec(JSON.parse(fs.readFileSync(app.spec, 'utf8')));
+ // A folder built against WORKSPACE_ENV: the SDK's own workspace is bound to it, and the baseline is stamped with it.
+ await workspaceFor(WORKSPACE_ENV, app.workspace);
+ writeBaseline(app.workspace, spec, { appDir: app.dir, environment: WORKSPACE_ENV, appUniqueName: appUniqueName(spec) });
+ const baselineFor = async (env) => {
+ const seen = [];
+ const { cli } = loadVerify(['--env', env, '--spec', `@${app.spec}`], { verifySpec: async (s, reader, opts) => { seen.push(opts); return { ok: true, checks: [], missing: [] }; } });
+ await assert.rejects(cli.main(), (err) => err.exitCode === 0);
+ assert.strictEqual(seen.length, 1);
+ return seen[0].baselineSpec;
+ };
+ const own = await baselineFor(WORKSPACE_ENV);
+ assert.ok(own && own.app && own.app.name === spec.app.name, 'the environment the baseline describes gets it');
+ assert.strictEqual(await baselineFor(RUN_ENV), undefined, 'another environment gets none: what the designer changed there says nothing about this snapshot');
+});
+
+test('verify refuses a link where the baseline would be read from, and a folder that is not there is just one with no baseline', async () => {
+ const app = appFolder();
+ const real = tempDir('binding-real-');
+ fs.symlinkSync(real, app.workspace, FOLDER_LINK);
+ const linked = loadVerify(['--env', RUN_ENV, '--spec', `@${app.spec}`]);
+ await assert.rejects(linked.cli.main(), (err) => err.exitCode === 1);
+ assert.match(linked.output(), /symbolic link or junction/);
+
+ const missing = path.join(tempDir('binding-none-'), 'nowhere');
+ const absent = loadVerify(['--env', RUN_ENV, '--spec', `@${app.spec}`, '--workspace', missing]);
+ await assert.rejects(absent.cli.main(), /unexpected GET/, 'it goes on to verify, with no baseline');
+ assert.ok(!fs.existsSync(missing), 'and creates nothing');
+});
+
+// --- the rule the halt rests on ---------------------------------------------------------------------
+
+test('no script clears or re-binds an SDK workspace', () => {
+ // `cleanWorkspace()` is the bundle's remedy for a mismatch: it discards the SDK's saved copies, metadata and
+ // baselines of the workspace (and so any edit in a copy that was never pushed) and binds it to the new
+ // environment, leaving the page-ownership receipts and the plugin's baseline beside them describing the old one.
+ // Choosing to do that is the operator's decision (a teardown that ends in --clear-workspace, which refuses while
+ // a receipt remains), never something a halt does on its behalf.
+ assert.deepStrictEqual(scriptsMatching(/\bcleanWorkspace\s*\(/), [], 'a script calls cleanWorkspace()');
+});
diff --git a/plugins/model-apps/scripts/vendor/PROVENANCE.json b/plugins/model-apps/scripts/vendor/PROVENANCE.json
index 0369b893b..a5a44e88f 100644
--- a/plugins/model-apps/scripts/vendor/PROVENANCE.json
+++ b/plugins/model-apps/scripts/vendor/PROVENANCE.json
@@ -1,14 +1,14 @@
{
- "commit": "8930278fa2da1ebb761496d4ef5a8079da9bc5fc",
- "subject": "cds-maker-sdk: languages, app form lists, genPage type, header token, publish perf (combined)",
+ "commit": "0ffa4384f9e2bba5a8d9d44f1d5d3ee2d72e6091",
+ "subject": "cds-maker-sdk: small fixes, open items (app publish bracket, Active BPF edit, metadata consistency, header writes) and getEnvironmentLanguages",
"dirtySdkPackage": 0,
- "libBuiltAt": "2026-10-01T17:02:15.216Z",
- "newestSrcAt": "2026-10-01T16:35:27.021Z",
+ "libBuiltAt": "2026-10-08T15:16:23.180Z",
+ "newestSrcAt": "2026-10-08T15:15:33.120Z",
"libIsStale": false,
"nostub": false,
"esbuildVersion": "0.28.1",
"nodeVersion": "v20.20.2",
- "builtAt": "2026-10-01T17:03:29.974Z",
- "bundleSha256": "d06d95be213156070a1b89027881cc72e228aead217ccca94160177760fde8c1",
- "bundleBytes": 843285
+ "builtAt": "2026-10-08T15:21:49.272Z",
+ "bundleSha256": "4dacd9b9700dd0bd781edacad2dc2b9e73e73c816014fad4e447329b861bb408",
+ "bundleBytes": 930555
}
diff --git a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs
index 76c0625d7..abf055115 100644
--- a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs
+++ b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs
@@ -25,56 +25,56 @@
}
globalThis.document=globalThis.document||globalThis.window.document;
})();
-var bx=Object.create;var El=Object.defineProperty;var wx=Object.getOwnPropertyDescriptor;var Ax=Object.getOwnPropertyNames;var Ex=Object.getPrototypeOf,Cx=Object.prototype.hasOwnProperty;var R=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var b=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},gn=(e,t)=>{for(var r in t)El(e,r,{get:t[r],enumerable:!0})},Al=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ax(t))!Cx.call(e,i)&&i!==r&&El(e,i,{get:()=>t[i],enumerable:!(n=wx(t,i))||n.enumerable});return e},Jn=(e,t,r)=>(Al(e,t,"default"),r&&Al(r,t,"default")),de=(e,t,r)=>(r=e!=null?bx(Ex(e)):{},Al(t||!e||!e.__esModule?El(r,"default",{value:e,enumerable:!0}):r,e)),$r=e=>Al(El({},"__esModule",{value:!0}),e);var Ti=b(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.DateTimeBehavior=D.PrecisionSource=D.StringFormatName=D.SourceType=D.ImeMode=D.SolutionEntityTypeCodeExtToComponentTypeCode=D.SolutionComponentTypeCodeToEntityTypeCodeExt=D.SolutionComponentVirtualAttributeSubtype=D.EntityTypeCode=D.SolutionComponentTypeCodeExt=D.RootComponentBehavior=D.SolutionComponentTypeCode=D.EntityKeyIndexStatus=D.ViewStateCode=D.ViewStatusCode=D.RelationshipSecurityTypes=D.CascadeType=D.RelationshipTypeExt=D.RelationshipType=D.AppSubType=D.BusinessProcessType=D.WorkflowCategory=D.WorkflowScope=D.WorkflowTypeCode=D.StatusCodeEnabledDisabled=D.StateCodeEnabledDisabled=D.StatusCode=D.StateCode=D.OptionSetType=D.AttributeTypeCodeNum=D.AttributeFormatName=D.AttributeFormatCode=D.AttributeTypeName=D.AttributeTypeCode=D.PluginSourceType=D.AuthType=D.PluginIsolationMode=D.ComponentState=D.ChartType=D.ChartsType=D.ViewType=D.AttributeType=D.ActivationState=D.FormPresentation=D.FormType=D.TableTypeCode=D.TableTypes=D.ActivityTypeMask=D.PrincipalType=D.OwnershipTypes=void 0;D.QueryType=D.KnownCustomSolutionComponentEntitySetName=D.TeamTypeEnum=D.EnvironmentVariableDefinitionTypeEnum=D.ConnectorTypeEnum=D.RoleInheritance=D.DefaultRoleTemplates=D.DeleteDependencyErrorCode=D.ServiceEndpointConnectionMode=D.ServiceEndpointContract=D.ServiceNamespaceFormat=D.ConnectionRoleCategory=D.ReportTypeCode=D.SdkMessageProcessingMode=D.SupportedDeployment=D.SdkMessageProcessingStage=D.WebResourceTypeCode=D.IntegerFormat=D.DateTimeFormat=void 0;var N0;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(N0||(D.OwnershipTypes=N0={}));var D0;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(D0||(D.PrincipalType=D0={}));var _0;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(_0||(D.ActivityTypeMask=_0={}));var I0;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(I0||(D.TableTypes=I0={}));var T0;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(T0||(D.TableTypeCode=T0={}));var P0;(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"})(P0||(D.FormType=P0={}));var R0;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(R0||(D.FormPresentation=R0={}));var O0;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(O0||(D.ActivationState=O0={}));var x0;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(x0||(D.AttributeType=x0={}));var L0;(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"})(L0||(D.ViewType=L0={}));var k0;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(k0||(D.ChartsType=k0={}));var F0;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(F0||(D.ChartType=F0={}));var M0;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(M0||(D.ComponentState=M0={}));var B0;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(B0||(D.PluginIsolationMode=B0={}));var $0;(function(e){e[e.BasicAuth=0]="BasicAuth"})($0||(D.AuthType=$0={}));var U0;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(U0||(D.PluginSourceType=U0={}));var q0;(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"})(q0||(D.AttributeTypeCode=q0={}));var V0;(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"})(V0||(D.AttributeTypeName=V0={}));var G0;(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"})(G0||(D.AttributeFormatCode=G0={}));var z0;(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"})(z0||(D.AttributeFormatName=z0={}));var W0;(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"})(W0||(D.AttributeTypeCodeNum=W0={}));var j0;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(j0||(D.OptionSetType=j0={}));var H0;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(H0||(D.StateCode=H0={}));var K0;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(K0||(D.StatusCode=K0={}));var J0;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(J0||(D.StateCodeEnabledDisabled=J0={}));var Q0;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(Q0||(D.StatusCodeEnabledDisabled=Q0={}));var X0;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(X0||(D.WorkflowTypeCode=X0={}));var Y0;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(Y0||(D.WorkflowScope=Y0={}));var Z0;(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"})(Z0||(D.WorkflowCategory=Z0={}));var ev;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(ev||(D.BusinessProcessType=ev={}));var tv;(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"})(tv||(D.AppSubType=tv={}));var rv;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(rv||(D.RelationshipType=rv={}));var nv;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(nv||(D.RelationshipTypeExt=nv={}));var iv;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(iv||(D.CascadeType=iv={}));var ov;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(ov||(D.RelationshipSecurityTypes=ov={}));var av;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(av||(D.ViewStatusCode=av={}));var sv;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(sv||(D.ViewStateCode=sv={}));var lv;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(lv||(D.EntityKeyIndexStatus=lv={}));var uv;(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"})(uv||(D.SolutionComponentTypeCode=uv={}));var cv;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(cv||(D.RootComponentBehavior=cv={}));var Cl;(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"})(Cl||(D.SolutionComponentTypeCodeExt=Cl={}));var Sl;(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"})(Sl||(D.EntityTypeCode=Sl={}));var dv;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(dv||(D.SolutionComponentVirtualAttributeSubtype=dv={}));function Sx(e){let t=Cl[e];return Sl[t]}D.SolutionComponentTypeCodeToEntityTypeCodeExt=Sx;function Nx(e){let t=Sl[e];return Cl[t]}D.SolutionEntityTypeCodeExtToComponentTypeCode=Nx;var pv;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(pv||(D.ImeMode=pv={}));var fv;(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"})(fv||(D.SourceType=fv={}));var mv;(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"})(mv||(D.StringFormatName=mv={}));var hv;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(hv||(D.PrecisionSource=hv={}));var gv;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(gv||(D.DateTimeBehavior=gv={}));var vv;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(vv||(D.DateTimeFormat=vv={}));var yv;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(yv||(D.IntegerFormat=yv={}));var bv;(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"})(bv||(D.WebResourceTypeCode=bv={}));var wv;(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"})(wv||(D.SdkMessageProcessingStage=wv={}));var Av;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(Av||(D.SupportedDeployment=Av={}));var Ev;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(Ev||(D.SdkMessageProcessingMode=Ev={}));var Cv;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(Cv||(D.ReportTypeCode=Cv={}));var Sv;(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"})(Sv||(D.ConnectionRoleCategory=Sv={}));var Nv;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(Nv||(D.ServiceNamespaceFormat=Nv={}));var Dv;(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"})(Dv||(D.ServiceEndpointContract=Dv={}));var _v;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(_v||(D.ServiceEndpointConnectionMode=_v={}));var Iv;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(Iv||(D.DeleteDependencyErrorCode=Iv={}));var Tv;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(Tv||(D.DefaultRoleTemplates=Tv={}));var Pv;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(Pv||(D.RoleInheritance=Pv={}));var Rv;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(Rv||(D.ConnectorTypeEnum=Rv={}));var Ov;(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"})(Ov||(D.EnvironmentVariableDefinitionTypeEnum=Ov={}));var xv;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(xv||(D.TeamTypeEnum=xv={}));var Lv;(function(e){e.Bots="bots"})(Lv||(D.KnownCustomSolutionComponentEntitySetName=Lv={}));var kv;(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"})(kv||(D.QueryType=kv={}))});var re=b(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.IncompatibleWorkspaceError=Q.PathTraversalError=Q.AmbiguousArtifactError=Q.JsonPointerError=Q.NotImplementedError=Q.WorkspaceNotInitializedError=Q.ConnectionError=Q.VersionConflictError=Q.LocalEditsWouldBeLostError=Q.StaleArtifactError=Q.InvalidArgumentError=Q.ValidationError=Q.PathNotFoundError=Q.ArtifactNotFoundError=Q.readPartialEnrichment=Q.withPartialEnrichment=Q.readPartialTokens=Q.withPartialTokens=Q.SdkError=void 0;var at=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};Q.SdkError=at;var Fv=Symbol.for("cds-maker-sdk.partialWriteTokens");function Dx(e,t){return typeof e=="object"&&e!==null&&(e[Fv]=t),e}Q.withPartialTokens=Dx;function _x(e){return Mv(e,Fv)}Q.readPartialTokens=_x;function Mv(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 Bv=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function Ix(e,t){return typeof e=="object"&&e!==null&&(e[Bv]=t),e}Q.withPartialEnrichment=Ix;function Tx(e){return Mv(e,Bv)}Q.readPartialEnrichment=Tx;var Vd=class extends at{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};Q.ArtifactNotFoundError=Vd;var Gd=class extends at{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};Q.PathNotFoundError=Gd;var zd=class extends at{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 vF=Object.create;var bu=Object.defineProperty;var bF=Object.getOwnPropertyDescriptor;var wF=Object.getOwnPropertyNames;var AF=Object.getPrototypeOf,CF=Object.prototype.hasOwnProperty;var L=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var b=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Ir=(e,t)=>{for(var r in t)bu(e,r,{get:t[r],enumerable:!0})},vu=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of wF(t))!CF.call(e,i)&&i!==r&&bu(e,i,{get:()=>t[i],enumerable:!(n=bF(t,i))||n.enumerable});return e},Ai=(e,t,r)=>(vu(e,t,"default"),r&&vu(r,t,"default")),ye=(e,t,r)=>(r=e!=null?vF(AF(e)):{},vu(t||!e||!e.__esModule?bu(r,"default",{value:e,enumerable:!0}):r,e)),hr=e=>vu(bu({},"__esModule",{value:!0}),e);var Ci=b(_=>{"use strict";Object.defineProperty(_,"__esModule",{value:!0});_.DateTimeBehavior=_.PrecisionSource=_.StringFormatName=_.SourceType=_.ImeMode=_.SolutionEntityTypeCodeExtToComponentTypeCode=_.SolutionComponentTypeCodeToEntityTypeCodeExt=_.SolutionComponentVirtualAttributeSubtype=_.EntityTypeCode=_.SolutionComponentTypeCodeExt=_.RootComponentBehavior=_.SolutionComponentTypeCode=_.EntityKeyIndexStatus=_.ViewStateCode=_.ViewStatusCode=_.RelationshipSecurityTypes=_.CascadeType=_.RelationshipTypeExt=_.RelationshipType=_.AppSubType=_.BusinessProcessType=_.WorkflowCategory=_.WorkflowScope=_.WorkflowTypeCode=_.StatusCodeEnabledDisabled=_.StateCodeEnabledDisabled=_.StatusCode=_.StateCode=_.OptionSetType=_.AttributeTypeCodeNum=_.AttributeFormatName=_.AttributeFormatCode=_.AttributeTypeName=_.AttributeTypeCode=_.PluginSourceType=_.AuthType=_.PluginIsolationMode=_.ComponentState=_.ChartType=_.ChartsType=_.ViewType=_.AttributeType=_.ActivationState=_.FormPresentation=_.FormType=_.TableTypeCode=_.TableTypes=_.ActivityTypeMask=_.PrincipalType=_.OwnershipTypes=void 0;_.QueryType=_.KnownCustomSolutionComponentEntitySetName=_.TeamTypeEnum=_.EnvironmentVariableDefinitionTypeEnum=_.ConnectorTypeEnum=_.RoleInheritance=_.DefaultRoleTemplates=_.DeleteDependencyErrorCode=_.ServiceEndpointConnectionMode=_.ServiceEndpointContract=_.ServiceNamespaceFormat=_.ConnectionRoleCategory=_.ReportTypeCode=_.SdkMessageProcessingMode=_.SupportedDeployment=_.SdkMessageProcessingStage=_.WebResourceTypeCode=_.IntegerFormat=_.DateTimeFormat=void 0;var sv;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(sv||(_.OwnershipTypes=sv={}));var lv;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(lv||(_.PrincipalType=lv={}));var uv;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(uv||(_.ActivityTypeMask=uv={}));var cv;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(cv||(_.TableTypes=cv={}));var dv;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(dv||(_.TableTypeCode=dv={}));var fv;(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(fv||(_.FormType=fv={}));var pv;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(pv||(_.FormPresentation=pv={}));var mv;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(mv||(_.ActivationState=mv={}));var hv;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(hv||(_.AttributeType=hv={}));var gv;(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"})(gv||(_.ViewType=gv={}));var yv;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(yv||(_.ChartsType=yv={}));var vv;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(vv||(_.ChartType=vv={}));var bv;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(bv||(_.ComponentState=bv={}));var wv;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(wv||(_.PluginIsolationMode=wv={}));var Av;(function(e){e[e.BasicAuth=0]="BasicAuth"})(Av||(_.AuthType=Av={}));var Cv;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(Cv||(_.PluginSourceType=Cv={}));var Ev;(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"})(Ev||(_.AttributeTypeCode=Ev={}));var Sv;(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"})(Sv||(_.AttributeTypeName=Sv={}));var Nv;(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"})(Nv||(_.AttributeFormatCode=Nv={}));var Dv;(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"})(Dv||(_.AttributeFormatName=Dv={}));var _v;(function(e){e[e.Boolean=0]="Boolean",e[e.Customer=1]="Customer",e[e.DateTime=2]="DateTime",e[e.Decimal=3]="Decimal",e[e.Double=4]="Double",e[e.Integer=5]="Integer",e[e.Lookup=6]="Lookup",e[e.Memo=7]="Memo",e[e.Money=8]="Money",e[e.Owner=9]="Owner",e[e.PartyList=10]="PartyList",e[e.Picklist=11]="Picklist",e[e.State=12]="State",e[e.Status=13]="Status",e[e.String=14]="String",e[e.Uniqueidentifier=15]="Uniqueidentifier",e[e.CalendarRules=16]="CalendarRules",e[e.Virtual=17]="Virtual",e[e.BigInt=18]="BigInt",e[e.ManagedProperty=19]="ManagedProperty",e[e.EntityName=20]="EntityName"})(_v||(_.AttributeTypeCodeNum=_v={}));var Iv;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(Iv||(_.OptionSetType=Iv={}));var Tv;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(Tv||(_.StateCode=Tv={}));var Pv;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(Pv||(_.StatusCode=Pv={}));var Ov;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(Ov||(_.StateCodeEnabledDisabled=Ov={}));var Rv;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(Rv||(_.StatusCodeEnabledDisabled=Rv={}));var kv;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(kv||(_.WorkflowTypeCode=kv={}));var xv;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(xv||(_.WorkflowScope=xv={}));var Lv;(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"})(Lv||(_.WorkflowCategory=Lv={}));var Fv;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(Fv||(_.BusinessProcessType=Fv={}));var Mv;(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"})(Mv||(_.AppSubType=Mv={}));var $v;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})($v||(_.RelationshipType=$v={}));var Bv;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Bv||(_.RelationshipTypeExt=Bv={}));var Uv;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(Uv||(_.CascadeType=Uv={}));var qv;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(qv||(_.RelationshipSecurityTypes=qv={}));var Vv;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(Vv||(_.ViewStatusCode=Vv={}));var Gv;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(Gv||(_.ViewStateCode=Gv={}));var Wv;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(Wv||(_.EntityKeyIndexStatus=Wv={}));var zv;(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"})(zv||(_.SolutionComponentTypeCode=zv={}));var jv;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(jv||(_.RootComponentBehavior=jv={}));var wu;(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"})(wu||(_.SolutionComponentTypeCodeExt=wu={}));var Au;(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"})(Au||(_.EntityTypeCode=Au={}));var Hv;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(Hv||(_.SolutionComponentVirtualAttributeSubtype=Hv={}));function EF(e){let t=wu[e];return Au[t]}_.SolutionComponentTypeCodeToEntityTypeCodeExt=EF;function SF(e){let t=Au[e];return wu[t]}_.SolutionEntityTypeCodeExtToComponentTypeCode=SF;var Kv;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(Kv||(_.ImeMode=Kv={}));var Jv;(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"})(Jv||(_.SourceType=Jv={}));var Qv;(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"})(Qv||(_.StringFormatName=Qv={}));var Yv;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(Yv||(_.PrecisionSource=Yv={}));var Xv;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(Xv||(_.DateTimeBehavior=Xv={}));var Zv;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(Zv||(_.DateTimeFormat=Zv={}));var eb;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(eb||(_.IntegerFormat=eb={}));var tb;(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"})(tb||(_.WebResourceTypeCode=tb={}));var rb;(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"})(rb||(_.SdkMessageProcessingStage=rb={}));var nb;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(nb||(_.SupportedDeployment=nb={}));var ib;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(ib||(_.SdkMessageProcessingMode=ib={}));var ob;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(ob||(_.ReportTypeCode=ob={}));var ab;(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"})(ab||(_.ConnectionRoleCategory=ab={}));var sb;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(sb||(_.ServiceNamespaceFormat=sb={}));var lb;(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"})(lb||(_.ServiceEndpointContract=lb={}));var ub;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(ub||(_.ServiceEndpointConnectionMode=ub={}));var cb;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(cb||(_.DeleteDependencyErrorCode=cb={}));var db;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(db||(_.DefaultRoleTemplates=db={}));var fb;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(fb||(_.RoleInheritance=fb={}));var pb;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(pb||(_.ConnectorTypeEnum=pb={}));var mb;(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"})(mb||(_.EnvironmentVariableDefinitionTypeEnum=mb={}));var hb;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(hb||(_.TeamTypeEnum=hb={}));var gb;(function(e){e.Bots="bots"})(gb||(_.KnownCustomSolutionComponentEntitySetName=gb={}));var yb;(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"})(yb||(_.QueryType=yb={}))});var X=b(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.IncompatibleWorkspaceError=Y.PathTraversalError=Y.AmbiguousArtifactError=Y.JsonPointerError=Y.NotImplementedError=Y.WorkspaceOrgMismatchError=Y.WorkspaceNotInitializedError=Y.attachCause=Y.ConnectionError=Y.VersionConflictError=Y.LocalEditsWouldBeLostError=Y.StaleArtifactError=Y.InvalidArgumentError=Y.ValidationError=Y.PathNotFoundError=Y.ArtifactNotFoundError=Y.readPartialEnrichment=Y.withPartialEnrichment=Y.readPartialTokens=Y.withPartialTokens=Y.SdkError=void 0;var it=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};Y.SdkError=it;var vb=Symbol.for("cds-maker-sdk.partialWriteTokens");function NF(e,t){return typeof e=="object"&&e!==null&&(e[vb]=t),e}Y.withPartialTokens=NF;function DF(e){return bb(e,vb)}Y.readPartialTokens=DF;function bb(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 wb=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function _F(e,t){return typeof e=="object"&&e!==null&&(e[wb]=t),e}Y.withPartialEnrichment=_F;function IF(e){return bb(e,wb)}Y.readPartialEnrichment=IF;var zf=class extends it{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};Y.ArtifactNotFoundError=zf;var jf=class extends it{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};Y.PathNotFoundError=jf;var Hf=class extends it{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"}};Q.ValidationError=zd;var Wd=class extends at{constructor(t){super("INVALID_ARGUMENT",t)}};Q.InvalidArgumentError=Wd;var jd=class extends at{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}};Q.StaleArtifactError=jd;var Hd=class extends at{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}};Q.LocalEditsWouldBeLostError=Hd;var Kd=class extends at{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}};Q.VersionConflictError=Kd;var Jd=class extends at{constructor(t,r,n,i){super("CONNECTION_ERROR",r>0?`HTTP ${r} from ${t}: ${n}`:`Transport failure reaching ${t}: ${n}`),this.url=t,this.statusCode=r,this.cause=i}};Q.ConnectionError=Jd;var Qd=class extends at{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};Q.WorkspaceNotInitializedError=Qd;var Xd=class extends at{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};Q.NotImplementedError=Xd;var Yd=class extends at{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};Q.JsonPointerError=Yd;var Zd=class extends at{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}};Q.AmbiguousArtifactError=Zd;var ep=class extends at{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}};Q.PathTraversalError=ep;var tp=class extends at{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}};Q.IncompatibleWorkspaceError=tp});var ae=b(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.odataQuery=Me.normalizeGuid=Me.createSafeXmlElement=Me.assertNoControlChars=Me.assertODataName=Me.assertXmlName=Me.xmlText=Me.odataPathLiteral=Me.odataLiteral=void 0;var Nl=re();function $v(e){return String(e??"").replace(/'/g,"''")}Me.odataLiteral=$v;function Px(e){return encodeURIComponent($v(e))}Me.odataPathLiteral=Px;function Rx(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}Me.xmlText=Rx;function Uv(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 Nl.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}Me.assertXmlName=Uv;function Ox(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new Nl.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}Me.assertODataName=Ox;function xx(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new Nl.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}Me.assertNoControlChars=xx;function Lx(e,t,r){return e.createElement(Uv(t,r))}Me.createSafeXmlElement=Lx;var kx=/^[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 Fx(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!kx.test(n))throw new Nl.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}Me.normalizeGuid=Fx;function Mx(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}Me.odataQuery=Mx});var be=b(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.nowIso=X.isAlreadyDeleted=X.deleteRecord=X.resendDeadlockVictim=X.DEADLOCK_BACKOFF_MS=X.isSqlDeadlockVictim=X.ensureSuccess=X.resolveCreatedId=X.requireCreatedId=X.withClientMintedId=X.readCreatedId=X.readRowEtag=X.readEtag=X.requireEtag=X.echoWrite=X.UPDATE_NO_ETAG_CODE=X.VERSION_CONFLICT_CODE=void 0;var go=re(),vo=ae();X.VERSION_CONFLICT_CODE="VERSION_CONFLICT";X.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function Bx(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}X.echoWrite=Bx;function $x(e,t,r){if(!e)throw new go.SdkError(X.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${r}': no concurrency token is held for it, so the write could not be made conditional and would silently overwrite a concurrent edit. Re-fetch the ${t} and re-apply the change.`);return e}X.requireEtag=$x;function qv(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}X.readEtag=qv;async function Ux(e,t,r,n){let i=`/${t}(${n})${(0,vo.odataQuery)([["$select",r]])}`;return qv(np(await e.get(i),e.apiUrl(i)))}X.readRowEtag=Ux;function rp(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,vo.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,vo.normalizeGuid)(a[1],t)}return null}X.readCreatedId=rp;function qx(e,t,r){return r?{...e,[t]:(0,vo.normalizeGuid)(r,t)}:e}X.withClientMintedId=qx;function Vx(e,t,r){let n=rp(e,t);if(!n)throw new go.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}X.requireCreatedId=Vx;function Gx(e,t,r,n){let i=rp(e,t);if(i)return i;if(n)return(0,vo.normalizeGuid)(n,t);throw new go.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}X.resolveCreatedId=Gx;function np(e,t){if(e.status===412)throw new go.SdkError(X.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new go.ConnectionError(t,e.status,Wx(e.body),e.body);return e}X.ensureSuccess=np;function Vv(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)}X.isSqlDeadlockVictim=Vv;X.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];async function zx(e){for(let t=0;;t+=1){let r=await e();if(t>=X.DEADLOCK_BACKOFF_MS.length||!Vv(r))return r;await new Promise(n=>setTimeout(n,X.DEADLOCK_BACKOFF_MS[t]))}}X.resendDeadlockVictim=zx;function Wx(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 jx(e,t,r,n){let i=(0,vo.normalizeGuid)(r,"id"),o=`/${t}(${i})`;np(await e.delete(o,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(o))}X.deleteRecord=jx;function Hx(e){return e instanceof go.ConnectionError&&e.statusCode===404}X.isAlreadyDeleted=Hx;function Kx(){return new Date().toISOString()}X.nowIso=Kx});var Rt=b(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.describeMalformedValue=yo.collectPages=void 0;var Gv=be(),ip=re();async function Jx(e,t,r,n,i){let o=[],a=new Set,s=e.apiUrl(t),l=(0,Gv.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new ip.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${op(c)}; refusing to return partial results.`);for(let p of c)o.push(p);let d=u?.["@odata.nextLink"];if(d==null)break;if(typeof d!="string"||d.length===0)throw new ip.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${op(d)}); cannot follow it, and refusing to return partial results.`);if(a.has(d))throw new ip.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);a.add(d),s=d,l=(0,Gv.ensureSuccess)(await e.getAbsolute(d,i),d)}return o}yo.collectPages=Jx;function op(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}yo.describeMalformedValue=op});var ap=b(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.businessRuleApi=Ur.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=Ur.WFOM_API_UNAVAILABLE_CODE=void 0;var vn=Ti(),Qx=Rt(),st=be(),Qn=ae(),_l=re();Ur.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";Ur.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function zv(e,t,r,n){let i=`/workflows(${Zx})/Microsoft.Dynamics.CRM.${t}`;try{return(0,st.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new _l.SdkError(Ur.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 Xx(e,t){let r=`/workflows(${t})${(0,Qn.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,st.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function Yx(e,t,r){let n=await Xx(e,t);if(n===null||n.etag===null)throw new _l.SdkError(st.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 _l.SdkError(st.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 Zx="00000000-0000-0000-0000-000000000000",Dl={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},eL="workflowid,name,description,primaryentity,statecode,category,type",tL="category eq 2 and type eq 1";async function Wv(e,t,r){var n;if(r==="Draft")return null;let i=(0,Qn.normalizeGuid)(t,"workflowid"),o=r==="Active",a={statecode:o?vn.StateCode.Activated:vn.StateCode.Draft,statuscode:o?vn.StatusCode.Activated:vn.StatusCode.Draft},s=`/workflows(${i})`,l=(0,st.ensureSuccess)(await e.patch(s,a,{headers:Dl}),e.apiUrl(s));return(n=(0,st.readEtag)(l))!==null&&n!==void 0?n:await ja(e,i)}async function ja(e,t){let r=`/workflows(${t})${(0,Qn.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,st.readEtag)(n):null}catch{return null}}async function rL(e,t,r){let n=await ja(e,t),i=await r(),o=(0,st.readEtag)(i);if(o)return{response:i,etag:o};let a=await ja(e,t);return{response:i,etag:n!==null&&n===a?a:null}}Ur.businessRuleApi={async get(e,t){let r=(0,Qn.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await rL(e,r,async()=>(0,st.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:o}},async list(e,t){let r=[tL];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,Qn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,Qn.odataQuery)([["$select",eL],["$filter",r.join(" and ")]])}`;return(await(0,Qx.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,Qn.normalizeGuid)(n.Entity.workflowid,"workflowid"),o=await zv(e,"CreateProcessWithWfomJson",n,Dl),a=(0,st.resolveCreatedId)(o,"workflowid","business rule",i),s=null;try{s=await Wv(e,a,n.status)}catch(l){try{await(0,st.deleteRecord)(e,"workflows",a)}catch{}throw l}return{id:a,etag:(r=s??(0,st.readEtag)(o))!==null&&r!==void 0?r:await ja(e,a)}},async update(e,t,r,n){var i,o;let a=r,s=(0,Qn.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...Dl,"If-Match":(0,st.requireEtag)(n,"business rule",s)},c=await Yx(e,s,u["If-Match"]),d=c.statecode===vn.StateCode.Activated;d&&(0,st.ensureSuccess)(await e.patch(l,{statecode:vn.StateCode.Draft,statuscode:vn.StatusCode.Draft},{headers:u}),e.apiUrl(l));let p;try{p=await zv(e,"UpdateProcessWithWfomJson",a,u)}catch(m){if(d)try{(0,st.ensureSuccess)(await e.patch(l,{statecode:vn.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:vn.StatusCode.Activated},{headers:Dl}),e.apiUrl(l))}catch(h){throw new _l.SdkError(Ur.BUSINESS_RULE_LEFT_DEACTIVATED_CODE,`The business-rule write failed AND the rule could not be re-activated, so '${s}' is left DEACTIVATED (Draft) on the server. Re-activate it before relying on it. Original write failure: ${m instanceof Error?m.message:String(m)}. Restore failure: ${h instanceof Error?h.message:String(h)}`)}throw m}let f=await Wv(e,s,a.status);return{id:s,etag:(o=f??(0,st.readEtag)(p))!==null&&o!==void 0?o:await ja(e,s)}},delete(e,t){return(0,st.deleteRecord)(e,"workflows",t)}}});var nr=b(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.publishBoundEntity=Qe.boundEntityPublishScope=Qe.publishGenPageById=Qe.publishDashboardById=Qe.publishWebResourceById=Qe.publishEntity=Qe.publishAppModule=Qe.publishXml=void 0;var jv=be(),Ha=ae(),Hv="/PublishXml";async function bo(e,t){(0,jv.ensureSuccess)(await(0,jv.resendDeadlockVictim)(()=>e.post(Hv,{ParameterXml:t})),e.apiUrl(Hv))}Qe.publishXml=bo;function nL(e,t){return bo(e,`<importexportxml><appmodules><appmodule>${(0,Ha.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}Qe.publishAppModule=nL;function Kv(e,t){return bo(e,`<importexportxml><entities><entity>${(0,Ha.xmlText)(t)}</entity></entities></importexportxml>`)}Qe.publishEntity=Kv;function iL(e,t){return bo(e,`<importexportxml><webresources><webresource>${(0,Ha.xmlText)(t)}</webresource></webresources></importexportxml>`)}Qe.publishWebResourceById=iL;function oL(e,t){return bo(e,`<importexportxml><dashboards><dashboard>${(0,Ha.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}Qe.publishDashboardById=oL;function aL(e,t){return bo(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,Ha.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}Qe.publishGenPageById=aL;function sL(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}Qe.boundEntityPublishScope=sL;function lL(e,t){let r=t?.entityLogicalName;return r?Kv(e,r):Promise.resolve()}Qe.publishBoundEntity=lL});var wo=b(Tl=>{"use strict";Object.defineProperty(Tl,"__esModule",{value:!0});Tl.JsonPointer=void 0;var Kt=re(),Il=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 Kt.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new Kt.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 Kt.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 Kt.JsonPointerError(r,`'${a}' is not a valid array index`);if(s>o.length)throw new Kt.JsonPointerError(r,`array index '${a}' is out of range`);o[s]=n}else{if(e.isReservedToken(a))throw new Kt.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 Kt.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 Kt.JsonPointerError(r,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new Kt.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 Kt.JsonPointerError(r,"add target must be an array");u.push(n);return}let a=e.resolve(t,r);if(!Array.isArray(a))throw new Kt.JsonPointerError(r,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new Kt.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 Kt.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)}};Tl.JsonPointer=Il;Il.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var Qv=b(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});Pl.findElements=void 0;var Jv=wo();function uL(e,t){let r=[];return sp(e,"",t,r),r}Pl.findElements=uL;function sp(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)=>{sp(i,Jv.JsonPointer.append(t,o),r,n)});else for(let i of Object.keys(e))sp(e[i],Jv.JsonPointer.append(t,i),r,n)}});var lp=b(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.assertMutationResult=qr.assertExistsResult=qr.assertReadResult=qr.assertStorageContract=void 0;var cL=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],dL=["ensureContainer","exists"];function pL(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of cL)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of dL){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}qr.assertStorageContract=pL;function fL(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.`)}qr.assertReadResult=fL;function mL(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.`)}qr.assertExistsResult=mL;function hL(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.`)}qr.assertMutationResult=hL});var up=b(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.retryTransientIoAsync=Ao.retryTransientIo=void 0;var gL=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),vL=5,Xv=10;function yL(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!Yv(r,t))throw r;wL(Xv*t)}}Ao.retryTransientIo=yL;async function bL(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!Yv(r,t))throw r;await new Promise(n=>setTimeout(n,Xv*t))}}Ao.retryTransientIoAsync=bL;function Yv(e,t){let r=e.code;return t<vL&&!!r&&gL.has(r)}function wL(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var ry=b(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.canonicalArtifactId=Jt.WorkspaceManager=Jt.WORKSPACE_SCHEMA_VERSION=Jt.retryTransientIo=void 0;var Cr=lp(),Rl=re(),AL=up();Object.defineProperty(Jt,"retryTransientIo",{enumerable:!0,get:function(){return AL.retryTransientIo}});function Zv(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Jt.WORKSPACE_SCHEMA_VERSION=1;var Xn={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},EL="manifest.json",Ka=".metadata",ey="entities";function ty(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}var cp=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(),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),[Xn[t],`${Ja(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[Ka,Xn[t],`${Ja(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[Ka,ey,`${t}.json`]}fsStore(){let t=Zv(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=Zv(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([Xn[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 Rl.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[EL]}async init(){if(this.storage.ensureContainer){let t=this.storage.ensureContainer.bind(this.storage),r=[[Ka,ey]];for(let i of Object.keys(Xn))r.push([Xn[i]],[Ka,Xn[i]]);let n=await Promise.allSettled(r.map(i=>ty(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,Cr.assertMutationResult)(i.value,"ensureContainer")}}await this.withManifest(async()=>{if(await this.isInitialized())return;let t={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};await this.writeManifest(t)})}async isInitialized(){return this.storage.exists?(0,Cr.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,Cr.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json")!==null}async ensureInitialized(){if(!await this.isInitialized())throw new Rl.WorkspaceNotInitializedError(this.workspaceLabel)}async clean(){let t=Object.keys(Xn).map(i=>[Xn[i]]);t.push([Ka]);let r=await Promise.allSettled(t.map(i=>ty(()=>this.storage.deleteByPrefix(i))));for(let i of r){if(i.status==="rejected")throw i.reason;(0,Cr.assertMutationResult)(i.value,"deleteByPrefix")}let n=await this.getManifest();n.artifacts=[],n.lastSyncAt=void 0,await this.init(),await this.writeManifest(n)}async readArtifact(t,r){return await this.ensureInitialized(),this.readJson(this.artifactKey(t,r))}async writeArtifact(t,r,n){await this.ensureInitialized(),await this.writeJson(this.artifactKey(t,r),n),await this.upsertManifestEntry(t,r,n)}async deleteArtifact(t,r){await this.ensureInitialized(),(0,Cr.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,Cr.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=Ja(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 this.readJson(this.metaKey(t,r))}async writeMeta(t,r,n){await this.writeJson(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.readJson(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.writeJson(this.entityKey(t),r)}async getManifest(){await this.ensureInitialized();let t=await this.readJson(this.manifestKey);if(!t)throw new Rl.WorkspaceNotInitializedError(this.workspaceLabel);if(t.schemaVersion!==void 0&&t.schemaVersion>Jt.WORKSPACE_SCHEMA_VERSION)throw new Rl.IncompatibleWorkspaceError(t.schemaVersion,Jt.WORKSPACE_SCHEMA_VERSION);return t}async writeManifest(t){await this.writeJson(this.manifestKey,{...t,schemaVersion:Jt.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();await this.writeManifest({...r,...t})})}async upsertManifestEntry(t,r,n){await this.withManifest(async()=>{let i=await this.getManifest(),o=Ja(r),a=n,s=typeof a.name=="string"?a.name:`${t}:${o}`,l=typeof a.entityLogicalName=="string"?a.entityLogicalName:void 0,u=i.artifacts.find(c=>c.type===t&&c.id===o);u?(u.name=s,u.entityLogicalName=l):i.artifacts.push({type:t,id:o,name:s,entityLogicalName:l,isDirty:!1}),await this.writeManifest(i)})}async readJson(t){let r=(0,Cr.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJson(t,r){(0,Cr.assertMutationResult)(await this.storage.writeTextAtomic(t,`${JSON.stringify(r,null,2)}
-`),"writeTextAtomic")}async removeFile(t){(0,Cr.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return this.storage.exists?(0,Cr.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,Cr.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}};Jt.WorkspaceManager=cp;function Ja(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()}Jt.canonicalArtifactId=Ja});var dp=b(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.deepEqual=Eo.deepDiff=void 0;var CL=wo();function SL(e,t){let r=[];return iy(e,t,"",r,0),r}Eo.deepDiff=SL;var Ol=Symbol("missing"),xl=512;function iy(e,t,r,n,i){if(e===t)return;if(i>xl)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${xl}`);let o=Ll(e),a=Ll(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=NL(e,t);for(let l of s){let u=ny(e,l),c=ny(t,l),d=CL.JsonPointer.append(r,l);u===Ol?n.push({pointer:d,type:"added",newValue:c}):c===Ol?n.push({pointer:d,type:"removed",oldValue:u}):iy(u,c,d,n,i+1)}return}oy(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function Ll(e){return e!==null&&typeof e=="object"}function NL(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 ny(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:Ol}return t in e?e[t]:Ol}function oy(e,t){return ay(e,t,0)}Eo.deepEqual=oy;function ay(e,t,r){if(e===t)return!0;if(r>xl)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${xl}`);if(!Ll(e)||!Ll(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&&ay(e[o],t[o],r+1))}});var ly=b(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.VersionManager=Co.PROJECTION_VERSION=void 0;var sy=dp();Co.PROJECTION_VERSION=5;var pp=class{constructor(t){this.workspace=t}async storeMeta(t,r,n){var i;let o=await this.getMeta(t,r),a=((i=n.snapshot)===null||i===void 0?void 0:i.status)==="Active",s=o?.everActivated===!0||a;await this.workspace.writeMeta(t,r,s?{...n,everActivated:s}:n)}async getMeta(t,r){return this.workspace.readMeta(t,r)}async isDirty(t,r){let n=await this.workspace.readArtifact(t,r);if(n===null)return!1;let i=await this.getMeta(t,r);return i?!(0,sy.deepEqual)(i.snapshot,n):!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,sy.deepDiff)(i.snapshot,n):o=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:o}}async checkConflict(t,r,n){let i=await this.getMeta(t,r);return!i||i.etag===null?!1:i.etag!==n}};Co.VersionManager=pp});var cy=b((fp,uy)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof fp=="object"?uy.exports=t():e.compareVersions=t()})(fp,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),p=parseInt(u[c]||0,10);if(d>p)return 1;if(p>d)return-1}var f=l[l.length-1],m=u[u.length-1];if(f&&m){var h=f.split(".").map(n),g=m.split(".").map(n);for(c=0;c<Math.max(h.length,g.length);c++){if(h[c]===void 0||typeof g[c]=="string"&&typeof h[c]=="number")return-1;if(g[c]===void 0||typeof h[c]=="string"&&typeof g[c]=="number"||h[c]>g[c])return 1;if(g[c]>h[c])return-1}}else if(f||m)return f?-1:1;return 0}})});var hy=b(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.EnvironmentFlowHostingType=Re.EnvironmentDisableReasonCode=Re.EnvironmentMigrationConstants=Re.EnvironmentProvisioningStates=Re.EnvironmentLocations=Re.EnvironmentCreationTypeConstants=Re.EnvironmentType=Re.EnvironmentSkuConstants=Re.environmentPermissions=Re.DatabaseType=void 0;var dy;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(dy||(Re.DatabaseType=dy={}));Re.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"};Re.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var py;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(py||(Re.EnvironmentType=py={}));Re.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Re.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"};Re.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Re.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var fy;(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"})(fy||(Re.EnvironmentDisableReasonCode=fy={}));var my;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(my||(Re.EnvironmentFlowHostingType=my={}))});var Cy=b(N=>{"use strict";var DL=N&&N.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(N,"__esModule",{value:!0});N.hasCommonDataServiceDatabase=N.getEnvironmentDiscoveryUrl=N.getEnvironmentWebApiUrl=N.getEnvironmentInstanceApiUrl=N.getEnvironmentLanguageCode=N.getEnvironmentUpdateCadence=N.checkVersions=N.isCds2EnvironmentVersionAtLeast=N.getSecurityOrConnectedGroupId=N.hasSecurityGroupId=N.doesCds2VersionSupportApiVersion9_1=N.doesCds2EnvironmentSupportApiVersion9_1=N.cdsVersionSupportingOSColorEdit=N.getEnvironmentDisplayName=N.getEnvironmentName=N.isEnvironmentInFirstReleaseCluster=N.isEnvironmentInPreprodCluster=N.isEnvironmentInTestCluster=N.isLiteEnvironmentUpgrading=N.isEnvironmentExpired=N.isEnvironmentInDeletedState=N.isEnvironmentInCreatingState=N.isDatabaseInProvisioningState=N.canUserCreateDatabase=N.isDisabledEnvironment=N.isDefaultEnvironment=N.isTrialEnvironment=N.isPlatformEnvironment=N.isTeamsEnvironment=N.isSandboxEnvironment=N.isProdEnvironment=N.isDevEnvironment=N.getEnvironmentType=N.getCrmInstanceName=N.getCrmInstanceUrl=N.getCrmAppDesignerUrl=N.getDevResourcesUrl=N.isEnvironmentInSuccessfulState=N.getAllThemesUrl=N.getAllPublishersUrl=N.getAllSolutionsUrl=N.getSecurityRolesUrl=N.getSecurityUsersUrl=N.environmentHasCds2Database=N.DEFAULT_SOLUTION_UNIQUE_NAME=N.DEFAULT_SOLUTION_ID=N.crmBapSolutionId=N.doesUserHavePermission=N.getLinkedEnvironmentMetadata=N.getCrmVersion=void 0;N.doesUserHaveFlowRunOnlyPermission=N.isUserPautoMakerWithoutDataAccess=N.isUserPautoMakerWithDataAccess=N.doesUserHaveCreateFlowPermission=N.equalsIgnoreCase=N.doesUserHaveCreateDatabasePermission=N.doesUserHaveDatabaseTablePermissions=N.isUserMakerWithoutDataAccess=N.isUserMakerWithDataAccess=N.doesUserHaveCreateAppPermission=N.doesUserHaveAdminPermission=void 0;var _L=DL(cy()),ge=hy(),Qa=hp();function IL(e){let t=bn(e);return t&&t.version}N.getCrmVersion=IL;function bn(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}N.getLinkedEnvironmentMetadata=bn;function yn(e,t){return e?!!e[t]:!1}N.doesUserHavePermission=yn;N.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";N.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";N.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function Pi(e){return!!bn(e)&&gy(e)}N.environmentHasCds2Database=Pi;function TL(e){if(e&&Pi(e)){let t=Yn(e);return(0,Qa.getCrmAdminSecurityRolesUrl)(t)}return""}N.getSecurityUsersUrl=TL;function PL(e){if(e&&Pi(e)){let t=Yn(e);return(0,Qa.getCrmAdminSecurityUsersUrl)(t)}return""}N.getSecurityRolesUrl=PL;function RL(e){if(e&&Pi(e)){let t=Yn(e);(0,Qa.getCrmAllSolutionsUrl)(t)}return""}N.getAllSolutionsUrl=RL;function OL(e){if(e&&Pi(e)){let t=Yn(e);return(0,Qa.getCrmAllPublishersUrl)(t)}return""}N.getAllPublishersUrl=OL;function xL(e){return e&&Pi(e)?Yn(e):""}N.getAllThemesUrl=xL;function gy(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===ge.EnvironmentProvisioningStates.Succeeded.toUpperCase()}N.isEnvironmentInSuccessfulState=gy;function LL(e){if(e&&Pi(e)){let t=Yn(e);return(0,Qa.getCrmDevResourcesUrl)(t)}return""}N.getDevResourcesUrl=LL;function kL(e){return`${e}designer/app/{${N.crmBapSolutionId}}/CreateNewApp}}`}N.getCrmAppDesignerUrl=kL;function Yn(e){let t=bn(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}N.getCrmInstanceUrl=Yn;function FL(e){let t=bn(e);return t?t.uniqueName:""}N.getCrmInstanceName=FL;function ML(e){return bn(e)?ge.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?ge.EnvironmentType.CDS1:ge.EnvironmentType.Empty}N.getEnvironmentType=ML;function BL(e){return e&&e.properties&&e.properties.environmentSku===ge.EnvironmentSkuConstants.Developer}N.isDevEnvironment=BL;function $L(e){return e&&e.properties&&e.properties.environmentSku===ge.EnvironmentSkuConstants.Production}N.isProdEnvironment=$L;function UL(e){return e&&e.properties&&e.properties.environmentSku===ge.EnvironmentSkuConstants.Sandbox}N.isSandboxEnvironment=UL;function Xa(e){return e&&e.properties&&e.properties.environmentSku===ge.EnvironmentSkuConstants.Teams}N.isTeamsEnvironment=Xa;function qL(e){return e&&e.properties&&e.properties.environmentSku===ge.EnvironmentSkuConstants.Platform}N.isPlatformEnvironment=qL;var VL=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===ge.EnvironmentSkuConstants.Trial};N.isTrialEnvironment=VL;function GL(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===ge.EnvironmentCreationTypeConstants.DefaultTenant)}N.isDefaultEnvironment=GL;function zL(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}N.isDisabledEnvironment=zL;function WL(e){return e&&e.properties&&yn(e.properties.permissions,ge.environmentPermissions.CreateDatabase)}N.canUserCreateDatabase=WL;function jL(e){return!!(e&&e.properties&&e.properties.provisioningState&&Ey(e.properties.provisioningState,ge.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}N.isDatabaseInProvisioningState=jL;function HL(e){return!!e&&!!e.properties&&e.properties.provisioningState===ge.EnvironmentProvisioningStates.Creating}N.isEnvironmentInCreatingState=HL;function KL(e){return e&&e.properties&&(e.properties.provisioningState===ge.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===ge.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===ge.EnvironmentProvisioningStates.FailedDeleting)}N.isEnvironmentInDeletedState=KL;function JL(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}N.isEnvironmentExpired=JL;function QL(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"}N.isLiteEnvironmentUpgrading=QL;function XL(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}N.isEnvironmentInTestCluster=XL;function YL(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}N.isEnvironmentInPreprodCluster=YL;function ZL(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}N.isEnvironmentInFirstReleaseCluster=ZL;function ek(e){return e&&e.name||""}N.getEnvironmentName=ek;function tk(e){return e&&e.properties&&e.properties.displayName||""}N.getEnvironmentDisplayName=tk;var vy="9.1.0.8202";N.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function rk(e){return wy(e,vy)}N.doesCds2EnvironmentSupportApiVersion9_1=rk;function nk(e){return mp(e,vy)}N.doesCds2VersionSupportApiVersion9_1=nk;function yy(e){let t=bn(e);if(t)return t.securityGroupId}function by(e){return e&&e.properties&&e.properties.connectedGroups}function ik(e,t){let r=by(e);return!!r&&!!r.find(n=>n.id===t)||yy(e)===t}N.hasSecurityGroupId=ik;function ok(e){let t=by(e);return t&&t.length>0&&t[0].id?t[0].id:yy(e)}N.getSecurityOrConnectedGroupId=ok;function wy(e,t){let r=e.version;return r?mp(r,t):!1}N.isCds2EnvironmentVersionAtLeast=wy;function mp(e,t){return t?e?(0,_L.default)(e,t)>=0:!1:!0}N.checkVersions=mp;function ak(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}N.getEnvironmentUpdateCadence=ak;function sk(e){let t=bn(e);return t?Number(t.baseLanguage):0}N.getEnvironmentLanguageCode=sk;function Ay(e){let t=bn(e);return t?t.instanceApiUrl:void 0}N.getEnvironmentInstanceApiUrl=Ay;function lk(e){let t=Ay(e);return t?t+"/api/data/v9.2":""}N.getEnvironmentWebApiUrl=lk;function uk(e){let t=Yn(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"}N.getEnvironmentDiscoveryUrl=uk;var ck=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===ge.DatabaseType.CommonDataService};N.hasCommonDataServiceDatabase=ck;var dk=e=>{var t;return yn((t=e.properties)===null||t===void 0?void 0:t.permissions,ge.environmentPermissions.AdminReadEnvironment)};N.doesUserHaveAdminPermission=dk;var pk=e=>{var t;return yn((t=e.properties)===null||t===void 0?void 0:t.permissions,ge.environmentPermissions.CreatePowerApp)};N.doesUserHaveCreateAppPermission=pk;var fk=e=>(0,N.doesUserHaveAdminPermission)(e)&&(0,N.hasCommonDataServiceDatabase)(e)?!0:(0,N.doesUserHaveCreateAppPermission)(e)?Xa(e)||(0,N.doesUserHaveDatabaseTablePermissions)(e):!1;N.isUserMakerWithDataAccess=fk;var mk=e=>(0,N.doesUserHaveCreateAppPermission)(e)&&!Xa(e)&&!(0,N.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,N.doesUserHaveAdminPermission)(e)||!(0,N.hasCommonDataServiceDatabase)(e));N.isUserMakerWithoutDataAccess=mk;var hk=e=>[ge.environmentPermissions.CreateDatabaseEntities,ge.environmentPermissions.ListDatabaseEntities,ge.environmentPermissions.UpdateDatabaseEntities,ge.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return yn((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});N.doesUserHaveDatabaseTablePermissions=hk;var gk=e=>{var t;return yn((t=e.properties)===null||t===void 0?void 0:t.permissions,ge.environmentPermissions.CreateDatabase)};N.doesUserHaveCreateDatabasePermission=gk;function Ey(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}N.equalsIgnoreCase=Ey;var vk=e=>{var t;return yn((t=e.properties)===null||t===void 0?void 0:t.permissions,ge.environmentPermissions.CreateFlow)};N.doesUserHaveCreateFlowPermission=vk;var yk=e=>(0,N.doesUserHaveAdminPermission)(e)&&(0,N.hasCommonDataServiceDatabase)(e)?!0:(0,N.doesUserHaveCreateFlowPermission)(e)?Xa(e)||(0,N.doesUserHaveDatabaseTablePermissions)(e):!1;N.isUserPautoMakerWithDataAccess=yk;var bk=e=>(0,N.doesUserHaveCreateFlowPermission)(e)&&!Xa(e)&&!(0,N.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,N.doesUserHaveAdminPermission)(e)||!(0,N.hasCommonDataServiceDatabase)(e));N.isUserPautoMakerWithoutDataAccess=bk;var wk=e=>{var t,r;return!yn((t=e.properties)===null||t===void 0?void 0:t.permissions,ge.environmentPermissions.CreateFlow)&&yn((r=e.properties)===null||r===void 0?void 0:r.permissions,ge.environmentPermissions.ReadEnvironment)};N.doesUserHaveFlowRunOnlyPermission=wk});var hp=b(E=>{"use strict";Object.defineProperty(E,"__esModule",{value:!0});E.getRequiredComponentsQueryUrl=E.solutionComponentCountSummariesQueryUrl=E.solutionComponentSummariesQueryUrl=E.solutionComponentConfigurationsQueryUrl=E.chartsQueryUrl=E.workflowsQueryUrl=E.entityDefinitionsQueryUrl=E.solutionComponentDefinitionsQueryUrl=E.getCreateNewArticleTemplateUrl=E.getCreateNewPublisherUrl=E.getEnableSecurityRolesUrl=E.getArticleTemplateUrl=E.getFieldSecurityProfileDesignerUrl=E.getSecurityRoleDesignerUrl=E.getMailMergeTemplateDesignerUrl=E.getEmailTemplateDesignerUrl=E.getConnectionRoleDesignerUrl=E.getSiteMapDesignerUrl=E.getWebResourceFileUrl=E.getWebResourceDesignerUrl=E.getReportDesignerUrl=E.getBusinessProcessFlowDesignerUrl=E.getProcessShareUrl=E.getProcessDesignerUrl=E.getChartDesignerUrl=E.getOpenModernEntityDashboardUrl=E.getNewModernEntityDashboardUrl=E.getNewModernDashboardUrl=E.getOpenModernDashboardUrl=E.getDashboardDesignerUrl=E.getAppModuleDesignerUrl=E.privilegesQueryUrls=E.xrmApiUrl=E.getPlayAppModuleUrl=E.getCrmAdminSecurityUsersUrl=E.getCrmAdminSecurityRolesUrl=E.getCrmMyAppsUrl=E.getCrmAppDesignerUrl=E.getCrmDevResourcesUrl=E.getCrmAllPublishersUrl=E.getCrmAllSolutionsUrl=E.getSolutionPublisherUrl=E.getExportTranslationFileName=E.getExportSolutionTranslationUrl=E.getImportSolutionTranslationUrl=E.getShowSolutionDependenciesUrl=E.getShowComponentDependenciesUrl=E.cdsServiceUrl=E.ODATA_NEXT_LINK=E.ODATA_MAX_PAGE_SIZE=void 0;E.retrieveOrganizationResources=E.getUCIEntityRecordEditUrl=E.getUCIEntityRecordBaseUrl=E.getBusinessRuleDesignerUri=E.retrieveUnpublishedSuffix=E.getSavePowerSettingUri=E.getPowerSettingUri=E.getPowerSettingsUri=E.RetrievePlatform=E.getAppSettingOverrideUri=E.AppSettingOverrideName=E.getOrgSettingOverrideUri=E.OrgSettingOverrideName=E.getSettingDefinitionsUri=E.retrieveFeatureControlSettingsByNamespaceUrl=E.retrieveDeploymentPipelineConfigAppUrl=E.SPNPrincipalIdUrl=E.retrieveDeploymentEnvironmentInfoUrl=E.devSolutionInfoUrl=E.deployOperationStatusUrl=E.getAIGeneratedDeploymentNotesUrl=E.deploymentStageRunUrl=E.validatePackageAsyncUrl=E.deployPackageAsyncUrl=E.updateDeploymentStageRunUrl=E.createDeploymentStageRunUrl=E.retrieveDeploymentStagesUrl=E.retrievePipelinesUrl=E.retrieveDeploymentPipelineInfoUrl=E.getDeploymentStageRunsUrl=E.appDeploymentUrls=E.getProvisionLanguageUrl=E.getSolutionQueryUrl=E.getSolutionsByUniqueNameQueryUrl=E.solutionsQueryUrl=E.getDependentComponentsWithMetadataQueryUrl=void 0;var Sy=Cy();E.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";E.ODATA_NEXT_LINK="@odata.nextLink";E.cdsServiceUrl="https://cds-org/";var Za;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Za||(Za={}));function Ak(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}E.getShowComponentDependenciesUrl=Ak;function Ek(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}E.getShowSolutionDependenciesUrl=Ek;function Ck(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}E.getImportSolutionTranslationUrl=Ck;function Sk(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}E.getExportSolutionTranslationUrl=Sk;function Nk(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}E.getExportTranslationFileName=Nk;function Dk(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`}E.getSolutionPublisherUrl=Dk;function gp(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function _k(e){return gp(e,Za.AllSolutions)}E.getCrmAllSolutionsUrl=_k;function Ik(e){return gp(e,Za.AllPublishers)}E.getCrmAllPublishersUrl=Ik;function Tk(e){return gp(e,Za.DevResources)}E.getCrmDevResourcesUrl=Tk;function Pk(e,t=Sy.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}E.getCrmAppDesignerUrl=Pk;function Rk(e){return`${e}apps`}E.getCrmMyAppsUrl=Rk;function Ok(e){return Ny(e,"role")+"&forceUCI=0"}E.getCrmAdminSecurityRolesUrl=Ok;function xk(e){return`${Ny(e,"systemuser")}&forceclassic=1`}E.getCrmAdminSecurityUsersUrl=xk;function Ny(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function Lk(e,t){return`${e}main.aspx?appid=${t}`}E.getPlayAppModuleUrl=Lk;E.xrmApiUrl="api/data/v9.0";E.privilegesQueryUrls={systemUserInfo:e=>`${e}${E.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${E.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${E.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function kk(e,t,r=Sy.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}E.getAppModuleDesignerUrl=kk;function Fk(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}E.getDashboardDesignerUrl=Fk;function Mk(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}E.getOpenModernDashboardUrl=Mk;function Bk(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}E.getNewModernDashboardUrl=Bk;function $k(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}E.getNewModernEntityDashboardUrl=$k;function Uk(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}E.getOpenModernEntityDashboardUrl=Uk;function qk(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}E.getChartDesignerUrl=qk;function Vk(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}E.getProcessDesignerUrl=Vk;function Gk(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}E.getProcessShareUrl=Gk;function zk(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}E.getBusinessProcessFlowDesignerUrl=zk;function Wk(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}E.getReportDesignerUrl=Wk;function jk(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`}E.getWebResourceDesignerUrl=jk;function Hk(e,t){return`${e}WebResources/${t}`}E.getWebResourceFileUrl=Hk;function Kk(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}E.getSiteMapDesignerUrl=Kk;function Jk(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}E.getConnectionRoleDesignerUrl=Jk;function Qk(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}E.getEmailTemplateDesignerUrl=Qk;function Xk(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}E.getMailMergeTemplateDesignerUrl=Xk;function Yk(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}E.getSecurityRoleDesignerUrl=Yk;function Zk(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}E.getFieldSecurityProfileDesignerUrl=Zk;function eF(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}E.getArticleTemplateUrl=eF;function tF(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}`}E.getEnableSecurityRolesUrl=tF;function rF(e){return`${e}tools/publisher/edit.aspx`}E.getCreateNewPublisherUrl=rF;function nF(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}E.getCreateNewArticleTemplateUrl=nF;E.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";E.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";E.workflowsQueryUrl="api/data/v9.0/workflows";E.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";E.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";E.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";E.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function iF(e,t){return`${E.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}E.getRequiredComponentsQueryUrl=iF;function oF(e,t){return`${E.cdsServiceUrl}${E.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}E.getDependentComponentsWithMetadataQueryUrl=oF;E.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function aF(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}E.getSolutionsByUniqueNameQueryUrl=aF;function sF(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}E.getSolutionQueryUrl=sF;function lF(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}E.getProvisionLanguageUrl=lF;E.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 uF(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"}};Y.ValidationError=Hf;var Kf=class extends it{constructor(t){super("INVALID_ARGUMENT",t)}};Y.InvalidArgumentError=Kf;var Jf=class extends it{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}};Y.StaleArtifactError=Jf;var Qf=class extends it{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}};Y.LocalEditsWouldBeLostError=Qf;var Yf=class extends it{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}};Y.VersionConflictError=Yf;var Xf=class extends it{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})}};Y.ConnectionError=Xf;function TF(e,t){return typeof e=="object"&&e!==null&&Object.defineProperty(e,"cause",{value:t,enumerable:!1,writable:!0,configurable:!0}),e}Y.attachCause=TF;var Zf=class extends it{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};Y.WorkspaceNotInitializedError=Zf;var ep=class extends it{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}};Y.WorkspaceOrgMismatchError=ep;var tp=class extends it{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};Y.NotImplementedError=tp;var rp=class extends it{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};Y.JsonPointerError=rp;var np=class extends it{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}};Y.AmbiguousArtifactError=np;var ip=class extends it{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}};Y.PathTraversalError=ip;var op=class extends it{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}};Y.IncompatibleWorkspaceError=op});var ae=b(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.odataQuery=We.normalizeGuid=We.createSafeXmlElement=We.assertNoControlChars=We.assertODataName=We.assertXmlName=We.xmlText=We.odataPathLiteral=We.odataLiteral=void 0;var Cu=X();function Ab(e){return String(e??"").replace(/'/g,"''")}We.odataLiteral=Ab;function PF(e){return encodeURIComponent(Ab(e))}We.odataPathLiteral=PF;function OF(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}We.xmlText=OF;function Cb(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 Cu.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}We.assertXmlName=Cb;function RF(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new Cu.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}We.assertODataName=RF;function kF(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new Cu.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}We.assertNoControlChars=kF;function xF(e,t,r){return e.createElement(Cb(t,r))}We.createSafeXmlElement=xF;var LF=/^[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 FF(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!LF.test(n))throw new Cu.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}We.normalizeGuid=FF;function MF(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}We.odataQuery=MF});var we=b(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.nowIso=K.isAlreadyDeleted=K.deleteRecord=K.resendAppSearchIndexRace=K.resendDeadlockVictim=K.resendWhile=K.isAppSearchIndexRace=K.namesAppSearchIndexRace=K.DEADLOCK_BACKOFF_MS=K.isSqlDeadlockVictim=K.ensureSuccess=K.resolveCreatedId=K.requireCreatedId=K.withClientMintedId=K.readCreatedId=K.readRowEtag=K.readEtag=K.requireEtag=K.isVersionToken=K.echoWrite=K.UPDATE_NO_ETAG_CODE=K.VERSION_CONFLICT_CODE=void 0;var Xo=X(),Zo=ae();K.VERSION_CONFLICT_CODE="VERSION_CONFLICT";K.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function $F(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}K.echoWrite=$F;function Eb(e){return typeof e=="string"&&e.trim()!==""&&e.trim()!=="*"}K.isVersionToken=Eb;function BF(e,t,r){if(!Eb(e))throw new Xo.SdkError(K.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}K.requireEtag=BF;function Sb(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}K.readEtag=Sb;async function UF(e,t,r,n){let i=`/${t}(${n})${(0,Zo.odataQuery)([["$select",r]])}`;return Sb(sp(await e.get(i),e.apiUrl(i)))}K.readRowEtag=UF;function ap(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,Zo.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,Zo.normalizeGuid)(a[1],t)}return null}K.readCreatedId=ap;function qF(e,t,r){return r?{...e,[t]:(0,Zo.normalizeGuid)(r,t)}:e}K.withClientMintedId=qF;function VF(e,t,r){let n=ap(e,t);if(!n)throw new Xo.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}K.requireCreatedId=VF;function GF(e,t,r,n){let i=ap(e,t);if(i)return i;if(n)return(0,Zo.normalizeGuid)(n,t);throw new Xo.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}K.resolveCreatedId=GF;function sp(e,t){if(e.status===412)throw new Xo.SdkError(K.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new Xo.ConnectionError(t,e.status,HF(e.body),e.body);return e}K.ensureSuccess=sp;function Nb(e){if(e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/\bSql Number:\s*1205\b/i.test(t)}K.isSqlDeadlockVictim=Nb;K.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];var WF=/(?:^|[^a-z0-9_])AppModule_DVTableSearch_M365AppModuleId(?![a-z0-9_])/i;function Db(e){return WF.test(e)&&/\bSql Number:\s*547\b/i.test(e)}K.namesAppSearchIndexRace=Db;function _b(e){return e.status!==400||e.body===void 0||e.body===null?!1:Db(typeof e.body=="string"?e.body:JSON.stringify(e.body))}K.isAppSearchIndexRace=_b;async function lp(e,t,r=K.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]))}}K.resendWhile=lp;function zF(e){return lp(Nb,e,K.DEADLOCK_BACKOFF_MS)}K.resendDeadlockVictim=zF;function jF(e){return lp(_b,e,K.DEADLOCK_BACKOFF_MS)}K.resendAppSearchIndexRace=jF;function HF(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 KF(e,t,r,n){let i=(0,Zo.normalizeGuid)(r,"id"),o=`/${t}(${i})`;sp(await e.delete(o,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(o))}K.deleteRecord=KF;function JF(e){return e instanceof Xo.ConnectionError&&e.statusCode===404}K.isAlreadyDeleted=JF;function QF(){return new Date().toISOString()}K.nowIso=QF});var Mt=b(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});ea.describeMalformedValue=ea.collectPages=void 0;var Ib=we(),up=X();async function YF(e,t,r,n,i){let o=[],a=new Set,s=e.apiUrl(t),l=(0,Ib.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new up.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${cp(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 up.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${cp(d)}); cannot follow it, and refusing to return partial results.`);if(a.has(d))throw new up.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);a.add(d),s=d,l=(0,Ib.ensureSuccess)(await e.getAbsolute(d,i),d)}return o}ea.collectPages=YF;function cp(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}ea.describeMalformedValue=cp});var dp=b(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.assertWorkflowKind=no.WORKFLOW_KIND_MISMATCH_CODE=void 0;var ro=Ci(),XF=X(),ZF=we(),eM=ae();no.WORKFLOW_KIND_MISMATCH_CODE="WORKFLOW_KIND_MISMATCH";var Tb={[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 tM(e,t,r){var n,i;let o=`/workflows(${t})${(0,eM.odataQuery)([["$select","category"]])}`,a=await e.get(o);if(a.status===404)return;(0,ZF.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=Tb[l])!==null&&i!==void 0?i:"process"} (category ${l})`:"a process whose category could not be read";throw new XF.SdkError(no.WORKFLOW_KIND_MISMATCH_CODE,`Refusing to delete workflow '${t}' as a ${Tb[r]}: it is ${u}. Nothing was changed. Check the id.`)}}no.assertWorkflowKind=tM});var fp=b(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.businessRuleApi=dn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=dn.WFOM_API_UNAVAILABLE_CODE=void 0;var cn=Ci(),rM=Mt(),nM=dp(),bt=we(),qn=ae(),Su=X();dn.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";dn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function Pb(e,t,r,n){let i=`/workflows(${aM})/Microsoft.Dynamics.CRM.${t}`;try{return(0,bt.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new Su.SdkError(dn.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 iM(e,t){let r=`/workflows(${t})${(0,qn.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,bt.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function oM(e,t,r){let n=await iM(e,t);if(n===null||n.etag===null)throw new Su.SdkError(bt.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 Su.SdkError(bt.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 aM="00000000-0000-0000-0000-000000000000",Eu={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},sM="workflowid,name,description,primaryentity,statecode,category,type",lM="category eq 2 and type eq 1";async function Ob(e,t,r){var n;if(r==="Draft")return null;let i=(0,qn.normalizeGuid)(t,"workflowid"),o=r==="Active",a={statecode:o?cn.StateCode.Activated:cn.StateCode.Draft,statuscode:o?cn.StatusCode.Activated:cn.StatusCode.Draft},s=`/workflows(${i})`,l=(0,bt.ensureSuccess)(await e.patch(s,a,{headers:Eu}),e.apiUrl(s));return(n=(0,bt.readEtag)(l))!==null&&n!==void 0?n:await Is(e,i)}async function Is(e,t){let r=`/workflows(${t})${(0,qn.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,bt.readEtag)(n):null}catch{return null}}async function uM(e,t,r){let n=await Is(e,t),i=await r(),o=(0,bt.readEtag)(i);if(o)return{response:i,etag:o};let a=await Is(e,t);return{response:i,etag:n!==null&&n===a?a:null}}dn.businessRuleApi={async get(e,t){let r=(0,qn.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await uM(e,r,async()=>(0,bt.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:o}},async list(e,t){let r=[lM];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,qn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,qn.odataQuery)([["$select",sM],["$filter",r.join(" and ")]])}`;return(await(0,rM.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,qn.normalizeGuid)(n.Entity.workflowid,"workflowid"),o=await Pb(e,"CreateProcessWithWfomJson",n,Eu),a=(0,bt.resolveCreatedId)(o,"workflowid","business rule",i),s=null;try{s=await Ob(e,a,n.status)}catch(l){try{await(0,bt.deleteRecord)(e,"workflows",a)}catch{}throw l}return{id:a,etag:(r=s??(0,bt.readEtag)(o))!==null&&r!==void 0?r:await Is(e,a)}},async update(e,t,r,n){var i,o;let a=r,s=(0,qn.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...Eu,"If-Match":(0,bt.requireEtag)(n,"business rule",s)},c=await oM(e,s,u["If-Match"]),d=c.statecode===cn.StateCode.Activated;d&&(0,bt.ensureSuccess)(await e.patch(l,{statecode:cn.StateCode.Draft,statuscode:cn.StatusCode.Draft},{headers:u}),e.apiUrl(l));let f;try{f=await Pb(e,"UpdateProcessWithWfomJson",a,u)}catch(m){if(d)try{(0,bt.ensureSuccess)(await e.patch(l,{statecode:cn.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:cn.StatusCode.Activated},{headers:Eu}),e.apiUrl(l))}catch(h){throw new Su.SdkError(dn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE,`The business-rule write failed AND the rule could not be re-activated, so '${s}' is left DEACTIVATED (Draft) on the server. Re-activate it before relying on it. Original write failure: ${m instanceof Error?m.message:String(m)}. Restore failure: ${h instanceof Error?h.message:String(h)}`)}throw m}let p=await Ob(e,s,a.status);return{id:s,etag:(o=p??(0,bt.readEtag)(f))!==null&&o!==void 0?o:await Is(e,s)}},async delete(e,t){let r=(0,qn.normalizeGuid)(t,"id");return await(0,nM.assertWorkflowKind)(e,r,cn.WorkflowCategory.BusinessRule),(0,bt.deleteRecord)(e,"workflows",r)}}});var Tr=b(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.publishBoundEntity=ot.boundEntityPublishScope=ot.publishGenPageById=ot.publishDashboardById=ot.publishWebResourceById=ot.publishEntity=ot.publishAppModule=ot.publishXml=void 0;var Rb=we(),Ts=ae(),kb="/PublishXml";async function ta(e,t){(0,Rb.ensureSuccess)(await(0,Rb.resendDeadlockVictim)(()=>e.post(kb,{ParameterXml:t})),e.apiUrl(kb))}ot.publishXml=ta;function cM(e,t){return ta(e,`<importexportxml><appmodules><appmodule>${(0,Ts.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}ot.publishAppModule=cM;function xb(e,t){return ta(e,`<importexportxml><entities><entity>${(0,Ts.xmlText)(t)}</entity></entities></importexportxml>`)}ot.publishEntity=xb;function dM(e,t){return ta(e,`<importexportxml><webresources><webresource>${(0,Ts.xmlText)(t)}</webresource></webresources></importexportxml>`)}ot.publishWebResourceById=dM;function fM(e,t){return ta(e,`<importexportxml><dashboards><dashboard>${(0,Ts.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}ot.publishDashboardById=fM;function pM(e,t){return ta(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,Ts.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}ot.publishGenPageById=pM;function mM(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}ot.boundEntityPublishScope=mM;function hM(e,t){let r=t?.entityLogicalName;return r?xb(e,r):Promise.resolve()}ot.publishBoundEntity=hM});var ra=b(Du=>{"use strict";Object.defineProperty(Du,"__esModule",{value:!0});Du.JsonPointer=void 0;var gr=X(),Nu=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 gr.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new gr.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 gr.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 gr.JsonPointerError(r,`'${a}' is not a valid array index`);if(s>o.length)throw new gr.JsonPointerError(r,`array index '${a}' is out of range`);o[s]=n}else{if(e.isReservedToken(a))throw new gr.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 gr.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 gr.JsonPointerError(r,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new gr.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 gr.JsonPointerError(r,"add target must be an array");u.push(n);return}let a=e.resolve(t,r);if(!Array.isArray(a))throw new gr.JsonPointerError(r,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new gr.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 gr.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)}};Du.JsonPointer=Nu;Nu.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var Fb=b(_u=>{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});_u.findElements=void 0;var Lb=ra();function gM(e,t){let r=[];return pp(e,"",t,r),r}_u.findElements=gM;function pp(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)=>{pp(i,Lb.JsonPointer.append(t,o),r,n)});else for(let i of Object.keys(e))pp(e[i],Lb.JsonPointer.append(t,i),r,n)}});var mp=b(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.assertMutationResult=fn.assertExistsResult=fn.assertReadResult=fn.assertStorageContract=void 0;var yM=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],vM=["ensureContainer","exists"];function bM(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of yM)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of vM){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}fn.assertStorageContract=bM;function wM(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.`)}fn.assertReadResult=wM;function AM(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.`)}fn.assertExistsResult=AM;function CM(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.`)}fn.assertMutationResult=CM});var hp=b(na=>{"use strict";Object.defineProperty(na,"__esModule",{value:!0});na.retryTransientIoAsync=na.retryTransientIo=void 0;var EM=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),SM=5,Mb=10;function NM(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!$b(r,t))throw r;_M(Mb*t)}}na.retryTransientIo=NM;async function DM(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!$b(r,t))throw r;await new Promise(n=>setTimeout(n,Mb*t))}}na.retryTransientIoAsync=DM;function $b(e,t){let r=e.code;return t<SM&&!!r&&EM.has(r)}function _M(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var Gb=b(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.canonicalArtifactId=yr.WorkspaceManager=yr.WORKSPACE_SCHEMA_VERSION=yr.retryTransientIo=void 0;var Nt=mp(),pn=X(),IM=hp();Object.defineProperty(yr,"retryTransientIo",{enumerable:!0,get:function(){return IM.retryTransientIo}});function Bb(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}yr.WORKSPACE_SCHEMA_VERSION=1;var Ei={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},TM="manifest.json",ia=".metadata",gp="entities";function Ub(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}function yp(e){if(e.schemaVersion!==void 0&&e.schemaVersion>yr.WORKSPACE_SCHEMA_VERSION)throw new pn.IncompatibleWorkspaceError(e.schemaVersion,yr.WORKSPACE_SCHEMA_VERSION)}function qb(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Iu(e){return e.trim().toLowerCase().replace(/\/+$/,"")}var vp=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),[Ei[t],`${Ps(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[ia,Ei[t],`${Ps(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[ia,gp,`${t.toLowerCase()}.json`]}fsStore(){let t=Bb(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=Bb(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([Ei[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 pn.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[TM]}assertDataKey(t,r){if(!Array.isArray(t)||t.length<2)throw new pn.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,Nt.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=[[ia,gp]];for(let i of Object.keys(Ei))r.push([Ei[i]],[ia,Ei[i]]);let n=await Promise.allSettled(r.map(i=>Ub(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,Nt.assertMutationResult)(i.value,"ensureContainer")}}async isInitialized(){return this.storage.exists?(0,Nt.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,Nt.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 pn.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 pn.WorkspaceNotInitializedError(this.workspaceLabel);this.assertBoundHere(t.value),this.bound=!0}assertBoundHere(t){if(!qb(t))throw new pn.WorkspaceOrgMismatchError("",this.instanceUrl);yp(t);let r=typeof t.instanceUrl=="string"?t.instanceUrl.trim():"",n=Iu(r);if(!n||n!==Iu(this.instanceUrl))throw new pn.WorkspaceOrgMismatchError(r,this.instanceUrl)}async clean(){let t=await this.readStoredManifest();if(!t.present||!qb(t.value))throw new pn.WorkspaceNotInitializedError(this.workspaceLabel);let r=t.value;yp(r);let n=Object.keys(Ei).map(o=>[Ei[o]]);n.push([ia]);let i=await Promise.allSettled(n.map(o=>Ub(()=>this.storage.deleteByPrefix(o))));for(let o of i){if(o.status==="rejected")throw o.reason;(0,Nt.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,Nt.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=Vb(n);if(i!==void 0&&o===i){await this.upsertManifestEntry(t,r,n,{unlessCurrent:!0});return}(0,Nt.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,Nt.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,Nt.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=Ps(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,Nt.assertMutationResult)(await this.storage.deleteByPrefix([ia,gp]),"deleteByPrefix");return}(0,Nt.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 pn.WorkspaceNotInitializedError(this.workspaceLabel);return yp(t),t}async writeManifest(t){await this.writeJsonUnchecked(this.manifestKey,{...t,schemaVersion:yr.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();if(t.instanceUrl!==void 0&&Iu(String(t.instanceUrl))!==Iu(r.instanceUrl))throw new pn.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=Ps(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,Nt.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return await this.ensureBound(),this.storage.exists?(0,Nt.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,Nt.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}async readJsonUnchecked(t){let r=(0,Nt.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJsonUnchecked(t,r){(0,Nt.assertMutationResult)(await this.storage.writeTextAtomic(t,Vb(r)),"writeTextAtomic")}};yr.WorkspaceManager=vp;function Vb(e){return`${JSON.stringify(e,null,2)}
+`}function Ps(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()}yr.canonicalArtifactId=Ps});var bp=b(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});oa.deepEqual=oa.deepDiff=void 0;var PM=ra();function OM(e,t){let r=[];return zb(e,t,"",r,0),r}oa.deepDiff=OM;var Tu=Symbol("missing"),Pu=512;function zb(e,t,r,n,i){if(e===t)return;if(i>Pu)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${Pu}`);let o=Ou(e),a=Ou(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=RM(e,t);for(let l of s){let u=Wb(e,l),c=Wb(t,l),d=PM.JsonPointer.append(r,l);u===Tu?n.push({pointer:d,type:"added",newValue:c}):c===Tu?n.push({pointer:d,type:"removed",oldValue:u}):zb(u,c,d,n,i+1)}return}jb(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function Ou(e){return e!==null&&typeof e=="object"}function RM(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 Wb(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:Tu}return t in e?e[t]:Tu}function jb(e,t){return Hb(e,t,0)}oa.deepEqual=jb;function Hb(e,t,r){if(e===t)return!0;if(r>Pu)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${Pu}`);if(!Ou(e)||!Ou(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&&Hb(e[o],t[o],r+1))}});var Jb=b(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});aa.VersionManager=aa.PROJECTION_VERSION=void 0;var Kb=bp();aa.PROJECTION_VERSION=7;var wp=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,Kb.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,Kb.deepDiff)(i.snapshot,n):o=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:o}}async checkConflict(t,r,n){let i=await this.getMeta(t,r);return!i||i.etag===null?!1:i.etag!==n}};aa.VersionManager=wp});var Yb=b((Ap,Qb)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof Ap=="object"?Qb.exports=t():e.compareVersions=t()})(Ap,function(){var e=/^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;function t(o,a){return o.indexOf(a)===-1?o.length:o.indexOf(a)}function r(o){var a=o.replace(/^v/,"").replace(/\+.*$/,""),s=t(a,"-"),l=a.substring(0,s).split(".");return l.push(a.substring(s+1)),l}function n(o){return isNaN(Number(o))?o:Number(o)}function i(o){if(typeof o!="string")throw new TypeError("Invalid argument expected string");if(!e.test(o))throw new Error("Invalid argument not valid semver ('"+o+"' received)")}return function(a,s){[a,s].forEach(i);for(var l=r(a),u=r(s),c=0;c<Math.max(l.length-1,u.length-1);c++){var d=parseInt(l[c]||0,10),f=parseInt(u[c]||0,10);if(d>f)return 1;if(f>d)return-1}var p=l[l.length-1],m=u[u.length-1];if(p&&m){var h=p.split(".").map(n),g=m.split(".").map(n);for(c=0;c<Math.max(h.length,g.length);c++){if(h[c]===void 0||typeof g[c]=="string"&&typeof h[c]=="number")return-1;if(g[c]===void 0||typeof h[c]=="string"&&typeof g[c]=="number"||h[c]>g[c])return 1;if(g[c]>h[c])return-1}}else if(p||m)return p?-1:1;return 0}})});var rw=b(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.EnvironmentFlowHostingType=Be.EnvironmentDisableReasonCode=Be.EnvironmentMigrationConstants=Be.EnvironmentProvisioningStates=Be.EnvironmentLocations=Be.EnvironmentCreationTypeConstants=Be.EnvironmentType=Be.EnvironmentSkuConstants=Be.environmentPermissions=Be.DatabaseType=void 0;var Xb;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(Xb||(Be.DatabaseType=Xb={}));Be.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"};Be.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var Zb;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(Zb||(Be.EnvironmentType=Zb={}));Be.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Be.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"};Be.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Be.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var ew;(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"})(ew||(Be.EnvironmentDisableReasonCode=ew={}));var tw;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(tw||(Be.EnvironmentFlowHostingType=tw={}))});var cw=b(D=>{"use strict";var kM=D&&D.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(D,"__esModule",{value:!0});D.hasCommonDataServiceDatabase=D.getEnvironmentDiscoveryUrl=D.getEnvironmentWebApiUrl=D.getEnvironmentInstanceApiUrl=D.getEnvironmentLanguageCode=D.getEnvironmentUpdateCadence=D.checkVersions=D.isCds2EnvironmentVersionAtLeast=D.getSecurityOrConnectedGroupId=D.hasSecurityGroupId=D.doesCds2VersionSupportApiVersion9_1=D.doesCds2EnvironmentSupportApiVersion9_1=D.cdsVersionSupportingOSColorEdit=D.getEnvironmentDisplayName=D.getEnvironmentName=D.isEnvironmentInFirstReleaseCluster=D.isEnvironmentInPreprodCluster=D.isEnvironmentInTestCluster=D.isLiteEnvironmentUpgrading=D.isEnvironmentExpired=D.isEnvironmentInDeletedState=D.isEnvironmentInCreatingState=D.isDatabaseInProvisioningState=D.canUserCreateDatabase=D.isDisabledEnvironment=D.isDefaultEnvironment=D.isTrialEnvironment=D.isPlatformEnvironment=D.isTeamsEnvironment=D.isSandboxEnvironment=D.isProdEnvironment=D.isDevEnvironment=D.getEnvironmentType=D.getCrmInstanceName=D.getCrmInstanceUrl=D.getCrmAppDesignerUrl=D.getDevResourcesUrl=D.isEnvironmentInSuccessfulState=D.getAllThemesUrl=D.getAllPublishersUrl=D.getAllSolutionsUrl=D.getSecurityRolesUrl=D.getSecurityUsersUrl=D.environmentHasCds2Database=D.DEFAULT_SOLUTION_UNIQUE_NAME=D.DEFAULT_SOLUTION_ID=D.crmBapSolutionId=D.doesUserHavePermission=D.getLinkedEnvironmentMetadata=D.getCrmVersion=void 0;D.doesUserHaveFlowRunOnlyPermission=D.isUserPautoMakerWithoutDataAccess=D.isUserPautoMakerWithDataAccess=D.doesUserHaveCreateFlowPermission=D.equalsIgnoreCase=D.doesUserHaveCreateDatabasePermission=D.doesUserHaveDatabaseTablePermissions=D.isUserMakerWithoutDataAccess=D.isUserMakerWithDataAccess=D.doesUserHaveCreateAppPermission=D.doesUserHaveAdminPermission=void 0;var xM=kM(Yb()),Ee=rw(),Os=Ep();function LM(e){let t=Gn(e);return t&&t.version}D.getCrmVersion=LM;function Gn(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}D.getLinkedEnvironmentMetadata=Gn;function Vn(e,t){return e?!!e[t]:!1}D.doesUserHavePermission=Vn;D.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";D.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";D.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function io(e){return!!Gn(e)&&nw(e)}D.environmentHasCds2Database=io;function FM(e){if(e&&io(e)){let t=Si(e);return(0,Os.getCrmAdminSecurityRolesUrl)(t)}return""}D.getSecurityUsersUrl=FM;function MM(e){if(e&&io(e)){let t=Si(e);return(0,Os.getCrmAdminSecurityUsersUrl)(t)}return""}D.getSecurityRolesUrl=MM;function $M(e){if(e&&io(e)){let t=Si(e);(0,Os.getCrmAllSolutionsUrl)(t)}return""}D.getAllSolutionsUrl=$M;function BM(e){if(e&&io(e)){let t=Si(e);return(0,Os.getCrmAllPublishersUrl)(t)}return""}D.getAllPublishersUrl=BM;function UM(e){return e&&io(e)?Si(e):""}D.getAllThemesUrl=UM;function nw(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===Ee.EnvironmentProvisioningStates.Succeeded.toUpperCase()}D.isEnvironmentInSuccessfulState=nw;function qM(e){if(e&&io(e)){let t=Si(e);return(0,Os.getCrmDevResourcesUrl)(t)}return""}D.getDevResourcesUrl=qM;function VM(e){return`${e}designer/app/{${D.crmBapSolutionId}}/CreateNewApp}}`}D.getCrmAppDesignerUrl=VM;function Si(e){let t=Gn(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}D.getCrmInstanceUrl=Si;function GM(e){let t=Gn(e);return t?t.uniqueName:""}D.getCrmInstanceName=GM;function WM(e){return Gn(e)?Ee.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?Ee.EnvironmentType.CDS1:Ee.EnvironmentType.Empty}D.getEnvironmentType=WM;function zM(e){return e&&e.properties&&e.properties.environmentSku===Ee.EnvironmentSkuConstants.Developer}D.isDevEnvironment=zM;function jM(e){return e&&e.properties&&e.properties.environmentSku===Ee.EnvironmentSkuConstants.Production}D.isProdEnvironment=jM;function HM(e){return e&&e.properties&&e.properties.environmentSku===Ee.EnvironmentSkuConstants.Sandbox}D.isSandboxEnvironment=HM;function Rs(e){return e&&e.properties&&e.properties.environmentSku===Ee.EnvironmentSkuConstants.Teams}D.isTeamsEnvironment=Rs;function KM(e){return e&&e.properties&&e.properties.environmentSku===Ee.EnvironmentSkuConstants.Platform}D.isPlatformEnvironment=KM;var JM=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===Ee.EnvironmentSkuConstants.Trial};D.isTrialEnvironment=JM;function QM(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===Ee.EnvironmentCreationTypeConstants.DefaultTenant)}D.isDefaultEnvironment=QM;function YM(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}D.isDisabledEnvironment=YM;function XM(e){return e&&e.properties&&Vn(e.properties.permissions,Ee.environmentPermissions.CreateDatabase)}D.canUserCreateDatabase=XM;function ZM(e){return!!(e&&e.properties&&e.properties.provisioningState&&uw(e.properties.provisioningState,Ee.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}D.isDatabaseInProvisioningState=ZM;function e$(e){return!!e&&!!e.properties&&e.properties.provisioningState===Ee.EnvironmentProvisioningStates.Creating}D.isEnvironmentInCreatingState=e$;function t$(e){return e&&e.properties&&(e.properties.provisioningState===Ee.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===Ee.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===Ee.EnvironmentProvisioningStates.FailedDeleting)}D.isEnvironmentInDeletedState=t$;function r$(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}D.isEnvironmentExpired=r$;function n$(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"}D.isLiteEnvironmentUpgrading=n$;function i$(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}D.isEnvironmentInTestCluster=i$;function o$(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}D.isEnvironmentInPreprodCluster=o$;function a$(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}D.isEnvironmentInFirstReleaseCluster=a$;function s$(e){return e&&e.name||""}D.getEnvironmentName=s$;function l$(e){return e&&e.properties&&e.properties.displayName||""}D.getEnvironmentDisplayName=l$;var iw="9.1.0.8202";D.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function u$(e){return sw(e,iw)}D.doesCds2EnvironmentSupportApiVersion9_1=u$;function c$(e){return Cp(e,iw)}D.doesCds2VersionSupportApiVersion9_1=c$;function ow(e){let t=Gn(e);if(t)return t.securityGroupId}function aw(e){return e&&e.properties&&e.properties.connectedGroups}function d$(e,t){let r=aw(e);return!!r&&!!r.find(n=>n.id===t)||ow(e)===t}D.hasSecurityGroupId=d$;function f$(e){let t=aw(e);return t&&t.length>0&&t[0].id?t[0].id:ow(e)}D.getSecurityOrConnectedGroupId=f$;function sw(e,t){let r=e.version;return r?Cp(r,t):!1}D.isCds2EnvironmentVersionAtLeast=sw;function Cp(e,t){return t?e?(0,xM.default)(e,t)>=0:!1:!0}D.checkVersions=Cp;function p$(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}D.getEnvironmentUpdateCadence=p$;function m$(e){let t=Gn(e);return t?Number(t.baseLanguage):0}D.getEnvironmentLanguageCode=m$;function lw(e){let t=Gn(e);return t?t.instanceApiUrl:void 0}D.getEnvironmentInstanceApiUrl=lw;function h$(e){let t=lw(e);return t?t+"/api/data/v9.2":""}D.getEnvironmentWebApiUrl=h$;function g$(e){let t=Si(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"}D.getEnvironmentDiscoveryUrl=g$;var y$=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===Ee.DatabaseType.CommonDataService};D.hasCommonDataServiceDatabase=y$;var v$=e=>{var t;return Vn((t=e.properties)===null||t===void 0?void 0:t.permissions,Ee.environmentPermissions.AdminReadEnvironment)};D.doesUserHaveAdminPermission=v$;var b$=e=>{var t;return Vn((t=e.properties)===null||t===void 0?void 0:t.permissions,Ee.environmentPermissions.CreatePowerApp)};D.doesUserHaveCreateAppPermission=b$;var w$=e=>(0,D.doesUserHaveAdminPermission)(e)&&(0,D.hasCommonDataServiceDatabase)(e)?!0:(0,D.doesUserHaveCreateAppPermission)(e)?Rs(e)||(0,D.doesUserHaveDatabaseTablePermissions)(e):!1;D.isUserMakerWithDataAccess=w$;var A$=e=>(0,D.doesUserHaveCreateAppPermission)(e)&&!Rs(e)&&!(0,D.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,D.doesUserHaveAdminPermission)(e)||!(0,D.hasCommonDataServiceDatabase)(e));D.isUserMakerWithoutDataAccess=A$;var C$=e=>[Ee.environmentPermissions.CreateDatabaseEntities,Ee.environmentPermissions.ListDatabaseEntities,Ee.environmentPermissions.UpdateDatabaseEntities,Ee.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return Vn((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});D.doesUserHaveDatabaseTablePermissions=C$;var E$=e=>{var t;return Vn((t=e.properties)===null||t===void 0?void 0:t.permissions,Ee.environmentPermissions.CreateDatabase)};D.doesUserHaveCreateDatabasePermission=E$;function uw(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}D.equalsIgnoreCase=uw;var S$=e=>{var t;return Vn((t=e.properties)===null||t===void 0?void 0:t.permissions,Ee.environmentPermissions.CreateFlow)};D.doesUserHaveCreateFlowPermission=S$;var N$=e=>(0,D.doesUserHaveAdminPermission)(e)&&(0,D.hasCommonDataServiceDatabase)(e)?!0:(0,D.doesUserHaveCreateFlowPermission)(e)?Rs(e)||(0,D.doesUserHaveDatabaseTablePermissions)(e):!1;D.isUserPautoMakerWithDataAccess=N$;var D$=e=>(0,D.doesUserHaveCreateFlowPermission)(e)&&!Rs(e)&&!(0,D.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,D.doesUserHaveAdminPermission)(e)||!(0,D.hasCommonDataServiceDatabase)(e));D.isUserPautoMakerWithoutDataAccess=D$;var _$=e=>{var t,r;return!Vn((t=e.properties)===null||t===void 0?void 0:t.permissions,Ee.environmentPermissions.CreateFlow)&&Vn((r=e.properties)===null||r===void 0?void 0:r.permissions,Ee.environmentPermissions.ReadEnvironment)};D.doesUserHaveFlowRunOnlyPermission=_$});var Ep=b(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.getRequiredComponentsQueryUrl=S.solutionComponentCountSummariesQueryUrl=S.solutionComponentSummariesQueryUrl=S.solutionComponentConfigurationsQueryUrl=S.chartsQueryUrl=S.workflowsQueryUrl=S.entityDefinitionsQueryUrl=S.solutionComponentDefinitionsQueryUrl=S.getCreateNewArticleTemplateUrl=S.getCreateNewPublisherUrl=S.getEnableSecurityRolesUrl=S.getArticleTemplateUrl=S.getFieldSecurityProfileDesignerUrl=S.getSecurityRoleDesignerUrl=S.getMailMergeTemplateDesignerUrl=S.getEmailTemplateDesignerUrl=S.getConnectionRoleDesignerUrl=S.getSiteMapDesignerUrl=S.getWebResourceFileUrl=S.getWebResourceDesignerUrl=S.getReportDesignerUrl=S.getBusinessProcessFlowDesignerUrl=S.getProcessShareUrl=S.getProcessDesignerUrl=S.getChartDesignerUrl=S.getOpenModernEntityDashboardUrl=S.getNewModernEntityDashboardUrl=S.getNewModernDashboardUrl=S.getOpenModernDashboardUrl=S.getDashboardDesignerUrl=S.getAppModuleDesignerUrl=S.privilegesQueryUrls=S.xrmApiUrl=S.getPlayAppModuleUrl=S.getCrmAdminSecurityUsersUrl=S.getCrmAdminSecurityRolesUrl=S.getCrmMyAppsUrl=S.getCrmAppDesignerUrl=S.getCrmDevResourcesUrl=S.getCrmAllPublishersUrl=S.getCrmAllSolutionsUrl=S.getSolutionPublisherUrl=S.getExportTranslationFileName=S.getExportSolutionTranslationUrl=S.getImportSolutionTranslationUrl=S.getShowSolutionDependenciesUrl=S.getShowComponentDependenciesUrl=S.cdsServiceUrl=S.ODATA_NEXT_LINK=S.ODATA_MAX_PAGE_SIZE=void 0;S.retrieveOrganizationResources=S.getUCIEntityRecordEditUrl=S.getUCIEntityRecordBaseUrl=S.getBusinessRuleDesignerUri=S.retrieveUnpublishedSuffix=S.getSavePowerSettingUri=S.getPowerSettingUri=S.getPowerSettingsUri=S.RetrievePlatform=S.getAppSettingOverrideUri=S.AppSettingOverrideName=S.getOrgSettingOverrideUri=S.OrgSettingOverrideName=S.getSettingDefinitionsUri=S.retrieveFeatureControlSettingsByNamespaceUrl=S.retrieveDeploymentPipelineConfigAppUrl=S.SPNPrincipalIdUrl=S.retrieveDeploymentEnvironmentInfoUrl=S.devSolutionInfoUrl=S.deployOperationStatusUrl=S.getAIGeneratedDeploymentNotesUrl=S.deploymentStageRunUrl=S.validatePackageAsyncUrl=S.deployPackageAsyncUrl=S.updateDeploymentStageRunUrl=S.createDeploymentStageRunUrl=S.retrieveDeploymentStagesUrl=S.retrievePipelinesUrl=S.retrieveDeploymentPipelineInfoUrl=S.getDeploymentStageRunsUrl=S.appDeploymentUrls=S.getProvisionLanguageUrl=S.getSolutionQueryUrl=S.getSolutionsByUniqueNameQueryUrl=S.solutionsQueryUrl=S.getDependentComponentsWithMetadataQueryUrl=void 0;var dw=cw();S.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";S.ODATA_NEXT_LINK="@odata.nextLink";S.cdsServiceUrl="https://cds-org/";var xs;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(xs||(xs={}));function I$(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}S.getShowComponentDependenciesUrl=I$;function T$(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}S.getShowSolutionDependenciesUrl=T$;function P$(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}S.getImportSolutionTranslationUrl=P$;function O$(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}S.getExportSolutionTranslationUrl=O$;function R$(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}S.getExportTranslationFileName=R$;function k$(e,t,r){return r?`${e}tools/publisher/edit.aspx?appSolutionId=%7b${r}%7d&id=%7b${t}%7d`:`${e}tools/publisher/edit.aspx?id=%7b${t}%7d`}S.getSolutionPublisherUrl=k$;function Sp(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function x$(e){return Sp(e,xs.AllSolutions)}S.getCrmAllSolutionsUrl=x$;function L$(e){return Sp(e,xs.AllPublishers)}S.getCrmAllPublishersUrl=L$;function F$(e){return Sp(e,xs.DevResources)}S.getCrmDevResourcesUrl=F$;function M$(e,t=dw.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}S.getCrmAppDesignerUrl=M$;function $$(e){return`${e}apps`}S.getCrmMyAppsUrl=$$;function B$(e){return fw(e,"role")+"&forceUCI=0"}S.getCrmAdminSecurityRolesUrl=B$;function U$(e){return`${fw(e,"systemuser")}&forceclassic=1`}S.getCrmAdminSecurityUsersUrl=U$;function fw(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function q$(e,t){return`${e}main.aspx?appid=${t}`}S.getPlayAppModuleUrl=q$;S.xrmApiUrl="api/data/v9.0";S.privilegesQueryUrls={systemUserInfo:e=>`${e}${S.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${S.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${S.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function V$(e,t,r=dw.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}S.getAppModuleDesignerUrl=V$;function G$(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}S.getDashboardDesignerUrl=G$;function W$(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}S.getOpenModernDashboardUrl=W$;function z$(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}S.getNewModernDashboardUrl=z$;function j$(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}S.getNewModernEntityDashboardUrl=j$;function H$(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}S.getOpenModernEntityDashboardUrl=H$;function K$(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}S.getChartDesignerUrl=K$;function J$(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getProcessDesignerUrl=J$;function Q$(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getProcessShareUrl=Q$;function Y$(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}S.getBusinessProcessFlowDesignerUrl=Y$;function X$(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}S.getReportDesignerUrl=X$;function Z$(e,t,r){return`${e}main.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&etc=9333&id=%7b${t}%7d&pagetype=webresourceedit`}S.getWebResourceDesignerUrl=Z$;function eB(e,t){return`${e}WebResources/${t}`}S.getWebResourceFileUrl=eB;function tB(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}S.getSiteMapDesignerUrl=tB;function rB(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getConnectionRoleDesignerUrl=rB;function nB(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getEmailTemplateDesignerUrl=nB;function iB(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getMailMergeTemplateDesignerUrl=iB;function oB(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getSecurityRoleDesignerUrl=oB;function aB(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}S.getFieldSecurityProfileDesignerUrl=aB;function sB(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}S.getArticleTemplateUrl=sB;function lB(e,t,r,n){return`${e}tools/FormEditor/Dialogs/FormRoleAssignment.aspx?appSolutionId=%7b${t}%7d&dType=1&formId=%7b${r}%7d&objectTypeCode=0&type=${n}`}S.getEnableSecurityRolesUrl=lB;function uB(e){return`${e}tools/publisher/edit.aspx`}S.getCreateNewPublisherUrl=uB;function cB(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}S.getCreateNewArticleTemplateUrl=cB;S.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";S.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";S.workflowsQueryUrl="api/data/v9.0/workflows";S.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";S.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";S.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";S.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function dB(e,t){return`${S.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}S.getRequiredComponentsQueryUrl=dB;function fB(e,t){return`${S.cdsServiceUrl}${S.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}S.getDependentComponentsWithMetadataQueryUrl=fB;S.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function pB(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}S.getSolutionsByUniqueNameQueryUrl=pB;function mB(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}S.getSolutionQueryUrl=mB;function hB(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}S.getProvisionLanguageUrl=hB;S.appDeploymentUrls={associateEnvironmentToPipelineUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})/deploymentpipeline_deploymentenvironment/$ref`,deploymentArtifactsUrl:"/api/data/v9.0/deploymentartifacts",deploymentEnvironmentUrl:"/api/data/v9.0/deploymentenvironments",deploymentPipelinesUrl:"/api/data/v9.0/deploymentpipelines",deploymentStagesUrl:"/api/data/v9.0/deploymentstages",retrieveDeploymentPipelinesUrl:e=>`/api/data/v9.0/RetrieveDeploymentPipelines(SourceEnvironmentId='${e}')`,deletePipelinesUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})`};function gB(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`}E.getDeploymentStageRunsUrl=uF;function cF(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}E.retrieveDeploymentPipelineInfoUrl=cF;function dF(e){return`/api/data/v9.0/deploymentenvironments
+ &$orderby=starttime desc`}S.getDeploymentStageRunsUrl=gB;function yB(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}S.retrieveDeploymentPipelineInfoUrl=yB;function vB(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}')`}E.retrievePipelinesUrl=dF;function pF(e){return`/api/data/v9.0/deploymentstages
+ &$filter=(environmentid eq '${e}')`}S.retrievePipelinesUrl=vB;function bB(e){return`/api/data/v9.0/deploymentstages
?$filter=(_deploymentpipelineid_value eq ${e})
&$select=name,description,deploymentstageid,_previousdeploymentstageid_value
- &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}E.retrieveDeploymentStagesUrl=pF;function fF(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}E.createDeploymentStageRunUrl=fF;function mF(e){return`/api/data/v9.0/deploymentstageruns(${e})`}E.updateDeploymentStageRunUrl=mF;function hF(){return"/api/data/v9.0/DeployPackageAsync"}E.deployPackageAsyncUrl=hF;function gF(){return"/api/data/v9.0/ValidatePackageAsync"}E.validatePackageAsyncUrl=gF;function vF(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)":""}`}E.deploymentStageRunUrl=vF;function yF(e){return`/api/data/v9.0/deploymentstageruns(${e})
- ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}E.getAIGeneratedDeploymentNotesUrl=yF;function bF(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)`}S.retrieveDeploymentStagesUrl=bB;function wB(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}S.createDeploymentStageRunUrl=wB;function AB(e){return`/api/data/v9.0/deploymentstageruns(${e})`}S.updateDeploymentStageRunUrl=AB;function CB(){return"/api/data/v9.0/DeployPackageAsync"}S.deployPackageAsyncUrl=CB;function EB(){return"/api/data/v9.0/ValidatePackageAsync"}S.validatePackageAsyncUrl=EB;function SB(e,t=!1,r=!1){return`/api/data/v9.0/deploymentstageruns(${e})
+ ?$select=deploymentstagerunid,stagerunstatus,errormessage,operation,operationdetails,operationstatus,${t?"scheduledtime,":""}targetenvironmentid,validationresults,artifactname,deploymentsettingsjson${r?"&$expand=createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}`}S.deploymentStageRunUrl=SB;function NB(e){return`/api/data/v9.0/deploymentstageruns(${e})
+ ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}S.getAIGeneratedDeploymentNotesUrl=NB;function DB(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`}E.deployOperationStatusUrl=bF;function wF(e){return`/api/data/v9.0/solutions(${e})
- ?$select=solutionid,uniquename,version`}E.devSolutionInfoUrl=wF;function AF(e){return`/api/data/v9.0/deploymentenvironments
+ &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}S.deployOperationStatusUrl=DB;function _B(e){return`/api/data/v9.0/solutions(${e})
+ ?$select=solutionid,uniquename,version`}S.devSolutionInfoUrl=_B;function IB(e){return`/api/data/v9.0/deploymentenvironments
?$select=deploymentenvironmentid,environmentid,environmenttype,name
- &$filter=(environmentid eq '${e}')`}E.retrieveDeploymentEnvironmentInfoUrl=AF;var EF=e=>`/api/data/v9.0/systemusers
+ &$filter=(environmentid eq '${e}')`}S.retrieveDeploymentEnvironmentInfoUrl=IB;var TB=e=>`/api/data/v9.0/systemusers
?$select=azureactivedirectoryobjectid
- &$filter=(applicationid eq '${e}')`;E.SPNPrincipalIdUrl=EF;function CF(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}E.retrieveDeploymentPipelineConfigAppUrl=CF;E.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function SF(e){return`/api/data/v9.0/settingdefinitions${e}`}E.getSettingDefinitionsUri=SF;E.OrgSettingOverrideName="organizationsettings";function NF(e,t=!1){let r=`/api/data/v9.0/${E.OrgSettingOverrideName}${e}`;return t?`${E.cdsServiceUrl}${r}`:r}E.getOrgSettingOverrideUri=NF;E.AppSettingOverrideName="appsettings";function DF(e,t=!1){let r=`/api/data/v9.0/${E.AppSettingOverrideName}${e}`;return t?`${E.cdsServiceUrl.replace("/$","")}${r}`:r}E.getAppSettingOverrideUri=DF;var Ya;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(Ya||(E.RetrievePlatform=Ya={}));function _F(e,t,r,n=Ya.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),r&&o.push(`RetrieveHiddenSettings=${r}`),n!==Ya.All&&o.push(`RetrievePlatformSettings=${n===Ya.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${E.cdsServiceUrl}${a}`:a}E.getPowerSettingsUri=_F;function IF(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?`${E.cdsServiceUrl}${o}`:o}E.getPowerSettingUri=IF;function TF(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${E.cdsServiceUrl}${t}`:t}E.getSavePowerSettingUri=TF;E.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function PF(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}E.getBusinessRuleDesignerUri=PF;function Dy({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}E.getUCIEntityRecordBaseUrl=Dy;function RF({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||Dy({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}E.getUCIEntityRecordEditUrl=RF;E.retrieveOrganizationResources=`${E.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var Iy=b(kl=>{"use strict";Object.defineProperty(kl,"__esModule",{value:!0});kl.DataverseClient=void 0;var OF=hp(),Ri=re(),_y=be(),vp=class{constructor(t,r,n){this.instanceUrl=t,this.httpClient=r,this.solutionUniqueName=n}withSolution(t){return this.solutionUniqueName?{...t,headers:{...t?.headers,"MSCRM.SolutionUniqueName":this.solutionUniqueName}}:t}apiUrl(t){let r=this.instanceUrl.replace(/\/+$/,""),n=t.startsWith("/")?t:`/${t}`;return`${r}/${OF.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof Ri.SdkError?n:new Ri.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t);return(0,_y.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,r)))}getAbsolute(t,r){return this.assertSameOrigin(t),(0,_y.resendDeadlockVictim)(()=>this.send(t,()=>this.httpClient.get(t,r)))}assertSameOrigin(t){let r,n;try{r=new URL(t),n=new URL(this.instanceUrl)}catch{throw new Ri.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new Ri.InvalidArgumentError(`Refusing to follow a cross-origin link ('${r.origin}' is not the configured instance '${n.origin}'); server-driven pagination must stay on-instance.`)}post(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.post(i,r,this.withSolution(n)))}get supportsAtomicBatch(){return typeof this.httpClient.postRaw=="function"}get solutionName(){return this.solutionUniqueName}postBatch(t,r,n){if(!this.httpClient.postRaw)throw new Ri.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 Ri.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 Ri.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)))}};kl.DataverseClient=vp});var Ty=b(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.findColumns=Zn.findTables=Zn.fetchEntityMetadataFromApi=void 0;var bp=be(),ir=ae();function Vr(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}function So(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 Fl(e,t){return(await Ml(e,t)).rows}async function Ml(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?{rows:[],ok:!1}:{rows:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[],ok:!0}}function Gr(e){return`/EntityDefinitions(LogicalName='${(0,ir.odataPathLiteral)(e)}')`}async function xF(e,t,r){let n=await Fl(e,`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,ir.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 LF(e){return`${Gr(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,ir.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function kF(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:Vr(a.Label),...So(a.Label)?{localizedLabel:So(a.Label)}:{}}}))}}function yp(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:Vr(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function FF(e,t,r){var n;let i=u=>Ml(e,u).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([r.catch(()=>({rows:[],ok:!1})),...o.map(u=>i(`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.${u}${(0,ir.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`))]),s=new Map;for(let{rows:u}of a)for(let c of u)!((n=c.OptionSet)===null||n===void 0)&&n.Options&&s.set(c.LogicalName,c.OptionSet.Options.map(yp));let l=await i(`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,ir.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let u of l.rows){let c=u.OptionSet;c?.TrueOption&&c.FalseOption&&s.set(u.LogicalName,[yp(c.FalseOption),yp(c.TrueOption)])}return{byColumn:s,complete:l.ok&&a.every(u=>u.ok)}}async function MF(e,t,r){let{rows:n,ok:i}=await Ml(e,`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,ir.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let o of n){let a=r.get(o.LogicalName);a&&o.Targets&&(a.targets=o.Targets)}return i}async function BF(e,t){var r,n,i,o;let a=[],s=await Fl(e,`${Gr(t)}/OneToManyRelationships${(0,ir.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 Fl(e,`${Gr(t)}/ManyToOneRelationships${(0,ir.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 Fl(e,`${Gr(t)}/ManyToManyRelationships${(0,ir.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}async function $F(e,t){var r,n,i,o,a;let s=`${Gr(t)}`+(0,ir.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,bp.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(g=>{var y,w,C;return{logicalName:g.LogicalName,displayName:Vr(g.DisplayName),...So(g.DisplayName)?{localizedDisplayName:So(g.DisplayName)}:{},attributeType:(y=g.AttributeType)!==null&&y!==void 0?y:"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}:{},...Vr(g.Description)?{description:Vr(g.Description)}:{}}}),d=new Map(c.map(g=>[g.logicalName,g])),p=Ml(e,LF(t)),[,,f,m,h]=await Promise.all([xF(e,t,d),kF(p,d),FF(e,t,p),MF(e,t,d),BF(e,t)]);for(let g of c){let y=f.byColumn.get(g.logicalName);y&&(g.choices=y)}return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:Vr(u.DisplayName),...So(u.DisplayName)?{localizedDisplayName:So(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,...Vr(u.Description)?{description:Vr(u.Description)}:{},columnDetailComplete:f.complete&&m,attributes:c,relationships:h}}Zn.fetchEntityMetadataFromApi=$F;async function UF(e,t,r){var n,i;let o=`/EntityDefinitions${(0,ir.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,bp.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,p;return{logicalName:c.LogicalName,schemaName:(d=c.SchemaName)!==null&&d!==void 0?d:c.LogicalName,displayName:Vr(c.DisplayName),entitySetName:(p=c.EntitySetName)!==null&&p!==void 0?p:"",isCustom:!!c.IsCustomEntity}}).filter(c=>c.logicalName.toLowerCase().includes(l)||c.schemaName.toLowerCase().includes(l)||c.displayName.toLowerCase().includes(l));return typeof r?.top=="number"?u.slice(0,r.top):u}Zn.findTables=UF;async function qF(e,t,r,n){var i,o;let a=`${Gr(t)}/Attributes`+(0,ir.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(o=(i=(0,bp.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 p,f;return{logicalName:d.LogicalName,schemaName:(p=d.SchemaName)!==null&&p!==void 0?p:d.LogicalName,displayName:Vr(d.DisplayName),attributeType:(f=d.AttributeType)!==null&&f!==void 0?f:"Unknown",isCustom:!!d.IsCustomAttribute}}).filter(d=>d.logicalName.toLowerCase().includes(u)||d.schemaName.toLowerCase().includes(u)||d.displayName.toLowerCase().includes(u));return typeof n?.top=="number"?c.slice(0,n.top):c}Zn.findColumns=qF});var Ep=b(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.renderTypeRegistrations=Ot.buildGenPageLegacyEnums=Ot.renderGenPageAuthoringTypes=Ot.buildGenPageRuntimeTypes=Ot.toDesignerEntity=Ot.TABLE_LOGICAL_NAME=void 0;Ot.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function wp(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var VF=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function Bl(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function Oy(e){var t,r;let n=e.choices;if(!n||n.length===0)return;let i=Bl(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 Py(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function xy(e){return!VF.has(e.logicalName)&&(!e.attributeOf||Bl(e)==="image")&&e.isValidForRead!==!1}var Ry=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function Ly(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(Py),i=e.attributes.filter(o=>!r.has(o.logicalName)).sort(Py);return[...n,...i]}function Ap(e){var t;let r=[],n=new Set,i=Ly(e);for(let o of i){let a=Bl(o),s=a==="image";xy(o)&&(s&&o.attributeOf&&n.add(o.attributeOf),r.push({AttributeTypeName:a,IsReadOnly:!o.isValidForUpdate,LogicalName:o.logicalName,OptionSet:Oy(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))}}Ot.toDesignerEntity=Ap;function ky(e,t="None"){let r={};for(let n of e)r[n.logicalName]=Ap(n);return By(r,t)}Ot.buildGenPageRuntimeTypes=ky;var Fy=`export interface TableRegistrations extends BaseTableRegistrations {
-`,My=`export interface EnumRegistrations extends BaseEnumRegistrations {
-`;function GF(e,t){return e.length>0?ky(e,t).text:Uy(`${Fy}}
-`,`${My}}
-`,"","")}Ot.renderGenPageAuthoringTypes=GF;function zF(e){let t=new Set;for(let n of e)for(let i of Ap(n).Attributes)Ry.has(i.AttributeTypeName)&&t.add(`${n.logicalName}_${i.LogicalName}`);let r=new Map;for(let n of e)for(let i of Ly(n)){let o=`${n.logicalName}_${i.logicalName}`,a=Oy(i);if(xy(i)||!Ry.has(Bl(i))||!a||t.has(o)||r.has(o))continue;let s={name:o,runtime:{},labels:new Map};r.set(o,{declaration:$y(o,a,!1,s),model:s})}return r}Ot.buildGenPageLegacyEnums=zF;function By(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=Fy,u=My,c="",d="";for(let p of o){s&&p.Description&&(c+=`// ${wp(p.Description)}
-`),c+=`export type ${p.LogicalName} = TableRow<{
+ &$filter=(applicationid eq '${e}')`;S.SPNPrincipalIdUrl=TB;function PB(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}S.retrieveDeploymentPipelineConfigAppUrl=PB;S.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function OB(e){return`/api/data/v9.0/settingdefinitions${e}`}S.getSettingDefinitionsUri=OB;S.OrgSettingOverrideName="organizationsettings";function RB(e,t=!1){let r=`/api/data/v9.0/${S.OrgSettingOverrideName}${e}`;return t?`${S.cdsServiceUrl}${r}`:r}S.getOrgSettingOverrideUri=RB;S.AppSettingOverrideName="appsettings";function kB(e,t=!1){let r=`/api/data/v9.0/${S.AppSettingOverrideName}${e}`;return t?`${S.cdsServiceUrl.replace("/$","")}${r}`:r}S.getAppSettingOverrideUri=kB;var ks;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(ks||(S.RetrievePlatform=ks={}));function xB(e,t,r,n=ks.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),r&&o.push(`RetrieveHiddenSettings=${r}`),n!==ks.All&&o.push(`RetrievePlatformSettings=${n===ks.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${S.cdsServiceUrl}${a}`:a}S.getPowerSettingsUri=xB;function LB(e,t,r,n=!1){let i=[`SettingName='${e}'`];t!==void 0&&i.push(`SolutionName='${t}'`),r!==void 0&&i.push(`AppUniqueName='${r}'`);let o="/api/data/v9.0/RetrieveUnpublishedSettingInfo";return i.length&&(o=`${o}(${i.join(",")})`),n?`${S.cdsServiceUrl}${o}`:o}S.getPowerSettingUri=LB;function FB(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${S.cdsServiceUrl}${t}`:t}S.getSavePowerSettingUri=FB;S.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function MB(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}S.getBusinessRuleDesignerUri=MB;function pw({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}S.getUCIEntityRecordBaseUrl=pw;function $B({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||pw({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}S.getUCIEntityRecordEditUrl=$B;S.retrieveOrganizationResources=`${S.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var gw=b(Ru=>{"use strict";Object.defineProperty(Ru,"__esModule",{value:!0});Ru.DataverseClient=void 0;var BB=Ep(),oo=X(),mw=we(),UB=new Set(["entitydefinitions","relationshipdefinitions","globaloptionsetdefinitions"]);function qB(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 UB.has(s)}function VB(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 hw(e,t){var r;if(!qB(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 Np=class{constructor(t,r,n,i=1){this.instanceUrl=t,this.httpClient=r,this.solutionUniqueName=n,this.readConcurrency=i}withSolution(t){return this.solutionUniqueName?{...t,headers:{...t?.headers,"MSCRM.SolutionUniqueName":this.solutionUniqueName}}:t}apiUrl(t){let r=this.instanceUrl.replace(/\/+$/,""),n=t.startsWith("/")?t:`/${t}`;return`${r}/${BB.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof oo.SdkError?n:new oo.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t),i=hw(t,r);return(0,mw.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,i)))}getAbsolute(t,r){this.assertSameOrigin(t);let n=hw(VB(t),r);return(0,mw.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 oo.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new oo.InvalidArgumentError(`Refusing to follow a cross-origin link ('${r.origin}' is not the configured instance '${n.origin}'); server-driven pagination must stay on-instance.`)}post(t,r,n){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.post(i,r,this.withSolution(n)))}get supportsAtomicBatch(){return typeof this.httpClient.postRaw=="function"}get solutionName(){return this.solutionUniqueName}postBatch(t,r,n){if(!this.httpClient.postRaw)throw new oo.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 oo.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 oo.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)))}};Ru.DataverseClient=Np});var vw=b(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.findColumns=Or.findTables=Or.readCheckColumns=Or.readColumnHints=Or.fetchEntityMetadataFromApi=void 0;var xu=we(),Ht=ae();function Pr(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}function ao(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 ku(e,t){return(await Lu(e,t)).rows}async function Lu(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 vr(e){return`/EntityDefinitions(LogicalName='${(0,Ht.odataPathLiteral)(e)}')`}async function GB(e,t,r){let n=await ku(e,`${vr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,Ht.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 WB(e){return`${vr(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,Ht.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function zB(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:Pr(a.Label),...ao(a.Label)?{localizedLabel:ao(a.Label)}:{}}}))}}function Dp(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:Pr(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function jB(e,t,r){var n;let i=u=>Lu(e,u).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([r.catch(()=>({rows:[],ok:!1})),...o.map(u=>i(`${vr(t)}/Attributes/Microsoft.Dynamics.CRM.${u}${(0,Ht.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`))]),s=new Map;for(let{rows:u}of a)for(let c of u)!((n=c.OptionSet)===null||n===void 0)&&n.Options&&s.set(c.LogicalName,c.OptionSet.Options.map(Dp));let l=await i(`${vr(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,Ht.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let u of l.rows){let c=u.OptionSet;c?.TrueOption&&c.FalseOption&&s.set(u.LogicalName,[Dp(c.FalseOption),Dp(c.TrueOption)])}return{byColumn:s,complete:l.ok&&a.every(u=>u.ok)}}async function HB(e,t,r){let{rows:n,ok:i}=await Lu(e,`${vr(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,Ht.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let o of n){let a=r.get(o.LogicalName);a&&o.Targets&&(a.targets=o.Targets)}return i}async function KB(e,t){var r,n,i,o;let a=[],s=await ku(e,`${vr(t)}/OneToManyRelationships${(0,Ht.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 ku(e,`${vr(t)}/ManyToOneRelationships${(0,Ht.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 ku(e,`${vr(t)}/ManyToManyRelationships${(0,Ht.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}async function JB(e,t){var r,n,i,o,a;let s=`${vr(t)}`+(0,Ht.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,xu.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(g=>{var v,w,C;return{logicalName:g.LogicalName,displayName:Pr(g.DisplayName),...ao(g.DisplayName)?{localizedDisplayName:ao(g.DisplayName)}:{},attributeType:(v=g.AttributeType)!==null&&v!==void 0?v:"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}:{},...Pr(g.Description)?{description:Pr(g.Description)}:{}}}),d=new Map(c.map(g=>[g.logicalName,g])),f=Lu(e,WB(t)),[,,p,m,h]=await Promise.all([GB(e,t,d),zB(f,d),jB(e,t,f),HB(e,t,d),KB(e,t)]);for(let g of c){let v=p.byColumn.get(g.logicalName);v&&(g.choices=v)}return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:Pr(u.DisplayName),...ao(u.DisplayName)?{localizedDisplayName:ao(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,...Pr(u.Description)?{description:Pr(u.Description)}:{},columnDetailComplete:p.complete&&m,attributes:c,relationships:h}}Or.fetchEntityMetadataFromApi=JB;var yw=40;async function _p(e,t,r,n){var i,o;let a=[...new Set(n.filter(l=>l!==""))],s=[];for(let l=0;l<a.length;l+=yw){let u=a.slice(l,l+yw).map(f=>`LogicalName eq '${(0,Ht.odataLiteral)(f)}'`).join(" or "),c=t+(0,Ht.odataQuery)([["$select",r],["$filter",u]]),d=(0,xu.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 QB(e,t,r){return(await _p(e,`${vr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName",r)).map(i=>{var o;let a=ao(i.DisplayName);return{logicalName:i.LogicalName,displayName:Pr(i.DisplayName),...a?{localizedDisplayName:a}:{},attributeType:(o=i.AttributeType)!==null&&o!==void 0?o:"Unknown"}})}Or.readColumnHints=QB;async function YB(e,t,r){let i=(await _p(e,`${vr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName,IsCustomAttribute",r)).map(s=>{var l;return{logicalName:s.LogicalName,displayName:Pr(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 _p(e,`${vr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata`,"LogicalName,MaxLength",[...o.keys()]);for(let s of a){let l=o.get(s.LogicalName);l&&typeof s.MaxLength=="number"&&(l.maxLength=s.MaxLength)}return i}Or.readCheckColumns=YB;async function XB(e,t,r){var n,i;let o=`/EntityDefinitions${(0,Ht.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,xu.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:Pr(c.DisplayName),entitySetName:(f=c.EntitySetName)!==null&&f!==void 0?f:"",isCustom:!!c.IsCustomEntity}}).filter(c=>c.logicalName.toLowerCase().includes(l)||c.schemaName.toLowerCase().includes(l)||c.displayName.toLowerCase().includes(l));return typeof r?.top=="number"?u.slice(0,r.top):u}Or.findTables=XB;async function ZB(e,t,r,n){var i,o;let a=`${vr(t)}/Attributes`+(0,Ht.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(o=(i=(0,xu.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[],u=(r??"").toLowerCase(),c=l.map(d=>{var f,p;return{logicalName:d.LogicalName,schemaName:(f=d.SchemaName)!==null&&f!==void 0?f:d.LogicalName,displayName:Pr(d.DisplayName),attributeType:(p=d.AttributeType)!==null&&p!==void 0?p:"Unknown",isCustom:!!d.IsCustomAttribute}}).filter(d=>d.logicalName.toLowerCase().includes(u)||d.schemaName.toLowerCase().includes(u)||d.displayName.toLowerCase().includes(u));return typeof n?.top=="number"?c.slice(0,n.top):c}Or.findColumns=ZB});var Pp=b(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.renderTypeRegistrations=Kt.buildGenPageLegacyEnums=Kt.renderGenPageAuthoringTypes=Kt.buildGenPageRuntimeTypes=Kt.toDesignerEntity=Kt.TABLE_LOGICAL_NAME=void 0;Kt.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function Ip(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var eU=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function Fu(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function Aw(e){var t,r;let n=e.choices;if(!n||n.length===0)return;let i=Fu(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 bw(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function Cw(e){return!eU.has(e.logicalName)&&(!e.attributeOf||Fu(e)==="image")&&e.isValidForRead!==!1}var ww=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function Ew(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(bw),i=e.attributes.filter(o=>!r.has(o.logicalName)).sort(bw);return[...n,...i]}function Tp(e){var t;let r=[],n=new Set,i=Ew(e);for(let o of i){let a=Fu(o),s=a==="image";Cw(o)&&(s&&o.attributeOf&&n.add(o.attributeOf),r.push({AttributeTypeName:a,IsReadOnly:!o.isValidForUpdate,LogicalName:o.logicalName,OptionSet:Aw(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))}}Kt.toDesignerEntity=Tp;function Sw(e,t="None"){let r={};for(let n of e)r[n.logicalName]=Tp(n);return _w(r,t)}Kt.buildGenPageRuntimeTypes=Sw;var Nw=`export interface TableRegistrations extends BaseTableRegistrations {
+`,Dw=`export interface EnumRegistrations extends BaseEnumRegistrations {
+`;function tU(e,t){return e.length>0?Sw(e,t).text:Tw(`${Nw}}
+`,`${Dw}}
+`,"","")}Kt.renderGenPageAuthoringTypes=tU;function rU(e){let t=new Set;for(let n of e)for(let i of Tp(n).Attributes)ww.has(i.AttributeTypeName)&&t.add(`${n.logicalName}_${i.LogicalName}`);let r=new Map;for(let n of e)for(let i of Ew(n)){let o=`${n.logicalName}_${i.logicalName}`,a=Aw(i);if(Cw(i)||!ww.has(Fu(i))||!a||t.has(o)||r.has(o))continue;let s={name:o,runtime:{},labels:new Map};r.set(o,{declaration:Iw(o,a,!1,s),model:s})}return r}Kt.buildGenPageLegacyEnums=rU;function _w(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=Nw,u=Dw,c="",d="";for(let f of o){s&&f.Description&&(c+=`// ${Ip(f.Description)}
+`),c+=`export type ${f.LogicalName} = TableRow<{
// Primary Key Column
- readonly ${p.PrimaryIdAttribute}: string,
-`,l+=` "${p.LogicalName}": ${p.LogicalName},
-`;for(let f of p.Attributes){if(f.LogicalName===p.PrimaryIdAttribute)continue;let m=`${f.IsReadOnly?" readonly ":""}${f.LogicalName}`,h=!0;switch(f.AttributeTypeName){case"string":case"memo":case"uniqueidentifier":case"entityname":m+=`: string,
+ readonly ${f.PrimaryIdAttribute}: string,
+`,l+=` "${f.LogicalName}": ${f.LogicalName},
+`;for(let p of f.Attributes){if(p.LogicalName===f.PrimaryIdAttribute)continue;let m=`${p.IsReadOnly?" readonly ":""}${p.LogicalName}`,h=!0;switch(p.AttributeTypeName){case"string":case"memo":case"uniqueidentifier":case"entityname":m+=`: string,
`;break;case"integer":case"double":case"decimal":case"money":case"bigint":m+=`: number,
`;break;case"datetime":m+=`: Date,
-`;break;case"customer":case"lookup":{let g=(r=f.Targets)!==null&&r!==void 0?r:f.AttributeTypeName==="customer"?["account","contact"]:void 0;if(!g||g.length===0){h=!1;break}m=` // Foreign Key Column
- ${f.IsReadOnly||g.every(w=>!e[w])?" readonly ":""}_${f.LogicalName}_value: `;let y="";for(let w of g)y+=`${y.length===0?"":" | "}\`/${w}(\${string})\``;m+=`${y},
-`;break}case"boolean":case"picklist":case"multiselectpicklist":case"state":case"status":{let g=`${p.LogicalName}_${f.LogicalName}`;m+=`: ${g},
-`;let y=(n=i.get(g))!==null&&n!==void 0?n:{name:g,runtime:{},labels:new Map};i.set(g,y),d+=$y(g,f.OptionSet,a,y),u+=` "${p.LogicalName}-${f.LogicalName}": ${g},
+`;break;case"customer":case"lookup":{let g=(r=p.Targets)!==null&&r!==void 0?r:p.AttributeTypeName==="customer"?["account","contact"]:void 0;if(!g||g.length===0){h=!1;break}m=` // Foreign Key Column
+ ${p.IsReadOnly||g.every(w=>!e[w])?" readonly ":""}_${p.LogicalName}_value: `;let v="";for(let w of g)v+=`${v.length===0?"":" | "}\`/${w}(\${string})\``;m+=`${v},
+`;break}case"boolean":case"picklist":case"multiselectpicklist":case"state":case"status":{let g=`${f.LogicalName}_${p.LogicalName}`;m+=`: ${g},
+`;let v=(n=i.get(g))!==null&&n!==void 0?n:{name:g,runtime:{},labels:new Map};i.set(g,v),d+=Iw(g,p.OptionSet,a,v),u+=` "${f.LogicalName}-${p.LogicalName}": ${g},
`;break}case"image":c+=` // This is an image encoded as a base64 string
`,m+=`: string,
-`;break;default:h=!1}h&&(s&&f.Description&&(c+=` // ${wp(f.Description)}
-`),a&&f.MaxLength&&(c+=" // Maximum length: "+f.MaxLength+`
+`;break;default:h=!1}h&&(s&&p.Description&&(c+=` // ${Ip(p.Description)}
+`),a&&p.MaxLength&&(c+=" // Maximum length: "+p.MaxLength+`
`),c+=` ${m}`)}c+=`}>
`}return l+=`}
`,u+=`}
-`,{text:Uy(l,u,c,d),enums:i}}Ot.renderTypeRegistrations=By;function $y(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: ${wp(a.color)}
+`,{text:Tw(l,u,c,d),enums:i}}Kt.renderTypeRegistrations=_w;function Iw(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: ${Ip(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 Uy(e,t,r,n){return`
+`}function Tw(e,t,r,n){return`
// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------
${e}
${t}
@@ -345,19 +345,23 @@ export interface GeneratedComponentProps {
dataApi: UxAgentDataApi;
pageInput?: PageInput;
}
-`}});var Gy=b($l=>{"use strict";Object.defineProperty($l,"__esModule",{value:!0});$l.generateGenPageRuntimeTypes=void 0;var Vy=Ep(),Oi=re(),qy=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),xi="generateGenPageRuntimeTypes";async function WF(e,t,r){let n=jF(t),i=HF(r),o=[];for(let a of n){let s=await e(a);if(s.columnDetailComplete!==!0)throw new Oi.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${xi}: the column metadata of data source '${a}' could not be read completely (a choice or lookup request failed), so its RuntimeTypes would lack enums a page can use. Retry.`);o.push(s)}return(0,Vy.renderGenPageAuthoringTypes)(o,i)}$l.generateGenPageRuntimeTypes=WF;function jF(e){if(!Array.isArray(e))throw new Oi.InvalidArgumentError(`${xi}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!Vy.TABLE_LOGICAL_NAME.test(r))throw new Oi.InvalidArgumentError(`${xi}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new Oi.InvalidArgumentError(`${xi}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function HF(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Oi.InvalidArgumentError(`${xi}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new Oi.InvalidArgumentError(`${xi}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!qy.has(r))throw new Oi.InvalidArgumentError(`${xi}: detail must be one of ${[...qy].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var Li=b(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});Ul.DEFAULT_LCID=void 0;Ul.DEFAULT_LCID=1033});var lt=b(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.assignMissingIds=zr.pointerTouchesValueMap=zr.isValueMapKey=zr.newId=void 0;var KF=wo();function zy(){return globalThis.crypto.randomUUID().toLowerCase()}zr.newId=zy;function JF(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Sp=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData"]);function QF(e){return Sp.has(e)}zr.isValueMapKey=QF;function XF(e){return KF.JsonPointer.parse(e).some(t=>Sp.has(t))}zr.pointerTouchesValueMap=XF;function YF(e){return Cp(e),e}zr.assignMissingIds=YF;function Cp(e){if(Array.isArray(e)){e.forEach(t=>Cp(t));return}if(JF(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=zy());for(let t of Object.keys(e))t==="id"||Sp.has(t)||Cp(e[t])}}});var ql=b(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.postChangeSet=ei.parseChangeSetStatuses=ei.renderChangeSet=void 0;var ki=re(),ZF=be(),Wy=lt(),es=ae();function jy(e,t){let r=`batch_${(0,Wy.newId)()}`,n=`changeset_${(0,Wy.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 ki.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 ki.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,es.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,es.assertNoControlChars)(s.etag,"batch operation etag");let p=Object.entries((c=s.headers)!==null&&c!==void 0?c:{});for(let[f,m]of p)if((0,es.assertNoControlChars)(f,"batch operation header name"),(0,es.assertNoControlChars)(m,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(f))throw new ki.InvalidArgumentError(`batch operation header name '${f}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,es.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}`]:[],...p.map(([f,m])=>`${f}: ${m}`),"",...d===void 0?[]:[d]].join(`\r
+`}});var Rw=b(Mu=>{"use strict";Object.defineProperty(Mu,"__esModule",{value:!0});Mu.generateGenPageRuntimeTypes=void 0;var Ow=Pp(),so=X(),Pw=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),lo="generateGenPageRuntimeTypes";async function nU(e,t,r){let n=iU(t),i=oU(r),o=[];for(let a of n){let s=await e(a);if(s.columnDetailComplete!==!0)throw new so.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${lo}: the column metadata of data source '${a}' could not be read completely (a choice or lookup request failed), so its RuntimeTypes would lack enums a page can use. Retry.`);o.push(s)}return(0,Ow.renderGenPageAuthoringTypes)(o,i)}Mu.generateGenPageRuntimeTypes=nU;function iU(e){if(!Array.isArray(e))throw new so.InvalidArgumentError(`${lo}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!Ow.TABLE_LOGICAL_NAME.test(r))throw new so.InvalidArgumentError(`${lo}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new so.InvalidArgumentError(`${lo}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function oU(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new so.InvalidArgumentError(`${lo}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new so.InvalidArgumentError(`${lo}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!Pw.has(r))throw new so.InvalidArgumentError(`${lo}: detail must be one of ${[...Pw].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var $w=b(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.getEnvironmentLanguages=uo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE=void 0;var aU=X(),Lw=we();uo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE="ENVIRONMENT_LANGUAGES_UNREADABLE";var kw="/organizations?$select=languagecode",sU="/RetrieveProvisionedLanguages()",lU="/RetrieveAvailableLanguages()";function Fw(e,t){return new aU.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 Mw(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}async function xw(e,t,r,n){let i=(0,Lw.ensureSuccess)(await e.get(t),e.apiUrl(t)).body,o=i?.[r];if(!Array.isArray(o)||o.length===0||!o.every(Mw))throw Fw(n,`answered no list of language codes in '${r}'`);return[...new Set(o)]}async function uU(e){var t;let r=(0,Lw.ensureSuccess)(await e.get(kw),e.apiUrl(kw)).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(!Mw(i))throw Fw("the organization read","did not answer one row with a language code");let o=await xw(e,sU,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages"),a=await xw(e,lU,"LocaleIds","RetrieveAvailableLanguages");return{baseLanguage:i,available:a,provisioned:o}}uo.getEnvironmentLanguages=uU});var sa=b(Wn=>{"use strict";function cU(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 Rp(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function dU(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 Bw=Rp({HTML:"text/html",isHTML:function(e){return e===Bw.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),Uw=Rp({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===Uw.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),$u=/[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]/,Op=new RegExp("[\\-\\.0-9"+$u.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),fU=new RegExp("^"+$u.source+Op.source+"*(?::"+$u.source+Op.source+"*)?$");Wn.assign=dU;Wn.find=cU;Wn.freeze=Rp;Wn.MIME_TYPE=Bw;Wn.NAMESPACE=Uw;Wn.nameStartChar=$u;Wn.nameChar=Op;Wn.tagNamePattern=fU});var Wp=b(Kn=>{var kp=sa(),mn=kp.find,Fs=kp.NAMESPACE,la=kp.tagNamePattern;function pU(e){return e!==""}function mU(e){return e?e.split(/[\t\n\f\r ]+/).filter(pU):[]}function hU(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function qw(e){if(!e)return[];var t=mU(e);return Object.keys(t.reduce(hU,{}))}function gU(e){return function(t){return e&&e.indexOf(t)!==-1}}function $s(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function Qt(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,$s(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Yt={},Rr=Yt.ELEMENT_NODE=1,ua=Yt.ATTRIBUTE_NODE=2,Ls=Yt.TEXT_NODE=3,Jw=Yt.CDATA_SECTION_NODE=4,Qw=Yt.ENTITY_REFERENCE_NODE=5,yU=Yt.ENTITY_NODE=6,xp=Yt.PROCESSING_INSTRUCTION_NODE=7,Lp=Yt.COMMENT_NODE=8,Yw=Yt.DOCUMENT_NODE=9,Xw=Yt.DOCUMENT_TYPE_NODE=10,zn=Yt.DOCUMENT_FRAGMENT_NODE=11,vU=Yt.NOTATION_NODE=12,Dt={},st={},Jte=Dt.INDEX_SIZE_ERR=(st[1]="Index size error",1),Qte=Dt.DOMSTRING_SIZE_ERR=(st[2]="DOMString size error",2),Jt=Dt.HIERARCHY_REQUEST_ERR=(st[3]="Hierarchy request error",3),Yte=Dt.WRONG_DOCUMENT_ERR=(st[4]="Wrong document",4),Vw=Dt.INVALID_CHARACTER_ERR=(st[5]="Invalid character",5),Xte=Dt.NO_DATA_ALLOWED_ERR=(st[6]="No data allowed",6),Zte=Dt.NO_MODIFICATION_ALLOWED_ERR=(st[7]="No modification allowed",7),Zw=Dt.NOT_FOUND_ERR=(st[8]="Not found",8),ere=Dt.NOT_SUPPORTED_ERR=(st[9]="Not supported",9),Gw=Dt.INUSE_ATTRIBUTE_ERR=(st[10]="Attribute in use",10),Jr=Dt.INVALID_STATE_ERR=(st[11]="Invalid state",11),tre=Dt.SYNTAX_ERR=(st[12]="Syntax error",12),rre=Dt.INVALID_MODIFICATION_ERR=(st[13]="Invalid modification",13),nre=Dt.NAMESPACE_ERR=(st[14]="Invalid namespace",14),ire=Dt.INVALID_ACCESS_ERR=(st[15]="Invalid access",15);function se(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,se);return r.code=e,t&&(this.message=this.message+": "+t),r}se.prototype=Error.prototype;$s(Dt,se);function jn(){}jn.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++)Gp(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 ca(e,t){this._node=e,this._refresh=t,Fp(this)}function Fp(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(fA(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];$s(r,e),e._inc=t}}ca.prototype.item=function(e){return Fp(this),this[e]||null};Qt(ca,jn);function Uu(){this._nameIndex=Object.create(null)}function eA(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function bU(e,t){e._nameIndex[t.nodeName]=t}function tA(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function Ww(e,t,r,n){if(n?(t[eA(t,n)]=r,tA(t,n)):t[t.length++]=r,bU(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&iA(i,e,n),wU(i,e,r))}}function zw(e,t,r){var n=eA(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,tA(t,r),e){var o=e.ownerDocument;o&&(iA(o,e,r),r.ownerElement=null)}}else throw new se(Zw,new Error(e.tagName+"@"+r))}Uu.prototype={length:0,item:jn.prototype.item,getNamedItem:function(e){for(var t=this.length;t--;){var r=this[t];if(r.nodeName==e)return r}},setNamedItem:function(e){var t=e.ownerElement;if(t&&t!=this._ownerElement)throw new se(Gw);var r=this._nameIndex[e.nodeName];return Ww(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new se(Gw);return r=this.getNamedItemNS(e.namespaceURI,e.localName),Ww(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return zw(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return zw(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 rA(){}rA.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new Bs;if(n.implementation=this,n.childNodes=new jn,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 zu;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function Ae(){}Ae.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(e,t){return Vu(this,e,t)},replaceChild:function(e,t){Vu(this,e,t,aA),t&&this.removeChild(t)},removeChild:function(e){return oA(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return dA(this.ownerDocument||this,this,e)},normalize:function(){at(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===Ls&&t.nodeType===Ls){for(var n=[],i=r;i!==null&&i.nodeType===Ls;)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("")),Wu(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==ua?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==ua?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function nA(e){return e=="<"&&"&lt;"||e==">"&&"&gt;"||e=="&"&&"&amp;"||e=='"'&&"&quot;"||"&#"+e.charCodeAt()+";"}$s(Yt,Ae);$s(Yt,Ae.prototype);function qu(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 Bs(){this.ownerDocument=this}function wU(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Fs.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function iA(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Fs.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Wu(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 oA(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,Wu(e.ownerDocument,e),t}function AU(e){return e&&(e.nodeType===Ae.DOCUMENT_NODE||e.nodeType===Ae.DOCUMENT_FRAGMENT_NODE||e.nodeType===Ae.ELEMENT_NODE)}function CU(e){return e&&(hn(e)||Mp(e)||Hn(e)||e.nodeType===Ae.DOCUMENT_FRAGMENT_NODE||e.nodeType===Ae.COMMENT_NODE||e.nodeType===Ae.PROCESSING_INSTRUCTION_NODE)}function Hn(e){return e&&e.nodeType===Ae.DOCUMENT_TYPE_NODE}function hn(e){return e&&e.nodeType===Ae.ELEMENT_NODE}function Mp(e){return e&&e.nodeType===Ae.TEXT_NODE}function jw(e,t){var r=e.childNodes||[];if(mn(r,hn)||Hn(t))return!1;var n=mn(r,Hn);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function Hw(e,t){var r=e.childNodes||[];function n(o){return hn(o)&&o!==t}if(mn(r,n))return!1;var i=mn(r,Hn);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function EU(e,t,r){if(!AU(e))throw new se(Jt,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new se(Zw,"child not in parent");if(!CU(t)||Hn(t)&&e.nodeType!==Ae.DOCUMENT_NODE)throw new se(Jt,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function SU(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===Ae.DOCUMENT_FRAGMENT_NODE){var o=i.filter(hn);if(o.length>1||mn(i,Mp))throw new se(Jt,"More than one element or text in fragment");if(o.length===1&&!jw(e,r))throw new se(Jt,"Element in fragment can not be inserted before doctype")}if(hn(t)&&!jw(e,r))throw new se(Jt,"Only one element can be added and only after doctype");if(Hn(t)){if(mn(n,Hn))throw new se(Jt,"Only one doctype is allowed");var a=mn(n,hn);if(r&&n.indexOf(a)<n.indexOf(r))throw new se(Jt,"Doctype can only be inserted before an element");if(!r&&a)throw new se(Jt,"Doctype can not be appended since element is present")}}function aA(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===Ae.DOCUMENT_FRAGMENT_NODE){var o=i.filter(hn);if(o.length>1||mn(i,Mp))throw new se(Jt,"More than one element or text in fragment");if(o.length===1&&!Hw(e,r))throw new se(Jt,"Element in fragment can not be inserted before doctype")}if(hn(t)&&!Hw(e,r))throw new se(Jt,"Only one element can be added and only after doctype");if(Hn(t)){let l=function(u){return Hn(u)&&u!==r};var s=l;if(mn(n,l))throw new se(Jt,"Only one doctype is allowed");var a=mn(n,hn);if(r&&n.indexOf(a)<n.indexOf(r))throw new se(Jt,"Doctype can only be inserted before an element")}}function Vu(e,t,r,n){EU(e,t,r),e.nodeType===Ae.DOCUMENT_NODE&&(n||SU)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===zn){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;Ms(o,l)}while(o!==a&&(o=o.nextSibling));return Wu(e.ownerDocument||e,e),t.nodeType==zn&&(t.firstChild=t.lastChild=null),t}function Ms(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===Rr&&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;)Ms(i,t),i=i.nextSibling}}function NU(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,Wu(e.ownerDocument,e,t);var r=e.ownerDocument||e;return Ms(t,r),t}Bs.prototype={nodeName:"#document",nodeType:Yw,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==zn){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return Vu(this,e,t),Ms(e,this),this.documentElement===null&&e.nodeType===Rr&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),oA(this,e)},replaceChild:function(e,t){Vu(this,e,t,aA),Ms(e,this),t&&this.removeChild(t),hn(e)&&(this.documentElement=e)},importNode:function(e,t){return DU(this,e,t)},getElementById:function(e){var t=null;return qu(this.documentElement,function(r){if(r.nodeType==Rr&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=qw(e);return new ca(this,function(r){var n=[];return t.length>0&&qu(r.documentElement,function(i){if(i!==r&&i.nodeType===Rr){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=qw(o);a=t.every(gU(s))}a&&n.push(i)}}}),n})},createElement:function(e){var t=new co;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new jn;var r=t.attributes=new Uu;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new ju;return e.ownerDocument=this,e.childNodes=new jn,e},createTextNode:function(e){var t=new $p;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new Bp;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new se(Vw,'data contains "]]>"');var t=new Up;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new Vp;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new Gu;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!la.test(e))throw new se(Vw,'not a valid xml name "'+e+'"');var t=new qp;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new co,n=t.split(":"),i=r.attributes=new Uu;return r.childNodes=new jn,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 Gu,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}};Qt(Bs,Ae);function co(){this._nsMap={}}co.prototype={nodeType:Rr,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===zn?this.insertBefore(e,null):NU(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 ca(this,function(t){var r=[];return qu(t,function(n){n!==t&&n.nodeType==Rr&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new ca(this,function(r){var n=[];return qu(r,function(i){i!==r&&i.nodeType===Rr&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};Bs.prototype.getElementsByTagName=co.prototype.getElementsByTagName;Bs.prototype.getElementsByTagNameNS=co.prototype.getElementsByTagNameNS;Qt(co,Ae);function Gu(){}Gu.prototype.nodeType=ua;Qt(Gu,Ae);function Us(){}Us.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[Jt])},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}};Qt(Us,Ae);function $p(){}$p.prototype={nodeName:"#text",nodeType:Ls,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}};Qt($p,Us);function Bp(){}Bp.prototype={nodeName:"#comment",nodeType:Lp};Qt(Bp,Us);function Up(){}Up.prototype={nodeName:"#cdata-section",nodeType:Jw};Qt(Up,Us);function zu(){}zu.prototype.nodeType=Xw;Qt(zu,Ae);function sA(){}sA.prototype.nodeType=vU;Qt(sA,Ae);function lA(){}lA.prototype.nodeType=yU;Qt(lA,Ae);function qp(){}qp.prototype.nodeType=Qw;Qt(qp,Ae);function ju(){}ju.prototype.nodeName="#document-fragment";ju.prototype.nodeType=zn;Qt(ju,Ae);function Vp(){}Vp.prototype.nodeType=xp;Qt(Vp,Ae);function uA(){}uA.prototype.serializeToString=function(e,t,r,n){return cA.call(e,t,r,n)};Ae.prototype.toString=cA;function cA(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 Gp(this,i,e,t,l,n),i.join("")}function Kw(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===Fs.XML||i===Fs.XMLNS)return!1;for(var o=r.length;o--;){var a=r[o];if(a.prefix===n)return a.namespace!==i}return!0}function Bu(e,t,r,n){if(n&&!la.test(t))throw new se(Jr,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,nA),'"')}function Gp(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 Rr:var c=a.attributes,d=c.length,f=a.tagName;u=Fs.isHTML(a.namespaceURI)||u;var p=f;if(!u&&!a.prefix&&a.namespaceURI){for(var m,h=0;h<c.length;h++)if(c.item(h).name==="xmlns"){m=c.item(h).value;break}if(!m)for(var g=l.length-1;g>=0;g--){var v=l[g];if(v.prefix===""&&v.namespace===a.namespaceURI){m=v.namespace;break}}if(m!==a.namespaceURI)for(var g=l.length-1;g>=0;g--){var v=l[g];if(v.namespace===a.namespaceURI){v.prefix&&(p=v.prefix+":"+f);break}}}if(o&&!la.test(p))throw new se(Jr,'The element name "'+p+'" is not a valid XML QName');t.push("<",p);for(var w=l.slice(),C=0;C<d;C++){var E=c.item(C);E.prefix=="xmlns"?w.push({prefix:E.localName,namespace:E.value}):E.nodeName=="xmlns"&&w.push({prefix:"",namespace:E.value})}for(var C=0;C<d;C++){var E=c.item(C);if(Kw(E,u,w)){var k=E.prefix||"",R=E.namespaceURI;Bu(t,k?"xmlns:"+k:"xmlns",R,o),w.push({prefix:k,namespace:R})}var T=n?n(E):E;T&&(typeof T=="string"?t.push(T):Bu(t,T.name,T.value,o))}if(f===p&&Kw(a,u,w)){var I=a.prefix||"",R=a.namespaceURI;Bu(t,I?"xmlns:"+I:"xmlns",R,o),w.push({prefix:I,namespace:R})}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):Gp(P,t,u,n,w.slice(),o),P=P.nextSibling;return t.push("</",f,">"),null}return{ns:w,isHTML:u,tag:p}}else return t.push("/>"),null;case Yw:case zn:return{ns:l.slice(),isHTML:u,tag:null};case ua:return Bu(t,a.name,a.value,o),null;case Ls:return t.push(a.data.replace(/[<&>]/g,nA)),null;case Jw:if(o&&a.data.indexOf("]]>")!==-1)throw new se(Jr,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case Lp:if(o&&a.data.indexOf("-->")!==-1)throw new se(Jr,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case Xw:if(o){if(!la.test(a.name))throw new se(Jr,'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 se(Jr,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new se(Jr,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new se(Jr,'DocumentType internalSubset contains "]>"')}var F=a.publicId,z=a.systemId;if(t.push("<!DOCTYPE ",a.name),F)t.push(" PUBLIC ",F),z&&z!="."&&t.push(" ",z),t.push(">");else if(z&&z!=".")t.push(" SYSTEM ",z,">");else{var Ie=a.internalSubset;Ie&&t.push(" [",Ie,"]"),t.push(">")}return null;case xp:if(o){if(!la.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new se(Jr,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new se(Jr,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case Qw:if(o&&!la.test(a.nodeName))throw new se(Jr,'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 DU(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===ua||r;return s?a:null}}),n}function dA(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 jn),a.ownerDocument=e;var u=r;switch(a.nodeType){case Rr:var c=i.attributes,d=a.attributes=new Uu,f=c.length;d._ownerElement=a;for(var p=0;p<f;p++)a.setAttributeNode(dA(e,c.item(p),!0));break;case ua:u=!0}return o!==null?o.appendChild(a):n=a,u?a:null}}),n}function fA(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(ca.prototype,"length",{get:function(){return Fp(this),this.$$length}}),Object.defineProperty(Ae.prototype,"textContent",{get:function(){if(this.nodeType===Rr||this.nodeType===zn){var e=[];return at(this,null,{enter:function(t){if(t.nodeType===Rr||t.nodeType===zn)return!0;if(t.nodeType===xp||t.nodeType===Lp)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case Rr:case zn: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}}}),fA=function(e,t,r){e["$$"+t]=r})}catch{}Kn.DocumentType=zu;Kn.DOMException=se;Kn.DOMImplementation=rA;Kn.Element=co;Kn.Node=Ae;Kn.NodeList=jn;Kn.walkDOM=at;Kn.XMLSerializer=uA});var mA=b(qs=>{"use strict";var pA=sa().freeze;qs.XML_ENTITIES=pA({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});qs.HTML_ENTITIES=pA({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"});qs.entityMap=qs.HTML_ENTITIES});var bA=b(jp=>{var Ws=sa().NAMESPACE,zp=sa().tagNamePattern,da=0,Ni=1,fa=2,Vs=3,pa=4,ma=5,Gs=6,Hu=7;function ha(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,ha)}ha.prototype=new Error;ha.prototype.name=ha.name;function yA(){}yA.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),OU(t,t={}),_U(e,t,r,n,this.errorHandler),n.endDocument()}};function _U(e,t,r,n,i){function o(ce){if(ce>65535){ce-=65536;var nt=55296+(ce>>10),to=56320+(ce&1023);return String.fromCharCode(nt,to)}else return String.fromCharCode(ce)}function a(ce){var nt=ce.slice(1,-1);return Object.hasOwnProperty.call(r,nt)?r[nt]:nt.charAt(0)==="#"?o(parseInt(nt.substr(1).replace("x","0x"))):(i.error("entity not found:"+ce),ce)}function s(ce){if(ce>h){var nt=e.substring(h,ce).replace(/&#?\w+;/g,a);f&&l(h),n.characters(nt,0,ce-h),h=ce}}function l(ce,nt){for(;ce>=c&&(nt=d.exec(e));)u=nt.index,c=u+nt[0].length,f.lineNumber++;f.columnNumber=ce-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,f=n.locator,p=[{currentNSMap:t}],m={},h=0;;){try{var g=e.indexOf("<",h);if(g<0){if(!e.substr(h).match(/^\s*$/)){var v=n.doc,w=v.createTextNode(e.substr(h));v.appendChild(w),n.currentElement=w}return}switch(g>h&&s(g),e.charAt(g+1)){case"/":var z=e.indexOf(">",g+3),C=e.substring(g+2,z).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),E=p.pop();z<0?(C=e.substring(g+2).replace(/[\s<].*/,""),i.error("end tag name: "+C+" is not complete:"+E.tagName),z=g+1+C.length):C.match(/\s</)?(C=C.replace(/[\s<].*/,""),i.error("end tag name: "+C+" maybe not complete"),z=g+1+C.length):/[ \t\n\r]/.test(C)&&zp.test(C.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+C+'"');var k=E.localNSMap,R=E.tagName==C,T=R||E.tagName&&E.tagName.toLowerCase()==C.toLowerCase();if(T){if(n.endElement(E.uri,E.localName,C),k)for(var I in k)Object.prototype.hasOwnProperty.call(k,I)&&n.endPrefixMapping(I);R||i.fatalError("end tag name: "+C+" is not match the current start tagName:"+E.tagName)}else p.push(E);z++;break;case"?":f&&l(g),z=kU(e,g,n);break;case"!":f&&l(g),z=RU(e,g,n,i);break;default:f&&l(g);var P=new vA,F=p[p.length-1].currentNSMap,z=IU(e,g,P,F,a,i),Ie=P.length;if(!P.closed&&PU(e,z,P.tagName,m)&&(P.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),f&&Ie){for(var yt=hA(f,{}),Te=0;Te<Ie;Te++){var Qe=P[Te];l(Qe.offset),Qe.locator=hA(f,{})}n.locator=yt,gA(P,n,F)&&p.push(P),n.locator=f}else gA(P,n,F)&&p.push(P);Ws.isHTML(P.uri)&&!P.closed?z=TU(e,z,P.tagName,a,n):z++}}catch(ce){if(ce instanceof ha)throw ce;i.error("element parse error: "+ce),z=-1}z>h?h=z:s(Math.max(g,h)+1)}}function hA(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function IU(e,t,r,n,i,o){function a(p,m,h){r.attributeNames.hasOwnProperty(p)&&o.fatalError("Attribute "+p+" redefined"),r.addValue(p,m.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),h)}for(var s,l,u=++t,c=da;;){var d=e.charAt(u);if(c===da&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===Ni)s=e.slice(t,u),c=Vs;else if(c===fa)c=Vs;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===Vs||c===Ni)if(c===Ni&&(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=ma;else throw new Error("attribute value no end '"+d+"' match");else if(c==pa)l=e.slice(t,u),a(s,l,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=ma;else throw new Error('attribute value must after "="');break;case"/":switch(c){case da:r.setTagName(e.slice(t,u));case ma:case Gs:case Hu:c=Hu,r.closed=!0;case pa:case Ni:break;case fa:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==da&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case da:r.setTagName(e.slice(t,u));case ma:case Gs:case Hu:break;case pa:case Ni:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case fa:c===fa&&(l=s),c==pa?(o.warning('attribute "'+l+'" missed quot(")!'),a(s,l,t)):((!Ws.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),a(l,l,t));break;case Vs:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case da:r.setTagName(e.slice(t,u)),c=Gs;break;case Ni:s=e.slice(t,u),c=fa;break;case pa:var l=e.slice(t,u);o.warning('attribute "'+l+'" missed quot(")!!'),a(s,l,t);case ma:c=Gs;break}else switch(c){case fa:var f=r.tagName;(!Ws.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=u,c=Ni;break;case ma:o.warning('attribute space is required"'+s+'"!!');case Gs:c=Ni,t=u;break;case Vs:c=pa,t=u;break;case Hu:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function gA(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=Ws.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var l=o.prefix;l&&(l==="xml"&&(o.uri=Ws.XML),l!=="xmlns"&&(o.uri=r[l||""]))}var f=n.indexOf(":");f>0?(l=e.prefix=n.slice(0,f),u=e.localName=n.slice(f+1)):(l=null,u=e.localName=n);var p=e.uri=r[l||""];if(t.startElement(p,u,n,e),e.closed){if(t.endElement(p,u,n),i)for(l in i)Object.prototype.hasOwnProperty.call(i,l)&&t.endPrefixMapping(l)}else return e.currentNSMap=r,e.localNSMap=i,!0}function TU(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 PU(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 OU(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function RU(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=xU(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 kU(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(!zp.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!zp.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 xU(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}jp.XMLReader=yA;jp.ParseError=ha});var DA=b(Ju=>{var LU=sa(),FU=Wp(),wA=mA(),EA=bA(),MU=FU.DOMImplementation,AA=LU.NAMESPACE,$U=EA.ParseError,BU=EA.XMLReader;function SA(e){return e.replace(/\r[\n\u0085]/g,`
+`).replace(/[\r\u0085\u2028]/g,`
+`)}function NA(e){this.options=e||{locator:{}}}NA.prototype.parseFromString=function(e,t){var r=this.options,n=new BU,i=r.domBuilder||new zs,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=UU(o,i,a),n.domBuilder=r.domBuilder||i,l&&(s[""]=AA.HTML),s.xml=s.xml||AA.XML;var c=r.normalizeLineEndings||SA;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function UU(e,t,r){if(!e){if(t instanceof zs)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+Hp(r))}||function(){}}return o("warning"),o("error"),o("fatalError"),n}function zs(){this.cdata=!1}function ga(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}zs.prototype={startDocument:function(){this.doc=new MU().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;Ku(this,o),this.currentElement=o,this.locator&&ga(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&&ga(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&&ga(this.locator,r),Ku(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=CA.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&&ga(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=CA.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&ga(this.locator,n),Ku(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&&ga(this.locator,i),Ku(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,Hp(this.locator))},error:function(e){console.error("[xmldom error] "+e,Hp(this.locator))},fatalError:function(e){throw new $U(e,this.locator)}};function Hp(e){if(e)return`
+@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function CA(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){zs.prototype[e]=function(){return null}});function Ku(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}Ju.__DOMHandler=zs;Ju.normalizeLineEndings=SA;Ju.DOMParser=NA});var ya=b(Qu=>{var _A=Wp();Qu.DOMImplementation=_A.DOMImplementation;Qu.XMLSerializer=_A.XMLSerializer;Qu.DOMParser=DA().DOMParser});var TA={};Ir(TA,{CCFControlConstants:()=>IA,CCFPropertyConstants:()=>Jp,CustomControlDataType:()=>M,CustomControlNames:()=>Jn,DefaultControlNameKeys:()=>Kp,ICCModeEnum:()=>Di,JSONParametersConstants:()=>Qp,LookUpType:()=>Yu,ManifestXMLConstants:()=>_t,NumberType:()=>Xu,Usage:()=>fo});var IA,Jp,Qp,_t,M,Kp,Jn,Di,fo,Yu,Xu,po=L(()=>{"use strict";IA={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"},Jp={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"},Qp={GroupDefinition:"GroupDefinition"},_t={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"})(M||(M={}));(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"})(Kp||(Kp={}));(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"})(Jn||(Jn={}));(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"})(Di||(Di={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(fo||(fo={}));Yu=[M.LookupCustomer,M.LookupOwner,M.LookupPartyList,M.LookupRegarding,M.LookupSimple],Xu=[M.WholeNone,M.WholeDuration,M.WholeLanguage,M.WholeTimeZone,M.FP,M.Decimal]});var va,$t,js=L(()=>{"use strict";va=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}},$t=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 PA={};Ir(PA,{AttributeDataSourceType:()=>Hs,AttributeDataSourceTypeMask:()=>Zu,AttributePrecisionSource:()=>Ks,EntityAttributeDataSourceType:()=>mo,EntityAttributeDateTimeBehavior:()=>Zp,EntityAttributeImeMode:()=>Xp,EntityAttributePrecisionSource:()=>em,EntityAttributeRequiredLevel:()=>_i,EntityAttributeType:()=>x,EntityAttributeTypeFormat:()=>G,EntityMetadataLookUpBase:()=>Qn,EntityResxKeyLookUp:()=>ec,SourceTypeMask:()=>Yp});var Qn,x,G,_i,mo,Yp,Hs,Zu,Xp,Zp,em,Ks,ec,ba=L(()=>{"use strict";js();Qn=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return ec.getDisplayNameResourceKey(this.name)}};(function(e){e.BigInt="BigIntType",e.CalendarRulesType="CalendarRulesType",e.Currency="MoneyType",e.Customer="Customer",e.CustomerType="CustomerType",e.DateTime="DateTimeType",e.DecimalNumber="DecimalType",e.EntityNameType="EntityNameType",e.FloatingPointNumber="DoubleType",e.Image="ImageType",e.File="FileType",e.Lookup="Lookup",e.LookupType="LookupType",e.ManagedPropertyType="ManagedPropertyType",e.MultipleLineofText="MemoType",e.MultiSelectOptionSet="MultiSelectPicklistType",e.OptionSet="PicklistType",e.Owner="Owner",e.OwnerType="OwnerType",e.PartyList="PartyList",e.PartyListType="PartyListType",e.PrimaryNameAttributeType="String",e.SingleLineofText="StringType",e.State="StateType",e.Status="StatusType",e.Subject="Subject",e.TimeStamp="TimeStampType",e.TwoOptions="BooleanType",e.UniqueIdentifier="Uniqueidentifier",e.UniqueIdentifierType="UniqueidentifierType",e.VirtualType="VirtualType",e.WholeNumber="IntegerType"})(x||(x={}));(function(e){e.Email="Email",e.Text="Text",e.TextArea="TextArea",e.Url="Url",e.TickerSymbol="TickerSymbol",e.PhoneticGuide="PhoneticGuide",e.VersionNumber="VersionNumber",e.Phone="Phone",e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale",e.DateOnly="DateOnly",e.DateAndTime="DateAndTime",e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean",e.Regarding="Regarding"})(G||(G={}));_i=class extends Qn{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},mo=class e extends Qn{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?Hs.Persistent:parseInt(Hs[this.name])}},Yp=class e extends Qn{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(Zu[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(Hs||(Hs={}));(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"})(Zu||(Zu={}));Xp=class e extends Qn{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"}},Zp=class e extends Qn{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"}},em=class e extends Qn{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?Ks.Currency:parseInt(Ks[this.name])}};(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(Ks||(Ks={}));ec=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new va;return t.add(x.TwoOptions,"SystemCustomization.type.bit.label"),t.add(x.Customer,"SystemCustomization.type.customer.label"),t.add(x.CustomerType,"SystemCustomization.type.customer.label"),t.add(x.DateTime,"SystemCustomization.type.datetime.label"),t.add(x.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add(x.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add(x.WholeNumber,"SystemCustomization.type.int.label"),t.add(x.LookupType,"SystemCustomization.type.lookup.label"),t.add(x.Lookup,"SystemCustomization.type.lookup.label"),t.add(x.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add(x.Currency,"SystemCustomization.type.money.label"),t.add(x.Owner,"SystemCustomization.type.owner.label"),t.add(x.OwnerType,"SystemCustomization.type.owner.label"),t.add(x.PartyList,"SystemCustomization.type.partylist.label"),t.add(x.PartyListType,"SystemCustomization.type.partylist.label"),t.add(x.OptionSet,"SystemCustomization.type.picklist.label"),t.add(x.State,"SystemCustomization.type.state.label"),t.add(x.Status,"SystemCustomization.type.status.label"),t.add(x.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add(x.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add(x.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add(x.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add(x.VirtualType,"SystemCustomization.type.virtual.label"),t.add(x.BigInt,"SystemCustomization.type.bigint.label"),t.add(x.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add(x.EntityNameType,"SystemCustomization.type.entityname.label"),t.add(x.Image,"SystemCustomization.type.image.label"),t.add(x.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add(x.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add(x.LookupType,"SystemCustomization.type.lookuptype.label"),t.add(x.Subject,"SystemCustomization.type.subject.label"),t.add(G.Email,"SystemCustomization.String.Format.email"),t.add(G.Text,"SystemCustomization.String.Format.text"),t.add(G.TextArea,"SystemCustomization.String.Format.textarea"),t.add(G.Url,"SystemCustomization.String.Format.url"),t.add(G.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(G.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(G.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(G.Phone,"SystemCustomization.String.Format.phone"),t.add(G.None,"SystemCustomization.Integer.Format."),t.add(G.Duration,"SystemCustomization.Integer.Format.duration"),t.add(G.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(G.Language,"SystemCustomization.Integer.Format.language"),t.add(G.Locale,"SystemCustomization.Integer.Format.language"),t.add(G.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(G.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(G.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(mo.Persistent,"SystemCustomization.String.Source.persistent"),t.add(mo.Calculated,"SystemCustomization.String.Source.calculated"),t.add(mo.Rollup,"SystemCustomization.String.Source.rollup"),t.add(mo.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var tm=b(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.parsePcfManifest=yn.manifestTypesForColumn=yn.DEFAULT_TYPE_GROUPS=void 0;var qU=ya(),W=(po(),hr(TA)),de=(ba(),hr(PA));yn.DEFAULT_TYPE_GROUPS={numbers:[W.CustomControlDataType.WholeNone,W.CustomControlDataType.FP,W.CustomControlDataType.Decimal,W.CustomControlDataType.Currency],text:[W.CustomControlDataType.SingleLineText,W.CustomControlDataType.SingleLineTextArea,W.CustomControlDataType.Multiple],lookup:[W.CustomControlDataType.LookupSimple,W.CustomControlDataType.LookupCustomer,W.CustomControlDataType.LookupOwner,W.CustomControlDataType.LookupPartyList,W.CustomControlDataType.LookupRegarding],dates:[W.CustomControlDataType.DateAndTimeDateOnly,W.CustomControlDataType.DateAndTimeDateAndTime],allFields:[W.CustomControlDataType.TwoOptions,W.CustomControlDataType.DateAndTimeDateOnly,W.CustomControlDataType.DateAndTimeDateAndTime,W.CustomControlDataType.FP,W.CustomControlDataType.Decimal,W.CustomControlDataType.WholeNone,W.CustomControlDataType.WholeDuration,W.CustomControlDataType.WholeTimeZone,W.CustomControlDataType.WholeLanguage,W.CustomControlDataType.LookupSimple,W.CustomControlDataType.LookupCustomer,W.CustomControlDataType.LookupOwner,W.CustomControlDataType.LookupPartyList,W.CustomControlDataType.LookupRegarding,W.CustomControlDataType.Multiple,W.CustomControlDataType.OptionSet,W.CustomControlDataType.SingleLineText,W.CustomControlDataType.SingleLineTextArea,W.CustomControlDataType.SingleLineEmail,W.CustomControlDataType.SingleLineURL,W.CustomControlDataType.SingleLineTickerSymbol,W.CustomControlDataType.SingleLinePhone]};var VU="Phone";function GU(e,t,r){switch(e){case de.EntityAttributeType.TwoOptions:return[W.CustomControlDataType.TwoOptions,W.CustomControlDataType.Boolean];case de.EntityAttributeType.Customer:case de.EntityAttributeType.CustomerType:return[W.CustomControlDataType.LookupCustomer];case de.EntityAttributeType.DateTime:return t===de.EntityAttributeTypeFormat.DateAndTime?[W.CustomControlDataType.DateAndTimeDateAndTime]:[W.CustomControlDataType.DateAndTimeDateOnly];case de.EntityAttributeType.DecimalNumber:return[W.CustomControlDataType.Decimal];case de.EntityAttributeType.FloatingPointNumber:return[W.CustomControlDataType.FP];case de.EntityAttributeType.File:return[W.CustomControlDataType.File];case de.EntityAttributeType.Image:return[W.CustomControlDataType.Image];case de.EntityAttributeType.WholeNumber:return t===de.EntityAttributeTypeFormat.Duration?[W.CustomControlDataType.WholeDuration]:t===de.EntityAttributeTypeFormat.Language?[W.CustomControlDataType.WholeLanguage]:t===de.EntityAttributeTypeFormat.TimeZone?[W.CustomControlDataType.WholeTimeZone]:[W.CustomControlDataType.WholeNone];case de.EntityAttributeType.LookupType:case de.EntityAttributeType.Lookup:return t===de.EntityAttributeTypeFormat.Regarding?[W.CustomControlDataType.LookupRegarding]:[W.CustomControlDataType.LookupSimple];case de.EntityAttributeType.MultipleLineofText:return[W.CustomControlDataType.Multiple];case de.EntityAttributeType.Currency:return[W.CustomControlDataType.Currency];case de.EntityAttributeType.Owner:case de.EntityAttributeType.OwnerType:return[W.CustomControlDataType.LookupOwner];case de.EntityAttributeType.PartyList:case de.EntityAttributeType.PartyListType:return[W.CustomControlDataType.LookupPartyList];case de.EntityAttributeType.Status:case de.EntityAttributeType.OptionSet:return[W.CustomControlDataType.OptionSet];case de.EntityAttributeType.SingleLineofText:switch(t){case de.EntityAttributeTypeFormat.Email:return[W.CustomControlDataType.SingleLineEmail];case de.EntityAttributeTypeFormat.Phone:return[W.CustomControlDataType.SingleLinePhone];case de.EntityAttributeTypeFormat.Text:return r===VU?[W.CustomControlDataType.SingleLinePhone]:[W.CustomControlDataType.SingleLineText];case de.EntityAttributeTypeFormat.TextArea:return[W.CustomControlDataType.SingleLineTextArea];case de.EntityAttributeTypeFormat.TickerSymbol:return[W.CustomControlDataType.SingleLineTickerSymbol];case de.EntityAttributeTypeFormat.Url:return[W.CustomControlDataType.SingleLineURL];default:return[W.CustomControlDataType.SingleLineText]}case de.EntityAttributeType.MultiSelectOptionSet:return[W.CustomControlDataType.MultiSelectOptionSet];default:return null}}yn.manifestTypesForColumn=GU;function OA(e){let t=[],r=e.childNodes;for(let n=0;n<r.length;n+=1)r[n].nodeType===1&&t.push(r[n]);return t}function gn(e,t){return e.hasAttribute(t)?e.getAttribute(t):null}function Yn(e,...t){return OA(e).filter(r=>t.includes(r.tagName))}function WU(e){let t=new Map;for(let r of Yn(e,"type-group"))t.set(String(gn(r,"name")),Yn(r,"type").map(n=>String(n.textContent)));for(let[r,n]of t)t.set(r,n.sort());return t}function zU(e){let t=e.getElementsByTagName("AvailableOn")[0];if(!t)return{web:!0,phone:!0,tablet:!0};let r=new Set(OA(t).map(n=>n.tagName));return{web:r.has("web"),phone:r.has("phone"),tablet:r.has("tablet")}}var jU={input:"input",bound:"bound",output:"output"};function HU(e,t,r){let n=gn(e,"usage"),i=n!==null&&jU[n]||"input",o=gn(e,"default-value"),a=Yn(e,"value").map(p=>{let m={name:gn(p,"name"),value:String(p.textContent),isDefault:gn(p,"default")==="true"};return m.isDefault&&(o=m.value),m}),s=gn(e,"of-type-group"),l=s!==null?t.get(s):void 0,u=s!==null&&Object.prototype.hasOwnProperty.call(yn.DEFAULT_TYPE_GROUPS,s)?yn.DEFAULT_TYPE_GROUPS[s]:void 0,c=l?[...l]:u?[...u]:[],d=gn(e,"of-type"),f=d!==null?d:c.length>0?c[0]:null;return{name:gn(e,"name"),usage:i,ofType:d,typeGroupName:s,ofTypeGroup:c,defaultType:f||void 0,required:gn(e,"required")==="true",hidden:gn(e,"hidden")==="true",defaultValue:o,enumValues:a,isPrimary:r&&i==="bound"}}function KU(e){var t;let r=[],n=m=>h=>r.push(`${m}: ${h}`),i=new qU.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the control manifest does not parse cleanly${r.length>0?` (${r[0]})`:""}`);let a=Yn(o,"control")[0];if(!a)throw new Error("the control manifest has no <control> element");let s=WU(a),l=Yn(a,"data-set"),u=Yn(a,"property"),c=Yn(a,"groups"),d=[],f=!1;for(let m of u){let h=HU(m,s,l.length===0&&!f);f=f||h.isPrimary,d.push(h)}let p=l.length>0||(d.length>0?d[0].usage==="bound":c.some(m=>Yn(m,"group").some(h=>Yn(h,"data-set","property").length>0)));return{properties:d,hasDataset:l.length>0,hasGroups:c.length>0,isBound:p,availableOn:zU(a)}}yn.parsePcfManifest=KU});var kA=b(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.readPcfColumn=Aa.readControlManifest=void 0;var wa=ae(),JU=tm();function rm(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 QU(e,t){var r,n;let i="/customcontrols"+(0,wa.odataQuery)([["$select","name,manifest"],["$filter",`name eq '${(0,wa.odataLiteral)(t)}'`]]);try{let o=await e.get(i);if(o.status<200||o.status>=300)return{kind:"unavailable",error:rm(`reading control "${t}"`,o.status,o.body)};let a=((n=(r=o.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(l=>l!==null&&typeof l=="object");if(a.length===0)return{kind:"missing"};if(a.length>1)return{kind:"ambiguous"};let s=a[0].manifest;return typeof s!="string"?{kind:"unavailable",error:new Error(`control "${t}" has no manifest`)}:{kind:"found",value:(0,JU.parsePcfManifest)(s)}}catch(o){return{kind:"unavailable",error:o instanceof Error?o:new Error(String(o))}}}Aa.readControlManifest=QU;var YU=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 RA(e){let t=e?.Value;return typeof t=="string"?t:void 0}async function XU(e,t,r,n){var i,o;let a=`/EntityDefinitions(LogicalName='${(0,wa.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,wa.odataPathLiteral)(r)}')`,s=n?.requireCreateEligibility===!0;try{let l=await e.get(a+(0,wa.odataQuery)([["$select",`LogicalName,AttributeType,AttributeTypeName,IsValidForForm,IsPrimaryId${s?",IsValidForCreate":""}`]]));if(l.status===404)return{kind:"missing"};if(l.status<200||l.status>=300)return{kind:"unavailable",error:rm(`reading column "${r}"`,l.status,l.body)};let u=(i=l.body)!==null&&i!==void 0?i:{},c=RA(u.AttributeTypeName);if(!c)return{kind:"unavailable",error:new Error(`column "${r}" has no AttributeTypeName`)};if(s&&typeof u.IsValidForCreate!="boolean")return{kind:"unavailable",error:new Error(`column "${r}" has no IsValidForCreate`)};let d={logicalName:typeof u.LogicalName=="string"?u.LogicalName:r,attributeTypeName:c,isValidForForm:u.IsValidForForm===!0,isPrimaryId:u.IsPrimaryId===!0,...s?{isValidForCreate:u.IsValidForCreate}:{}},f=YU.get(c);if(f){let p=await e.get(`${a}/Microsoft.Dynamics.CRM.${f.cast}`+(0,wa.odataQuery)([["$select",f.select]]));if(p.status<200||p.status>=300)return{kind:"unavailable",error:rm(`reading the format of column "${r}"`,p.status,p.body)};let m=(o=p.body)!==null&&o!==void 0?o:{};typeof m.Format=="string"&&(d.format=m.Format);let h=RA(m.FormatName);h&&(d.formatName=h)}return{kind:"found",value:d}}catch(l){return{kind:"unavailable",error:l instanceof Error?l:new Error(String(l))}}}Aa.readPcfColumn=XU});var ho=b(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.DEFAULT_LCID=void 0;tc.DEFAULT_LCID=1033});var lt=b(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.assignMissingIds=vn.pointerTouchesValueMap=vn.isValueMapKey=vn.newId=void 0;var ZU=ra();function xA(){return globalThis.crypto.randomUUID().toLowerCase()}vn.newId=xA;function eq(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var im=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData","customControl"]);function tq(e){return im.has(e)}vn.isValueMapKey=tq;function rq(e){return ZU.JsonPointer.parse(e).some(t=>im.has(t))}vn.pointerTouchesValueMap=rq;function nq(e){return nm(e),e}vn.assignMissingIds=nq;function nm(e){if(Array.isArray(e)){e.forEach(t=>nm(t));return}if(eq(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=xA());for(let t of Object.keys(e))t==="id"||im.has(t)||nm(e[t])}}});var Qs=b(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.sendChangeSet=Xt.partResponse=Xt.postChangeSet=Xt.parseChangeSetParts=Xt.parseChangeSetStatuses=Xt.renderChangeSet=void 0;var Ii=X(),om=we(),LA=lt(),Js=ae();function am(e,t){let r=`batch_${(0,LA.newId)()}`,n=`changeset_${(0,LA.newId)()}`,i=t.map((s,l)=>String(l+1)),o=t.map((s,l)=>{var u,c;if(s.rawBody!==void 0&&s.contentType===void 0)throw new Ii.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a raw body but no Content-Type`);let d=(u=s.rawBody)!==null&&u!==void 0?u:s.body===void 0?void 0:JSON.stringify(s.body);if(d!==void 0&&(d.includes(`--${n}`)||d.includes(`--${r}`)))throw new Ii.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,Js.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,Js.assertNoControlChars)(s.etag,"batch operation etag");let f=Object.entries((c=s.headers)!==null&&c!==void 0?c:{});for(let[p,m]of f)if((0,Js.assertNoControlChars)(p,"batch operation header name"),(0,Js.assertNoControlChars)(m,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(p))throw new Ii.InvalidArgumentError(`batch operation header name '${p}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,Js.assertNoControlChars)(s.contentType,"batch operation content type"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...d===void 0?[]:[`Content-Type: ${s.rawBody!==void 0?s.contentType:"application/json;type=entry"}`],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],...f.map(([p,m])=>`${p}: ${m}`),"",...d===void 0?[]:[d]].join(`\r
`)});return{body:[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...o,`--${n}--`,`--${r}--`,""].join(`\r
-`),batchId:r,contentIds:i}}ei.renderChangeSet=jy;function Hy(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 p of l.slice(1)){if(p.startsWith("--"))break;let f=p.indexOf(`\r
+`),batchId:r,contentIds:i}}Xt.renderChangeSet=am;function FA(e,t){var r;return(r=sm(e,t))===null||r===void 0?void 0:r.map(n=>n.status)}Xt.parseChangeSetStatuses=FA;function sm(e,t){var r,n,i,o;if(typeof e!="string"||e.length===0)return;let a=(r=/^--(\S+)\r?\n/.exec(e))===null||r===void 0?void 0:r[1];if(a===void 0||!e.trimEnd().endsWith(`--${a}--`))return;let s=(n=/Content-Type:\s*multipart\/mixed;\s*boundary=(\S+)/i.exec(e))===null||n===void 0?void 0:n[1];if(s===void 0||s===a)return;let l=e.split(`--${s}`);if(l.length<2||!/^--(\r?\n|$)/.test(l[l.length-1]))return;let u=new Set(t),c=[],d=new Set;for(let f of l.slice(1)){if(f.startsWith("--"))break;let p=f.indexOf(`\r
\r
-`);if(f===-1)return;let m=p.slice(0,f),h=p.slice(f+4);if(!/^Content-Type:\s*application\/http\b/im.test(m))return;let g=/^HTTP\/1\.[01] (\d{3})\b/.exec(h);if(!g||((i=h.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let y=(o=/^Content-ID:\s*(\S+)/im.exec(m))===null||o===void 0?void 0:o[1];if(y===void 0||d.has(y)||!u.has(y))return;d.add(y),c.push(Number(g[1]))}return c.length===0?void 0:c}ei.parseChangeSetStatuses=Hy;async function eM(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:o}=jy(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,ZF.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new ki.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=Hy(a.body,o);if(l===void 0)throw new ki.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 ki.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 ki.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}ei.postChangeSet=eM});var Vl=b(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.updateTable=Y.deleteAlternateKey=Y.createAlternateKey=Y.deleteGlobalOptionSet=Y.createGlobalOptionSet=Y.deleteRelationship=Y.deleteColumn=Y.updateColumn=Y.deleteTable=Y.createRelationship=Y.insertStatusValue=Y.createCustomerColumn=Y.createColumns=Y.setColumnVisualization=Y.getColumnVisualization=Y.createColumn=Y.createTable=Y.resolveEntitySetName=Y.pluralFallback=void 0;var pe=be(),J=ae(),Wr=Li(),we=re(),tM=ql(),rM={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 xe(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:nM(e,t)}}var Ky=65535;function nM(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 we.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 we.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>Ky)throw new we.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${Ky})`);if(i.has(s))throw new we.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new we.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(a,s)})}function Yy(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new we.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}Y.pluralFallback=Yy;function ts(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}function _p(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function Jy(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function rs(e){let t=(0,pe.readCreatedId)(e,"MetadataId");if(!t)throw new we.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function iM(e,t,r){var n,i,o,a,s,l,u,c,d,p,f,m,h,g,y,w,C,S,T,O,k,F,P,q;if(t.defaultValue!==void 0&&e!=="boolean")throw new we.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new we.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:(p=t.precision)!==null&&p!==void 0?p:2,MinValue:(f=t.minValue)!==null&&f!==void 0?f:-1e11,MaxValue:(m=t.maxValue)!==null&&m!==void 0?m:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(h=t.precision)!==null&&h!==void 0?h:2,PrecisionSource:2,MinValue:(g=t.minValue)!==null&&g!==void 0?g:0,MaxValue:(y=t.maxValue)!==null&&y!==void 0?y:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(w=t.defaultValue)!==null&&w!==void 0?w:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:xe((C=t.trueLabel)!==null&&C!==void 0?C:"Yes",r)},FalseOption:{Value:0,Label:xe((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:(T=t.dateFormat)!==null&&T!==void 0?T:"DateAndTime"};case"choice":return Qy(t,r,!1);case"multiChoice":return Qy(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(O=t.maxSizeKb)!==null&&O!==void 0?O:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(k=t.isPrimaryImage)!==null&&k!==void 0?k:!1,MaxSizeInKB:(F=t.maxSizeKb)!==null&&F!==void 0?F:10240};case"autonumber":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(P=t.maxLength)!==null&&P!==void 0?P:100,AutoNumberFormat:(q=t.autoNumberFormat)!==null&&q!==void 0?q:""};default:throw new we.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function Qy(e,t,r){let i={"@odata.type":r?"Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata":"Microsoft.Dynamics.CRM.PicklistAttributeMetadata",AttributeType:r?"Virtual":"Picklist",AttributeTypeName:{Value:r?"MultiSelectPicklistType":"PicklistType"}};if(e.globalChoiceMetadataId)return i["[email protected]"]=`/GlobalOptionSetDefinitions(${(0,J.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new we.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:xe(o.label,t)}))},i}var Np=new WeakMap;async function oM(e,t){var r,n;let i=(r=Np.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let o=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')${(0,J.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,pe.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new we.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,J.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=Np.get(e);return l||(l=new Map,Np.set(e,l)),l.set(t,s),s}Y.resolveEntitySetName=oM;async function aM(e,t){var r,n,i,o,a,s,l,u,c,d,p,f,m,h,g;let y=(r=t.languageCode)!==null&&r!==void 0?r:Wr.DEFAULT_LCID,w=_p(t.schemaName),C=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${w}_Name`,S={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:C,RequiredLevel:ts("None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:xe((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",y),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(S.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&tb(t.columns,"createTable");let T={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:xe(t.displayName,y),DisplayCollectionName:xe((a=t.pluralName)!==null&&a!==void 0?a:Yy(t.displayName),y),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:[S,...((c=t.columns)!==null&&c!==void 0?c:[]).map(Je=>Ip(Je,y))]};t.description&&(T.Description=xe(t.description,y));let O="/EntityDefinitions",k=(0,pe.ensureSuccess)(await e.post(O,T),e.apiUrl(O)),F=rs(k),P=`/EntityDefinitions(${F})`+(0,J.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),q=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),V=Math.max(0,(p=t.readBackDelayMs)!==null&&p!==void 0?p:1e3),Ve;for(let Je=1;Je<=q;Je+=1){let Ge=await e.get(P);if(Ge.status>=200&&Ge.status<300){Ve=Ge;break}Ge.status!==404&&(0,pe.ensureSuccess)(Ge,e.apiUrl(P)),Je<q&&V>0&&await new Promise(Z=>setTimeout(Z,V))}if(!Ve)throw new we.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${F}) but its metadata was still not readable after ${q} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${F}) once the environment catches up, or raise 'readBackAttempts'.`);let Pt=Ve.body;return{logicalName:(f=Pt.LogicalName)!==null&&f!==void 0?f:t.schemaName.toLowerCase(),metadataId:F,entitySetName:(m=Pt.EntitySetName)!==null&&m!==void 0?m:"",primaryIdAttribute:(h=Pt.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=Pt.PrimaryNameAttribute)!==null&&g!==void 0?g:C.toLowerCase()}}Y.createTable=aM;function Ip(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,o={...iM(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:ts((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:xe(e.displayName,i)};return e.description&&(o.Description=xe(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),Zy(o,e),o}function Zy(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 sM(e,t,r){var n;let i=Ip(r,(n=r.languageCode)!==null&&n!==void 0?n:Wr.DEFAULT_LCID),o=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`,a=(0,pe.ensureSuccess)(await e.post(o,i),e.apiUrl(o)),s={logicalName:r.schemaName.toLowerCase(),metadataId:rs(a)};if(r.visualization&&r.visualization!=="None")try{await ib(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new we.SdkError("COLUMN_VISUALIZATION_BIND_FAILED",`Column '${s.logicalName}' on '${t}' was created, but binding its '${r.visualization}' grid visualization failed; the column exists WITHOUT a visualization. Retry with setColumnVisualization('${t}', '${s.logicalName}', '${r.visualization}'). Cause: ${l instanceof Error?l.message:String(l)}`);throw u.cause=l,u}return s}Y.createColumn=sM;var No="/controlconfigurations",eb="CustomRenderersConfiguration",Dp={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 tb(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new we.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 rb(e){return JSON.stringify({type:Dp[e]})}function lM(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(Dp).find(i=>Dp[i]===r);return n??"None"}async function nb(e,t,r){var n,i;let o=`entitylogicalname eq '${(0,J.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,J.odataLiteral)(r)}'`,a=`${No}${(0,J.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",o]])}`,l=(i=(n=(0,pe.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,p;return((p=(d=c.Attribute)===null||d===void 0?void 0:d.logicalname)===null||p===void 0?void 0:p.toLowerCase())===u})}async function uM(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,J.odataPathLiteral)(r)}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,a=(n=(0,pe.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!a)throw new we.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,J.normalizeGuid)(a,"MetadataId")}async function ib(e,t,r,n,i){let o={name:eb,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:rb(i),"[email protected]":`/attributes(${(0,J.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,pe.ensureSuccess)(await e.post(No,o),e.apiUrl(No))}async function cM(e,t,r){var n;let i=await nb(e,t,r);return lM((n=i[0])===null||n===void 0?void 0:n.metadatajson)}Y.getColumnVisualization=cM;async function dM(e,t,r,n){let o=(await nb(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of o){let c=`${No}(${(0,J.normalizeGuid)(u,"controlconfigurationid")})`;(0,pe.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,l=await uM(e,t,r);if(a){let u=`${No}(${(0,J.normalizeGuid)(a,"controlconfigurationid")})`,c={name:eb,metadatajson:rb(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,pe.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await ib(e,t,r,l,n);for(let u of s){let c=`${No}(${(0,J.normalizeGuid)(u,"controlconfigurationid")})`;(0,pe.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}Y.setColumnVisualization=dM;async function pM(e,t,r){if(r.length===0)return;if(tb(r,"createColumns"),!e.supportsAtomicBatch)throw new we.InvalidArgumentError(`createColumns writes ${r.length} columns on '${t}' as ONE atomic change set, which needs a verbatim request body. Implement HttpClient.postRaw, or call createColumn per column and accept that a failure can leave the table partly extended.`);let n=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`;await(0,tM.postChangeSet)(e,r.map(i=>{var o;return{method:"POST",path:n,body:Ip(i,(o=i.languageCode)!==null&&o!==void 0?o:Wr.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}Y.createColumns=pM;async function fM(e,t,r){var n,i,o,a;let s=(n=r.languageCode)!==null&&n!==void 0?n:Wr.DEFAULT_LCID,l=_p(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:xe(r.displayName,s),RequiredLevel:ts((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,pe.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}Y.createCustomerColumn=fM;async function mM(e,t,r){var n,i,o,a,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:Wr.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:xe(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,pe.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)}Y.insertStatusValue=mM;async function hM(e,t){var r,n,i,o,a;let s=(r=t.languageCode)!==null&&r!==void 0?r:Wr.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new we.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let p=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${_p(t.schemaName)}_${t.referencedEntity}Id`;u=p.toLowerCase(),l={"@odata.type":"Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata",SchemaName:t.schemaName,ReferencedEntity:t.referencedEntity,ReferencingEntity:t.referencingEntity,Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.LookupAttributeMetadata",AttributeType:"Lookup",AttributeTypeName:{Value:"LookupType"},SchemaName:p,RequiredLevel:ts((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:xe((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new we.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,pe.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:rs(d),lookupLogicalName:u}}Y.createRelationship=hM;async function gM(e,t){let r=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')`;(0,pe.ensureSuccess)(await e.delete(r),e.apiUrl(r))}Y.deleteTable=gM;async function vM(e,t,r,n){var i,o;let a=(i=n.languageCode)!==null&&i!==void 0?i:Wr.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,J.odataPathLiteral)(r)}')${(0,J.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,pe.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=rM[(o=c.AttributeType)!==null&&o!==void 0?o:""];if(!c.MetadataId||!d)throw new we.InvalidArgumentError(`cannot update column '${r}' on '${t}' (type '${c.AttributeType}' not supported)`);let p=(0,J.normalizeGuid)(c.MetadataId,"MetadataId"),f=`${s}(${p})/${d}`,m=(0,pe.ensureSuccess)(await e.get(f),e.apiUrl(f)).body;for(let g of Object.keys(m))g.startsWith("@odata.")&&delete m[g];if(m["@odata.type"]=d,n.displayName!==void 0&&(m.DisplayName=xe(n.displayName,a)),n.description!==void 0&&(m.Description=xe(n.description,a)),n.required!==void 0&&(m.RequiredLevel=ts(n.required)),n.maxLength!==void 0&&(m.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(m.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new we.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 we.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(m.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(m.Format=n.integerFormat),Zy(m,n);let h=`${s}(${p})`;(0,pe.ensureSuccess)(await e.put(h,m,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}Y.updateColumn=vM;async function yM(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Attributes`,o=`${i}(LogicalName='${(0,J.odataPathLiteral)(r)}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,pe.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new we.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,pe.ensureSuccess)(await e.delete(l),e.apiUrl(l))}Y.deleteColumn=yM;async function bM(e,t){var r,n,i;let o=`/RelationshipDefinitions${(0,J.odataQuery)([["$filter",`SchemaName eq '${(0,J.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(n=(r=(0,pe.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 we.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,pe.ensureSuccess)(await e.delete(l),e.apiUrl(l))}Y.deleteRelationship=bM;async function Xy(e,t){var r;let n=`/GlobalOptionSetDefinitions(Name='${(0,J.odataPathLiteral)(t)}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(n);if(i.status===404)return;let a=(r=(0,pe.ensureSuccess)(i,e.apiUrl(n)).body)===null||r===void 0?void 0:r.MetadataId;return a?(0,J.normalizeGuid)(a,"MetadataId"):void 0}async function wM(e,t){var r;let n=t.name.toLowerCase(),i=await Xy(e,n);if(i)return{name:n,metadataId:i};let o=(r=t.languageCode)!==null&&r!==void 0?r:Wr.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:xe(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:xe(l.label,o)}))};t.description&&(a.Description=xe(t.description,o));let s="/GlobalOptionSetDefinitions";try{let l=(0,pe.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:n,metadataId:rs(l)}}catch(l){let u;try{u=await Xy(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}Y.createGlobalOptionSet=wM;async function AM(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,J.odataPathLiteral)(t.toLowerCase())}')`;(0,pe.ensureSuccess)(await e.delete(r),e.apiUrl(r))}Y.deleteGlobalOptionSet=AM;async function EM(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Wr.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:xe(r.displayName,i),KeyAttributes:r.keyAttributes},a=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Keys`,s=(0,pe.ensureSuccess)(await e.post(a,o),e.apiUrl(a));return{logicalName:r.schemaName.toLowerCase(),metadataId:rs(s)}}Y.createAlternateKey=EM;async function CM(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')/Keys`,o=`${i}(LogicalName='${(0,J.odataPathLiteral)(r.toLowerCase())}')${(0,J.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,pe.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new we.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,J.normalizeGuid)(s,"MetadataId")})`;(0,pe.ensureSuccess)(await e.delete(l),e.apiUrl(l))}Y.deleteAlternateKey=CM;async function SM(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Wr.DEFAULT_LCID,o=`/EntityDefinitions(LogicalName='${(0,J.odataPathLiteral)(t)}')`,s=(0,pe.ensureSuccess)(await e.get(o),e.apiUrl(o)).body,l=s.MetadataId;if(!l)throw new we.InvalidArgumentError(`table '${t}' not found`);let u=(0,J.normalizeGuid)(l,"MetadataId");for(let d of Object.keys(s))d.startsWith("@odata.")&&delete s[d];s["@odata.type"]="Microsoft.Dynamics.CRM.EntityMetadata",r.displayName!==void 0&&(s.DisplayName=xe(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=xe(r.pluralName,i)),r.description!==void 0&&(s.Description=xe(r.description,i)),r.auditEnabled!==void 0&&Jy(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&Jy(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,pe.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}Y.updateTable=SM});var ri=b(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.rebuildRaw=xt.assembleChildren=xt.spliceChildren=xt.mergeAttrs=xt.rawFromNode=xt.emptyBag=void 0;var ti=re(),ob=1e6,zl=512;function NM(){return{a:[],c:[]}}xt.emptyBag=NM;function ab(e,t=0){if(t>zl)throw new ti.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${zl}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>ab(r,t+1))}}xt.rawFromNode=ab;function DM(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}xt.mergeAttrs=DM;function Gl(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>ob)throw new ti.InvalidArgumentError(`Bag child index must be an integer in [0, ${ob}] (got ${String(l)})`);if(r.has(l))throw new ti.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}xt.spliceChildren=Gl;function _M(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:Gl(e.w.c,t)};return Gl(e.c,[r])}return Gl(e.c,t)}xt.assembleChildren=_M;function sb(e,t,r,n=0){if(n>zl)throw new ti.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${zl}`);IM(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,sb(o,t,i,n+1));return i}xt.rebuildRaw=sb;function IM(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new ti.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new ti.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 ti.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 ti.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var Do=b(wn=>{"use strict";function TM(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 Pp(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function PM(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 lb=Pp({HTML:"text/html",isHTML:function(e){return e===lb.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),ub=Pp({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===ub.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),Wl=/[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]/,Tp=new RegExp("[\\-\\.0-9"+Wl.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),RM=new RegExp("^"+Wl.source+Tp.source+"*(?::"+Wl.source+Tp.source+"*)?$");wn.assign=PM;wn.find=TM;wn.freeze=Pp;wn.MIME_TYPE=lb;wn.NAMESPACE=ub;wn.nameStartChar=Wl;wn.nameChar=Tp;wn.tagNamePattern=RM});var Vp=b(Sn=>{var Rp=Do(),jr=Rp.find,is=Rp.NAMESPACE,_o=Rp.tagNamePattern;function OM(e){return e!==""}function xM(e){return e?e.split(/[\t\n\f\r ]+/).filter(OM):[]}function LM(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function cb(e){if(!e)return[];var t=xM(e);return Object.keys(t.reduce(LM,{}))}function kM(e){return function(t){return e&&e.indexOf(t)!==-1}}function as(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function kt(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,as(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Ft={},or=Ft.ELEMENT_NODE=1,Io=Ft.ATTRIBUTE_NODE=2,ns=Ft.TEXT_NODE=3,yb=Ft.CDATA_SECTION_NODE=4,bb=Ft.ENTITY_REFERENCE_NODE=5,FM=Ft.ENTITY_NODE=6,Op=Ft.PROCESSING_INSTRUCTION_NODE=7,xp=Ft.COMMENT_NODE=8,wb=Ft.DOCUMENT_NODE=9,Ab=Ft.DOCUMENT_TYPE_NODE=10,An=Ft.DOCUMENT_FRAGMENT_NODE=11,MM=Ft.NOTATION_NODE=12,pt={},Ye={},aX=pt.INDEX_SIZE_ERR=(Ye[1]="Index size error",1),sX=pt.DOMSTRING_SIZE_ERR=(Ye[2]="DOMString size error",2),Lt=pt.HIERARCHY_REQUEST_ERR=(Ye[3]="Hierarchy request error",3),lX=pt.WRONG_DOCUMENT_ERR=(Ye[4]="Wrong document",4),db=pt.INVALID_CHARACTER_ERR=(Ye[5]="Invalid character",5),uX=pt.NO_DATA_ALLOWED_ERR=(Ye[6]="No data allowed",6),cX=pt.NO_MODIFICATION_ALLOWED_ERR=(Ye[7]="No modification allowed",7),Eb=pt.NOT_FOUND_ERR=(Ye[8]="Not found",8),dX=pt.NOT_SUPPORTED_ERR=(Ye[9]="Not supported",9),pb=pt.INUSE_ATTRIBUTE_ERR=(Ye[10]="Attribute in use",10),Sr=pt.INVALID_STATE_ERR=(Ye[11]="Invalid state",11),pX=pt.SYNTAX_ERR=(Ye[12]="Syntax error",12),fX=pt.INVALID_MODIFICATION_ERR=(Ye[13]="Invalid modification",13),mX=pt.NAMESPACE_ERR=(Ye[14]="Invalid namespace",14),hX=pt.INVALID_ACCESS_ERR=(Ye[15]="Invalid access",15);function ie(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,Ye[e]),this.message=Ye[e],Error.captureStackTrace&&Error.captureStackTrace(this,ie);return r.code=e,t&&(this.message=this.message+": "+t),r}ie.prototype=Error.prototype;as(pt,ie);function En(){}En.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++)qp(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 To(e,t){this._node=e,this._refresh=t,Lp(this)}function Lp(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(kb(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];as(r,e),e._inc=t}}To.prototype.item=function(e){return Lp(this),this[e]||null};kt(To,En);function Hl(){this._nameIndex=Object.create(null)}function Cb(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function BM(e,t){e._nameIndex[t.nodeName]=t}function Sb(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function fb(e,t,r,n){if(n?(t[Cb(t,n)]=r,Sb(t,n)):t[t.length++]=r,BM(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&_b(i,e,n),$M(i,e,r))}}function mb(e,t,r){var n=Cb(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,Sb(t,r),e){var o=e.ownerDocument;o&&(_b(o,e,r),r.ownerElement=null)}}else throw new ie(Eb,new Error(e.tagName+"@"+r))}Hl.prototype={length:0,item:En.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 ie(pb);var r=this._nameIndex[e.nodeName];return fb(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new ie(pb);return r=this.getNamedItemNS(e.namespaceURI,e.localName),fb(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return mb(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return mb(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 Nb(){}Nb.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new ss;if(n.implementation=this,n.childNodes=new En,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 Yl;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function me(){}me.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 Jl(this,e,t)},replaceChild:function(e,t){Jl(this,e,t,Tb),t&&this.removeChild(t)},removeChild:function(e){return Ib(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return Lb(this.ownerDocument||this,this,e)},normalize:function(){Xe(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===ns&&t.nodeType===ns){for(var n=[],i=r;i!==null&&i.nodeType===ns;)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("")),Xl(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==Io?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==Io?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function Db(e){return e=="<"&&"&lt;"||e==">"&&"&gt;"||e=="&"&&"&amp;"||e=='"'&&"&quot;"||"&#"+e.charCodeAt()+";"}as(Ft,me);as(Ft,me.prototype);function Kl(e,t){return Xe(e,null,{enter:function(r){return t(r)?Xe.STOP:!0}})===Xe.STOP}function Xe(e,t,r){for(var n=[{node:e,context:t,phase:Xe.ENTER}];n.length>0;){var i=n.pop();if(i.phase===Xe.ENTER){var o=r.enter(i.node,i.context);if(o===Xe.STOP)return Xe.STOP;if(n.push({node:i.node,context:o,phase:Xe.EXIT}),o==null)continue;for(var a=i.node.lastChild;a;)n.push({node:a,context:o,phase:Xe.ENTER}),a=a.previousSibling}else r.exit&&r.exit(i.node,i.context)}}Xe.STOP=Symbol("walkDOM.STOP");Xe.ENTER=0;Xe.EXIT=1;function ss(){this.ownerDocument=this}function $M(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===is.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function _b(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===is.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Xl(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 Ib(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,Xl(e.ownerDocument,e),t}function UM(e){return e&&(e.nodeType===me.DOCUMENT_NODE||e.nodeType===me.DOCUMENT_FRAGMENT_NODE||e.nodeType===me.ELEMENT_NODE)}function qM(e){return e&&(Hr(e)||kp(e)||Cn(e)||e.nodeType===me.DOCUMENT_FRAGMENT_NODE||e.nodeType===me.COMMENT_NODE||e.nodeType===me.PROCESSING_INSTRUCTION_NODE)}function Cn(e){return e&&e.nodeType===me.DOCUMENT_TYPE_NODE}function Hr(e){return e&&e.nodeType===me.ELEMENT_NODE}function kp(e){return e&&e.nodeType===me.TEXT_NODE}function hb(e,t){var r=e.childNodes||[];if(jr(r,Hr)||Cn(t))return!1;var n=jr(r,Cn);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function gb(e,t){var r=e.childNodes||[];function n(o){return Hr(o)&&o!==t}if(jr(r,n))return!1;var i=jr(r,Cn);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function VM(e,t,r){if(!UM(e))throw new ie(Lt,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new ie(Eb,"child not in parent");if(!qM(t)||Cn(t)&&e.nodeType!==me.DOCUMENT_NODE)throw new ie(Lt,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function GM(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===me.DOCUMENT_FRAGMENT_NODE){var o=i.filter(Hr);if(o.length>1||jr(i,kp))throw new ie(Lt,"More than one element or text in fragment");if(o.length===1&&!hb(e,r))throw new ie(Lt,"Element in fragment can not be inserted before doctype")}if(Hr(t)&&!hb(e,r))throw new ie(Lt,"Only one element can be added and only after doctype");if(Cn(t)){if(jr(n,Cn))throw new ie(Lt,"Only one doctype is allowed");var a=jr(n,Hr);if(r&&n.indexOf(a)<n.indexOf(r))throw new ie(Lt,"Doctype can only be inserted before an element");if(!r&&a)throw new ie(Lt,"Doctype can not be appended since element is present")}}function Tb(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===me.DOCUMENT_FRAGMENT_NODE){var o=i.filter(Hr);if(o.length>1||jr(i,kp))throw new ie(Lt,"More than one element or text in fragment");if(o.length===1&&!gb(e,r))throw new ie(Lt,"Element in fragment can not be inserted before doctype")}if(Hr(t)&&!gb(e,r))throw new ie(Lt,"Only one element can be added and only after doctype");if(Cn(t)){let l=function(u){return Cn(u)&&u!==r};var s=l;if(jr(n,l))throw new ie(Lt,"Only one doctype is allowed");var a=jr(n,Hr);if(r&&n.indexOf(a)<n.indexOf(r))throw new ie(Lt,"Doctype can only be inserted before an element")}}function Jl(e,t,r,n){VM(e,t,r),e.nodeType===me.DOCUMENT_NODE&&(n||GM)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===An){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;os(o,l)}while(o!==a&&(o=o.nextSibling));return Xl(e.ownerDocument||e,e),t.nodeType==An&&(t.firstChild=t.lastChild=null),t}function os(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===or&&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;)os(i,t),i=i.nextSibling}}function zM(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,Xl(e.ownerDocument,e,t);var r=e.ownerDocument||e;return os(t,r),t}ss.prototype={nodeName:"#document",nodeType:wb,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==An){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return Jl(this,e,t),os(e,this),this.documentElement===null&&e.nodeType===or&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),Ib(this,e)},replaceChild:function(e,t){Jl(this,e,t,Tb),os(e,this),t&&this.removeChild(t),Hr(e)&&(this.documentElement=e)},importNode:function(e,t){return WM(this,e,t)},getElementById:function(e){var t=null;return Kl(this.documentElement,function(r){if(r.nodeType==or&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=cb(e);return new To(this,function(r){var n=[];return t.length>0&&Kl(r.documentElement,function(i){if(i!==r&&i.nodeType===or){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=cb(o);a=t.every(kM(s))}a&&n.push(i)}}}),n})},createElement:function(e){var t=new Fi;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new En;var r=t.attributes=new Hl;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new Zl;return e.ownerDocument=this,e.childNodes=new En,e},createTextNode:function(e){var t=new Fp;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new Mp;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new ie(db,'data contains "]]>"');var t=new Bp;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new Up;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new Ql;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!_o.test(e))throw new ie(db,'not a valid xml name "'+e+'"');var t=new $p;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new Fi,n=t.split(":"),i=r.attributes=new Hl;return r.childNodes=new En,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 Ql,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}};kt(ss,me);function Fi(){this._nsMap={}}Fi.prototype={nodeType:or,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===An?this.insertBefore(e,null):zM(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 To(this,function(t){var r=[];return Kl(t,function(n){n!==t&&n.nodeType==or&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new To(this,function(r){var n=[];return Kl(r,function(i){i!==r&&i.nodeType===or&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};ss.prototype.getElementsByTagName=Fi.prototype.getElementsByTagName;ss.prototype.getElementsByTagNameNS=Fi.prototype.getElementsByTagNameNS;kt(Fi,me);function Ql(){}Ql.prototype.nodeType=Io;kt(Ql,me);function ls(){}ls.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(Ye[Lt])},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}};kt(ls,me);function Fp(){}Fp.prototype={nodeName:"#text",nodeType:ns,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}};kt(Fp,ls);function Mp(){}Mp.prototype={nodeName:"#comment",nodeType:xp};kt(Mp,ls);function Bp(){}Bp.prototype={nodeName:"#cdata-section",nodeType:yb};kt(Bp,ls);function Yl(){}Yl.prototype.nodeType=Ab;kt(Yl,me);function Pb(){}Pb.prototype.nodeType=MM;kt(Pb,me);function Rb(){}Rb.prototype.nodeType=FM;kt(Rb,me);function $p(){}$p.prototype.nodeType=bb;kt($p,me);function Zl(){}Zl.prototype.nodeName="#document-fragment";Zl.prototype.nodeType=An;kt(Zl,me);function Up(){}Up.prototype.nodeType=Op;kt(Up,me);function Ob(){}Ob.prototype.serializeToString=function(e,t,r,n){return xb.call(e,t,r,n)};me.prototype.toString=xb;function xb(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 qp(this,i,e,t,l,n),i.join("")}function vb(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===is.XML||i===is.XMLNS)return!1;for(var o=r.length;o--;){var a=r[o];if(a.prefix===n)return a.namespace!==i}return!0}function jl(e,t,r,n){if(n&&!_o.test(t))throw new ie(Sr,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,Db),'"')}function qp(e,t,r,n,i,o){i||(i=[]),Xe(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 or:var c=a.attributes,d=c.length,p=a.tagName;u=is.isHTML(a.namespaceURI)||u;var f=p;if(!u&&!a.prefix&&a.namespaceURI){for(var m,h=0;h<c.length;h++)if(c.item(h).name==="xmlns"){m=c.item(h).value;break}if(!m)for(var g=l.length-1;g>=0;g--){var y=l[g];if(y.prefix===""&&y.namespace===a.namespaceURI){m=y.namespace;break}}if(m!==a.namespaceURI)for(var g=l.length-1;g>=0;g--){var y=l[g];if(y.namespace===a.namespaceURI){y.prefix&&(f=y.prefix+":"+p);break}}}if(o&&!_o.test(f))throw new ie(Sr,'The element name "'+f+'" is not a valid XML QName');t.push("<",f);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(vb(S,u,w)){var T=S.prefix||"",O=S.namespaceURI;jl(t,T?"xmlns:"+T:"xmlns",O,o),w.push({prefix:T,namespace:O})}var k=n?n(S):S;k&&(typeof k=="string"?t.push(k):jl(t,k.name,k.value,o))}if(p===f&&vb(a,u,w)){var F=a.prefix||"",O=a.namespaceURI;jl(t,F?"xmlns:"+F:"xmlns",O,o),w.push({prefix:F,namespace:O})}var P=a.firstChild;if(P||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(p)){if(t.push(">"),u&&/^script$/i.test(p)){for(;P;)P.data?t.push(P.data):qp(P,t,u,n,w.slice(),o),P=P.nextSibling;return t.push("</",p,">"),null}return{ns:w,isHTML:u,tag:f}}else return t.push("/>"),null;case wb:case An:return{ns:l.slice(),isHTML:u,tag:null};case Io:return jl(t,a.name,a.value,o),null;case ns:return t.push(a.data.replace(/[<&>]/g,Db)),null;case yb:if(o&&a.data.indexOf("]]>")!==-1)throw new ie(Sr,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case xp:if(o&&a.data.indexOf("-->")!==-1)throw new ie(Sr,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case Ab:if(o){if(!_o.test(a.name))throw new ie(Sr,'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 ie(Sr,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new ie(Sr,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new ie(Sr,'DocumentType internalSubset contains "]>"')}var q=a.publicId,V=a.systemId;if(t.push("<!DOCTYPE ",a.name),q)t.push(" PUBLIC ",q),V&&V!="."&&t.push(" ",V),t.push(">");else if(V&&V!=".")t.push(" SYSTEM ",V,">");else{var Ve=a.internalSubset;Ve&&t.push(" [",Ve,"]"),t.push(">")}return null;case Op:if(o){if(!_o.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new ie(Sr,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new ie(Sr,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case bb:if(o&&!_o.test(a.nodeName))throw new ie(Sr,'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 WM(e,t,r){var n;return Xe(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===Io||r;return s?a:null}}),n}function Lb(e,t,r){var n;return Xe(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 En),a.ownerDocument=e;var u=r;switch(a.nodeType){case or:var c=i.attributes,d=a.attributes=new Hl,p=c.length;d._ownerElement=a;for(var f=0;f<p;f++)a.setAttributeNode(Lb(e,c.item(f),!0));break;case Io:u=!0}return o!==null?o.appendChild(a):n=a,u?a:null}}),n}function kb(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(To.prototype,"length",{get:function(){return Lp(this),this.$$length}}),Object.defineProperty(me.prototype,"textContent",{get:function(){if(this.nodeType===or||this.nodeType===An){var e=[];return Xe(this,null,{enter:function(t){if(t.nodeType===or||t.nodeType===An)return!0;if(t.nodeType===Op||t.nodeType===xp)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case or:case An: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}}}),kb=function(e,t,r){e["$$"+t]=r})}catch{}Sn.DocumentType=Yl;Sn.DOMException=ie;Sn.DOMImplementation=Nb;Sn.Element=Fi;Sn.Node=me;Sn.NodeList=En;Sn.walkDOM=Xe;Sn.XMLSerializer=Ob});var Mb=b(us=>{"use strict";var Fb=Do().freeze;us.XML_ENTITIES=Fb({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});us.HTML_ENTITIES=Fb({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"});us.entityMap=us.HTML_ENTITIES});var Vb=b(zp=>{var ps=Do().NAMESPACE,Gp=Do().tagNamePattern,Po=0,ni=1,Ro=2,cs=3,Oo=4,xo=5,ds=6,eu=7;function Lo(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,Lo)}Lo.prototype=new Error;Lo.prototype.name=Lo.name;function Ub(){}Ub.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),QM(t,t={}),jM(e,t,r,n,this.errorHandler),n.endDocument()}};function jM(e,t,r,n,i){function o(Z){if(Z>65535){Z-=65536;var ye=55296+(Z>>10),hn=56320+(Z&1023);return String.fromCharCode(ye,hn)}else return String.fromCharCode(Z)}function a(Z){var ye=Z.slice(1,-1);return Object.hasOwnProperty.call(r,ye)?r[ye]:ye.charAt(0)==="#"?o(parseInt(ye.substr(1).replace("x","0x"))):(i.error("entity not found:"+Z),Z)}function s(Z){if(Z>h){var ye=e.substring(h,Z).replace(/&#?\w+;/g,a);p&&l(h),n.characters(ye,0,Z-h),h=Z}}function l(Z,ye){for(;Z>=c&&(ye=d.exec(e));)u=ye.index,c=u+ye[0].length,p.lineNumber++;p.columnNumber=Z-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,p=n.locator,f=[{currentNSMap:t}],m={},h=0;;){try{var g=e.indexOf("<",h);if(g<0){if(!e.substr(h).match(/^\s*$/)){var y=n.doc,w=y.createTextNode(e.substr(h));y.appendChild(w),n.currentElement=w}return}switch(g>h&&s(g),e.charAt(g+1)){case"/":var V=e.indexOf(">",g+3),C=e.substring(g+2,V).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),S=f.pop();V<0?(C=e.substring(g+2).replace(/[\s<].*/,""),i.error("end tag name: "+C+" is not complete:"+S.tagName),V=g+1+C.length):C.match(/\s</)?(C=C.replace(/[\s<].*/,""),i.error("end tag name: "+C+" maybe not complete"),V=g+1+C.length):/[ \t\n\r]/.test(C)&&Gp.test(C.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+C+'"');var T=S.localNSMap,O=S.tagName==C,k=O||S.tagName&&S.tagName.toLowerCase()==C.toLowerCase();if(k){if(n.endElement(S.uri,S.localName,C),T)for(var F in T)Object.prototype.hasOwnProperty.call(T,F)&&n.endPrefixMapping(F);O||i.fatalError("end tag name: "+C+" is not match the current start tagName:"+S.tagName)}else f.push(S);V++;break;case"?":p&&l(g),V=YM(e,g,n);break;case"!":p&&l(g),V=XM(e,g,n,i);break;default:p&&l(g);var P=new qb,q=f[f.length-1].currentNSMap,V=HM(e,g,P,q,a,i),Ve=P.length;if(!P.closed&&JM(e,V,P.tagName,m)&&(P.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),p&&Ve){for(var Pt=Bb(p,{}),Je=0;Je<Ve;Je++){var Ge=P[Je];l(Ge.offset),Ge.locator=Bb(p,{})}n.locator=Pt,$b(P,n,q)&&f.push(P),n.locator=p}else $b(P,n,q)&&f.push(P);ps.isHTML(P.uri)&&!P.closed?V=KM(e,V,P.tagName,a,n):V++}}catch(Z){if(Z instanceof Lo)throw Z;i.error("element parse error: "+Z),V=-1}V>h?h=V:s(Math.max(g,h)+1)}}function Bb(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function HM(e,t,r,n,i,o){function a(f,m,h){r.attributeNames.hasOwnProperty(f)&&o.fatalError("Attribute "+f+" redefined"),r.addValue(f,m.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),h)}for(var s,l,u=++t,c=Po;;){var d=e.charAt(u);if(c===Po&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===ni)s=e.slice(t,u),c=cs;else if(c===Ro)c=cs;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===cs||c===ni)if(c===ni&&(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=xo;else throw new Error("attribute value no end '"+d+"' match");else if(c==Oo)l=e.slice(t,u),a(s,l,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=xo;else throw new Error('attribute value must after "="');break;case"/":switch(c){case Po:r.setTagName(e.slice(t,u));case xo:case ds:case eu:c=eu,r.closed=!0;case Oo:case ni:break;case Ro:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==Po&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case Po:r.setTagName(e.slice(t,u));case xo:case ds:case eu:break;case Oo:case ni:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case Ro:c===Ro&&(l=s),c==Oo?(o.warning('attribute "'+l+'" missed quot(")!'),a(s,l,t)):((!ps.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),a(l,l,t));break;case cs:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case Po:r.setTagName(e.slice(t,u)),c=ds;break;case ni:s=e.slice(t,u),c=Ro;break;case Oo:var l=e.slice(t,u);o.warning('attribute "'+l+'" missed quot(")!!'),a(s,l,t);case xo:c=ds;break}else switch(c){case Ro:var p=r.tagName;(!ps.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=u,c=ni;break;case xo:o.warning('attribute space is required"'+s+'"!!');case ds:c=ni,t=u;break;case cs:c=Oo,t=u;break;case eu:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function $b(e,t,r){for(var n=e.tagName,i=null,d=e.length;d--;){var o=e[d],a=o.qName,s=o.value,p=a.indexOf(":");if(p>0)var l=o.prefix=a.slice(0,p),u=a.slice(p+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=ps.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var l=o.prefix;l&&(l==="xml"&&(o.uri=ps.XML),l!=="xmlns"&&(o.uri=r[l||""]))}var p=n.indexOf(":");p>0?(l=e.prefix=n.slice(0,p),u=e.localName=n.slice(p+1)):(l=null,u=e.localName=n);var f=e.uri=r[l||""];if(t.startElement(f,u,n,e),e.closed){if(t.endElement(f,u,n),i)for(l in i)Object.prototype.hasOwnProperty.call(i,l)&&t.endPrefixMapping(l)}else return e.currentNSMap=r,e.localNSMap=i,!0}function KM(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 JM(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 QM(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function XM(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=ZM(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 YM(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 qb(){this.attributeNames={}}qb.prototype={setTagName:function(e){if(!Gp.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!Gp.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 ZM(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}zp.XMLReader=Ub;zp.ParseError=Lo});var Jb=b(ru=>{var eB=Do(),tB=Vp(),Gb=Mb(),jb=Vb(),rB=tB.DOMImplementation,zb=eB.NAMESPACE,nB=jb.ParseError,iB=jb.XMLReader;function Hb(e){return e.replace(/\r[\n\u0085]/g,`
-`).replace(/[\r\u0085\u2028]/g,`
-`)}function Kb(e){this.options=e||{locator:{}}}Kb.prototype.parseFromString=function(e,t){var r=this.options,n=new iB,i=r.domBuilder||new fs,o=r.errorHandler,a=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?Gb.HTML_ENTITIES:Gb.XML_ENTITIES;a&&i.setDocumentLocator(a),n.errorHandler=oB(o,i,a),n.domBuilder=r.domBuilder||i,l&&(s[""]=zb.HTML),s.xml=s.xml||zb.XML;var c=r.normalizeLineEndings||Hb;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function oB(e,t,r){if(!e){if(t instanceof fs)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+Wp(r))}||function(){}}return o("warning"),o("error"),o("fatalError"),n}function fs(){this.cdata=!1}function ko(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}fs.prototype={startDocument:function(){this.doc=new rB().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;tu(this,o),this.currentElement=o,this.locator&&ko(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&&ko(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&&ko(this.locator,r),tu(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=Wb.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&&ko(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=Wb.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&ko(this.locator,n),tu(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&&ko(this.locator,i),tu(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,Wp(this.locator))},error:function(e){console.error("[xmldom error] "+e,Wp(this.locator))},fatalError:function(e){throw new nB(e,this.locator)}};function Wp(e){if(e)return`
-@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function Wb(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){fs.prototype[e]=function(){return null}});function tu(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}ru.__DOMHandler=fs;ru.normalizeLineEndings=Hb;ru.DOMParser=Kb});var iu=b(nu=>{var Qb=Vp();nu.DOMImplementation=Qb.DOMImplementation;nu.XMLSerializer=Qb.XMLSerializer;nu.DOMParser=Jb().DOMParser});var ii=b(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});ou.installDomShim=void 0;var Xb=iu(),Yb=!1,aB={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 sB(){if(Yb)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=Xb.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=Xb.XMLSerializer),typeof e.Node>"u"&&(e.Node=aB),Yb=!0}ou.installDomShim=sB});var oi=b(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.projectElementBag=Le.serializeNode=Le.domEngine=Le.nodeLikeFromDom=Le.parseXmlRoot=Le.EMPTY_FORM_SENTINEL=Le.TEXT_SENTINEL=void 0;var lB=ri(),ms=re(),uB=ii();Le.TEXT_SENTINEL="#text";Le.EMPTY_FORM_SENTINEL="#empty";var su=new WeakSet;function cB(e,t){(0,uB.installDomShim)();let r=e&&e.trim()!==""?e:t,i=new DOMParser().parseFromString(r,"text/xml").documentElement;if(!i)throw new ms.InvalidArgumentError("XML source has no root element (empty or malformed input)");return pB(i),fB(i),gB(i,r),i}Le.parseXmlRoot=cB;var dB=new Set([1,3]);function pB(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(!dB.has(o.nodeType))throw new ms.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 fB(e){var t,r;let n=(t=e.ownerDocument)!==null&&t!==void 0?t:e.parentNode;if(!n)return;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a!==e&&!(a.nodeType===3&&((r=a.nodeValue)!==null&&r!==void 0?r:"").trim()===""))throw new ms.InvalidArgumentError(`Unsupported document-level XML node (type ${a.nodeType}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}}function mB(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 hB(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 ew(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 gB(e,t){let r=mB(t),n=hB(e),i=Math.min(r.length,n.length);for(let o=0;o<i;o+=1){if(r[o])continue;let a=n[o];ew(a)||su.add(a)}}function jp(e){let t=e.nodeType===3;return{getNodeName:()=>t?Le.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:Le.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 su.has(e)&&!ew(e)&&i.push({key:Le.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(jp(o))}return r}}}Le.nodeLikeFromDom=jp;function vB(e){return{make:t=>t===Le.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===Le.EMPTY_FORM_SENTINEL?su.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}Le.domEngine=vB;function tw(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 au(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw au(r);t+=1;continue}if(r>=56320&&r<=57343)throw au(r)}}function au(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new ms.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 yB(e){return tw(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\r/g,"&#xD;").replace(/\n/g,"&#xA;").replace(/\t/g,"&#x9;")}function bB(e){return tw(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function wB(e){return rw(e,0)}Le.serializeNode=wB;var Zb=512;function rw(e,t){var r;if(t>Zb)throw new ms.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${Zb}`);if(e.nodeType===3)return bB((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+'="'+yB(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 su.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of a)i+=rw(l,t+1);return i+"</"+n.tagName+">"}function AB(e){let t=jp(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,lB.rawFromNode)(r)}))}}Le.projectElementBag=AB});var Nr=b(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.rejectUnknownKeys=ft.childObjects=ft.optionalGuidId=ft.optionalEnum=ft.eachObject=ft.issue=ft.isJsonObject=void 0;function nw(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}ft.isJsonObject=nw;function Fo(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}ft.issue=Fo;function iw(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{nw(o)?i.push({node:o,index:a}):n.push(Fo(`${t}/${a}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}ft.eachObject=iw;function EB(e,t,r,n,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!r.includes(a))&&o.push(Fo(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}ft.optionalEnum=EB;var CB=/^(?:\{[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 SB(e,t,r,n,i){let o=e[t];typeof o=="string"&&o!==""&&!CB.test(o)&&i.push(Fo(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${o}'`))}ft.optionalGuidId=SB;function NB(e,t,r,n,i){let o=e[t],a=`${r}/${t}`;return o===void 0?[]:Array.isArray(o)?iw(o,a,n,i):(i.push(Fo(a,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}ft.childObjects=NB;function DB(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(Fo(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}ft.rejectUnknownKeys=DB});var af=b(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.genPageEmbedIssues=B.mintEmbedIdentity=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.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 _B=iu(),IB=wo(),Hp=lt(),ar=Nr();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 TB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Mt(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),TB.test(t)?t:""}B.normGuid=Mt;function ai(e,t){let r=le(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=ai;function gs(e){return le(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=gs;function le(e){return Array.isArray(e)?e:[]}function Zp(e,t){let r=le(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function sw(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function lw(e){return Kr(e).map(t=>t.cell)}B.typedCells=lw;function Kr(e){let t=[];return le(e?.tabs).forEach((r,n)=>{le(ve(r)?r.columns:void 0).forEach((i,o)=>{le(ve(i)?i.sections:void 0).forEach((a,s)=>{le(ve(a)?a.rows:void 0).forEach((l,u)=>{le(ve(l)?l.cells:void 0).forEach((c,d)=>{ve(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${o}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}function Nn(e){return ve(e)?Mt(Zp(e.bag,"uniqueid")):""}B.controlUniqueId=Nn;function PB(e){let t=new Set;for(let{cell:r}of Kr(e)){let n=$i(r.control)?Nn(r.control):"";n&&t.add(n)}return t}function RB(e){let t=new Map;for(let{cell:r}of Kr(e)){let n=ve(r.control)?Nn(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function OB(e){return e!==void 0&&e.genPage===void 0&&(rf(e)!==B.CUSTOM_CONTROL_CLASS_ID||!du(e))}function Kp(e,t){if(ve(e)){t(e);for(let r of le(e.c))Kp(r,t)}}function Mi(e,t){var r;if(ve(e)){for(let n of le(e.c))Kp(n?.node,t);for(let n of le((r=e.w)===null||r===void 0?void 0:r.c))Kp(n?.node,t)}}function uu(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(Mt(ai(i,"uniqueid")))};return Mi(e?.bag,n),le(e?.tabs).forEach(i=>{ve(i)&&(Mi(i.bag,n),le(i.columns).forEach(o=>{ve(o)&&(Mi(o.bag,n),le(o.sections).forEach(a=>{ve(a)&&(Mi(a.bag,n),le(a.rows).forEach(s=>{ve(s)&&(Mi(s.bag,n),le(s.cells).forEach(l=>{ve(l)&&(Mi(l.bag,n),ve(l.control)&&(r(Nn(l.control)),Mi(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=uu;function Mo(e){return le(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=Mo;function Bi(e,t){var r;let n=Mt(t);if(n)return le((r=Mo(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&Mt(ai(i,"forControl"))===n)}B.descriptionFor=Bi;function vs(e){return le(e.c).filter(uw)}B.pageEntries=vs;function uw(e){return e?.n==="customControl"&&ai(e,"name")===B.GENPAGE_CONTROL_NAME}function Jp(e,t){let r=le(e.c).find(n=>n?.n==="parameters");return le(r?.c).find(n=>n?.n===t)}B.entryParameter=Jp;function Qp(e){return ai(e,"static")==="true"}B.isStaticParameter=Qp;function ys(e){let t=vs(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let o=Jp(t[i],"RefId");if(!o||!Qp(o))return{kind:"unsupported"};let a=Mt(gs(o));if(!a)return{kind:"unsupported"};let s=Jp(t[i],"PageInput");if(s&&!Qp(s))return{kind:"unsupported"};let l=s?gs(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=ys;function ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ef(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return ve(t)&&ve(t.data)?t.data:void 0}B.inputDataFrom=ef;function tf(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=tf;function rf(e){return sw(e.classId!==void 0?e.classId:Zp(e.bag,"classid"))}B.effectiveClassId=rf;function du(e){return!e.fieldName}B.isUnbound=du;function nf(e,t){if(tf(e)!=="Main"||!du(t)||rf(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=Nn(t),n=r?Bi(e.bag,r):void 0;return n!==void 0&&ys(n).kind==="projectable"}B.isRecognizedEmbed=nf;function xB(e){for(let t of lw(e)){let r=t.control;if(!r||!nf(e,r))continue;let n=ys(Bi(e.bag,Nn(r)));if(n.kind!=="projectable")continue;let i=ef(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=xB;var LB=new Set(["pageId","inputData"]);function hs(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 kB(e){let t=[],r=u=>c=>t.push(`${u}: ${c}`),i=new _B.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new Error(`the formxml does not parse cleanly${t.length>0?` (${t[0]})`:""}`);let o=new Set,a=i.getElementsByTagName("control");for(let u=0;u<a.length;u+=1){let c=Mt(a[u].getAttribute("uniqueid"));c&&o.add(c)}let s=hs(i).find(u=>u.nodeName==="controlDescriptions"),l=new Map;for(let u of s?hs(s):[]){let c=Mt(u.getAttribute("forControl"));if(!(u.nodeName!=="controlDescription"||!c||!o.has(c)))for(let d of hs(u)){if(d.nodeName!=="customControl"||d.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let p=hs(d).find(h=>h.nodeName==="parameters"),f=p?hs(p).find(h=>h.nodeName==="RefId"):void 0,m=f&&f.getAttribute("static")==="true"?Mt(f.textContent):"";m&&l.set(`${c}|${m}`,[c,m])}}return[...l.values()]}B.activeEmbedBindings=kB;function lu(e){return{n:`<${e}`,a:[],c:[]}}function Xp(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[lu(t)]}}function Yp(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);ve(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function FB(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:[Xp("RefId",t),...r===void 0?[]:[Xp("PageInput",Yp(r))]]}]}))}}function cu(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>cu(r,t[n]));if(ve(e)&&ve(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&cu(e[n],t[n]))}return e===t}function MB(e,t,r){let n=le(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&Mt(gs(i))!==t&&(i.c=[lu(t)]);let o=n.c.findIndex(u=>u?.n==="PageInput"),a=o>=0?n.c[o]:void 0,s=a?gs(a):void 0;if(cu(ef(s),r))return;if(r!==void 0){a?a.c=[lu(Yp(r,s))]:n.c.push(Xp("PageInput",Yp(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(o,1):a.c=[lu(JSON.stringify(l))]}function of(e){let t=le(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=of;function BB(e,t){var r;let n=e.bag,i=Mo(n);if(i&&t){let o=uu(t),a=uu(e),s=PB(t),l=RB(e),u=le(i.node.c),c=[];for(let d of u){let p=d?.n==="controlDescription"&&vs(d).length>0?Mt(ai(d,"forControl")):"";if(!p||!o.has(p))c.push(d);else if(a.has(p))if(s.has(p)&&OB(l.get(p))&&cu(d,Bi(t.bag,p))){let f=le(d.c).filter(m=>!uw(m));f.length>0&&c.push({...d,c:f})}else c.push(d)}(c.length!==u.length||c.some((d,p)=>d!==u[p]))&&(i.node.c=c)}for(let{cell:o}of Kr(e)){let a=o.control;if(!$i(a)||!ve(a.genPage))continue;let s=Mt(a.genPage.pageId),l=a.genPage.inputData,u=Nn(a);if(!u){if(pu(a)!==void 0)continue;u=pw(a)}let c=Bi(n,u);if(c){for(let f of vs(c))MB(f,s,l);continue}i||(i={i:of(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=Zp(a.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),p=d.startsWith("{")?d:`{${u}}`;i.node.c.push(FB(p,s,l))}}B.reconcileEmbedDescriptions=BB;function $B(e,t){let r=Mo(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=Kr(e).some(({cell:a})=>$i(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=Mo(o.bag);s?s.node=a:(o.bag=ve(o.bag)?o.bag:{a:[],c:[]},o.bag.c=le(o.bag.c),o.bag.c.push({i:of(e.bag),node:a}))}for(let{cell:a}of Kr(o))$i(a.control)&&(cw(a.control),dw(a));return o}B.commitEmbedState=$B;function UB(e){if(Kr(e).some(({cell:r})=>$i(r.control)))return!0;let t=Mo(e.bag);return le(t?.node.c).some(r=>r?.n==="controlDescription"&&vs(r).length>0)}B.mayCommitEmbedState=UB;function cw(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=cw;function dw(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=dw;function $i(e){return ve(e)&&e.genPage!==void 0}B.hasGenPage=$i;function ow(e){return $i(e.control)&&(!e.control.id||!e.id||pu(e.control)===void 0)}function pu(e){let t=le(ve(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}function qB(e){if(!Kr(e).some(({cell:r})=>ow(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of Kr(t)){if(!ow(r))continue;let n=r.control;n.id||(n.id=(0,Hp.newId)()),r.id||(r.id=(0,Hp.newId)()),pu(n)===void 0&&pw(n)}return t}B.mintEmbedIdentity=qB;function pw(e){let t=(0,Hp.newId)(),r=`{${t}}`;if(!ve(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=le(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=le(e.bag.c),t}function aw(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function VB(e){let t=le(e.c).filter(r=>r?.n==="customControl").map(r=>{var n,i;return(i=(n=ai(r,"name"))!==null&&n!==void 0?n:ai(r,"id"))!==null&&i!==void 0?i:"(unnamed)"});return[...new Set(t)].join(", ")||"(no custom control)"}function GB(e){let t=[],r;for(let{cell:n,pointer:i}of Kr(e)){let o=n.control;if(!ve(o))continue;let a=`${i}/control`;if(o.genPage===void 0){zB(e,o,a,t);continue}r=r??uu(e),WB(e,o,a,r,t)}return t}B.genPageEmbedIssues=GB;function zB(e,t,r,n){if(!nf(e,t))return;let i=ys(Bi(e.bag,Nn(t)));n.push((0,ar.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 WB(e,t,r,n,i){var o;let a=`${r}/genPage`,s=t.genPage;if(!ve(s))i.push((0,ar.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${aw(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!Mt(s.pageId))&&i.push((0,ar.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&&!ve(s.inputData)&&i.push((0,ar.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${aw(s.inputData)}`));for(let f of Object.keys(s))LB.has(f)||i.push((0,ar.issue)(IB.JsonPointer.append(a,f),"genpage-embed-unknown-key",`'${f}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}du(t)||i.push((0,ar.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&&sw(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,ar.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=tf(e);l!=="Main"&&i.push((0,ar.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=pu(t);u!==void 0&&!Mt(u)&&i.push((0,ar.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=Nn(t);if(!c)return;let d=Bi(e.bag,c),p=d?ys(d):void 0;d&&p?.kind==="none"?i.push((0,ar.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${VB(d)}). genPage would have to delete that binding to take its place, so embed the page in a new cell instead.`)):p?.kind==="unsupported"&&i.push((0,ar.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,ar.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 lf=b(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.findMissingGenPages=si.GENPAGE_LOOKUP_CHUNK=void 0;var jB=Rt(),sf=ae();si.GENPAGE_LOOKUP_CHUNK=50;async function HB(e,t,r){let n=[...new Set(t.map(o=>(0,sf.normalizeGuid)(o,"uxagentprojectid")))],i=new Set;for(let o=0;o<n.length;o+=si.GENPAGE_LOOKUP_CHUNK){let a=n.slice(o,o+si.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,sf.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,jB.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,sf.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(o=>!i.has(o))}si.findMissingGenPages=HB});var cf=b(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.patchSystemForm=sr.assertSystemFormContentUnchanged=sr.readSystemFormContentEtag=sr.readSystemFormRowEtag=sr.unpublishedSystemFormPath=void 0;var Bt=be(),KB=ae(),uf=re();function fu(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,KB.odataQuery)([["$select",t]])}sr.unpublishedSystemFormPath=fu;function fw(e,t){return(0,Bt.readRowEtag)(e,"systemforms","formid",t)}sr.readSystemFormRowEtag=fw;async function JB(e,t){let r=fu(t);return(0,Bt.readEtag)((0,Bt.ensureSuccess)(await e.get(r),e.apiUrl(r)))}sr.readSystemFormContentEtag=JB;async function mw(e,t,r,n,i){(0,Bt.requireEtag)(i,r,t);let o=(0,Bt.readEtag)((0,Bt.ensureSuccess)(await e.get(n),e.apiUrl(n)));if(o===null)throw new uf.SdkError(Bt.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(o!==i)throw new uf.SdkError(Bt.VERSION_CONFLICT_CODE,`Version conflict writing ${r} '${t}': its formxml changed on the server since it was read (held ${i}, server ${o}). Re-fetch the ${r} and re-apply the change.`)}sr.assertSystemFormContentUnchanged=mw;async function QB(e,t,r,n,i,o){(0,Bt.requireEtag)(i,r,t);let a=await fw(e,t);if(a===null)throw new uf.SdkError(Bt.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.`);await mw(e,t,r,fu(t),i);let s=(0,Bt.echoWrite)("formid",{"If-Match":a}),l=`/systemforms(${t})${s.query}`;return(0,Bt.ensureSuccess)(await e.patch(l,n,s.options),e.apiUrl(l)),XB(e,t,r,o)}sr.patchSystemForm=QB;async function XB(e,t,r,n){let i;try{let o=fu(t,n.select),a=(0,Bt.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,l=(0,Bt.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);if(l&&u&&c&&d.length===0)return{id:t,etag:l,readBack:s};i=l?!u||!c?`the read did not return this ${r}'s document`:`the read did not return its ${d.join(", ")}`:"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 mf=b($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.getFormSecurityRoles=$t.setFormSecurityRoles=$t.formApi=$t.FORM_GENPAGE_TARGET_UNVERIFIABLE=$t.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var YB=Rt(),ut=be(),lr=ae(),Ui=re(),df=oi(),gw=af(),ZB=lf(),mu=cf();$t.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";$t.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var vw="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",e$={select:vw,required:["name","type","objecttypecode"]},t$="formid,name,type,objecttypecode",r$=2,n$={Main:r$,QuickView:6,QuickCreate:7,Card:11};$t.formApi={async get(e,t){let n=`/systemforms(${(0,lr.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,lr.odataQuery)([["$select",vw]]),i=(0,ut.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,ut.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=>n$[u]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,lr.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,lr.odataQuery)([["$select",t$],["$filter",a.join(" and ")]])}`;return(await(0,YB.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=hw(t);n!==void 0&&await yw(e,ff(n,"payload"),[]);let i=(0,ut.echoWrite)("formid"),o=`/systemforms${i.query}`,a=(0,ut.ensureSuccess)(await e.post(o,(0,ut.withClientMintedId)(t,"formid",r),i.options),e.apiUrl(o));return{id:(0,ut.resolveCreatedId)(a,"formid","form",r),etag:(0,ut.readEtag)(a)}},async update(e,t,r,n){let i=(0,lr.normalizeGuid)(t,"id"),o=hw(r);return o!==void 0&&await o$(e,i,o,n),(0,mu.patchSystemForm)(e,i,"form",r,n,e$)},readToken(e,t){return(0,mu.readSystemFormContentEtag)(e,(0,lr.normalizeGuid)(t,"id"))},delete(e,t){return(0,ut.deleteRecord)(e,"systemforms",t)}};var pf="DisplayConditions";async function i$(e,t,r){var n,i,o,a;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new Ui.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,lr.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,lr.odataQuery)([["$select","formid,formxml"]]),u=(0,ut.ensureSuccess)(await e.get(l),e.apiUrl(l)),c=(0,ut.readEtag)(u),d=u.body,p=d?.formxml;if(!p)throw new Ui.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let f=(0,df.parseXmlRoot)(p,"<form/>"),m=f.ownerDocument;if(!m)throw new Ui.InvalidArgumentError(`form '${s}' produced no owner document`);let h=bw(f,pf),g=h?.hasAttribute("Order")&&(n=h.getAttribute("Order"))!==null&&n!==void 0?n:void 0,y=h?.getAttribute("FallbackForm")||void 0;h&&f.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 Ui.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)),f.appendChild(h)}else if(w){let k=m.createElement(pf),F=r.order!==void 0?String(r.order):g;F!==void 0&&k.setAttribute("Order",F);let P=r.fallbackForm!==void 0?String(r.fallbackForm):y??"false";if(k.setAttribute("FallbackForm",P),r.everyone)k.appendChild(m.createElement("Everyone"));else for(let q of(a=r.roleIds)!==null&&a!==void 0?a:[]){let V=m.createElement("Role");V.setAttribute("Id",`{${(0,lr.normalizeGuid)(q,"roleId")}}`),k.appendChild(V)}f.appendChild(k)}let S=(0,df.serializeNode)(f);await(0,mu.assertSystemFormContentUnchanged)(e,s,"form",l,c);let T=await(0,mu.readSystemFormRowEtag)(e,s),O=`/systemforms(${s})`;(0,ut.ensureSuccess)(await e.patch(O,{formxml:S},{headers:{"Content-Type":"application/json","If-Match":(0,ut.requireEtag)(T,"form",s)}}),e.apiUrl(O))}$t.setFormSecurityRoles=i$;function hw(e){let t=e?.formxml;return typeof t=="string"&&t.includes(gw.GENPAGE_CONTROL_NAME)?t:void 0}function ff(e,t){try{return(0,gw.activeEmbedBindings)(e)}catch(r){throw new Ui.SdkError($t.FORM_GENPAGE_TARGET_UNVERIFIABLE,`Refusing to push the form: the ${t} formxml could not be parsed, so the generative pages it embeds cannot be verified (${r instanceof Error?r.message:String(r)}).`)}}async function yw(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,ZB.findMissingGenPages)(e,i,"form generative-page preflight");if(o.length>0)throw new Ui.SdkError($t.FORM_GENPAGE_TARGET_NOT_FOUND,`Refusing to push the form: it embeds generative page(s) ${o.map(a=>`'${a}'`).join(", ")} that do not exist in this environment. Push the page before the form that embeds it.`)}async function o$(e,t,r,n){var i;(0,ut.requireEtag)(n,"form",t);let o=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,lr.odataQuery)([["$select","formid,formxml"]]),a=(0,ut.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(0,ut.readEtag)(a);if(s===null||s!==n)throw new Ui.SdkError(ut.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!==""?ff(l,"server"):[];await yw(e,ff(r,"payload"),u)}function bw(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 a$(e,t){var r,n;let o=`/systemforms(${(0,lr.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,lr.odataQuery)([["$select","formid,formxml"]]),s=(r=(0,ut.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,df.parseXmlRoot)(s,"<form/>"),u=bw(l,pf);if(!u)return;let c=[],d=!1,p=u.childNodes;for(let m=0;m<p.length;m+=1){let h=p[m];if(h.nodeType!==1)continue;let g=h;if(g.tagName==="Everyone")d=!0;else if(g.tagName==="Role"){let y=(n=g.getAttribute("Id"))!==null&&n!==void 0?n:"";y&&c.push(y.replace(/[{}]/g,"").toLowerCase())}}let f=u.getAttribute("Order");return{...d?{everyone:!0}:{},...c.length>0?{roleIds:c}:{},fallbackForm:u.getAttribute("FallbackForm")==="true",...f!==null&&f!==""?{order:Number(f)}:{}}}$t.getFormSecurityRoles=a$});var vu=b(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.disassociateRecords=Oe.associateRecords=Oe.createRecordsBulk=Oe.upsertRecord=Oe.queryAllRecords=Oe.queryRecords=Oe.getRecord=Oe.deleteRecord=Oe.updateRecord=Oe.createRecord=void 0;var s$=Rt(),Dr=be(),mt=ae(),hu=re(),Jr=Vl();function gu(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 l$(e,t,r){let i=`/${await(0,Jr.resolveEntitySetName)(e,t)}`,o=(0,Dr.ensureSuccess)(await e.post(i,gu(r)),e.apiUrl(i)),a=(0,Dr.readCreatedId)(o,`${t}id`);if(!a)throw new hu.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}Oe.createRecord=l$;async function u$(e,t,r,n){let i=(0,mt.normalizeGuid)(r,"id"),a=`/${await(0,Jr.resolveEntitySetName)(e,t)}(${i})`;(0,Dr.ensureSuccess)(await e.patch(a,gu(n)),e.apiUrl(a))}Oe.updateRecord=u$;async function c$(e,t,r){let n=(0,mt.normalizeGuid)(r,"id"),o=`/${await(0,Jr.resolveEntitySetName)(e,t)}(${n})`;(0,Dr.ensureSuccess)(await e.delete(o),e.apiUrl(o))}Oe.deleteRecord=c$;async function d$(e,t,r,n){var i;let o=(0,mt.normalizeGuid)(r,"id"),a=await(0,Jr.resolveEntitySetName)(e,t),s=(0,mt.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),l=`/${a}(${o})${s}`;return(i=(0,Dr.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)!==null&&i!==void 0?i:{}}Oe.getRecord=d$;function p$(e){return e?.fetchXml?(0,mt.odataQuery)([["fetchXml",e.fetchXml]]):(0,mt.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 ww(e,t,r){var n,i;if(r?.paginate){if(r.top!==void 0)throw new hu.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 hu.InvalidArgumentError("queryRecords: `paginate` is not supported with `fetchXml` \u2014 FetchXML paging uses a paging cookie (page / fetchxmlpagingcookie), not @odata.nextLink. Page the FetchXML manually, or use an OData query.")}let a=`/${await(0,Jr.resolveEntitySetName)(e,t)}${p$(r)}`;return r?.paginate?(0,s$.collectPages)(e,a,"queryRecords"):(i=(n=(0,Dr.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]}Oe.queryRecords=ww;async function f$(e,t,r){return ww(e,t,{...r,paginate:!0})}Oe.queryAllRecords=f$;function m$(e){if("id"in e)return`(${(0,mt.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,mt.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,mt.assertODataName)(e.key,"alternate key name")}=${t})`}async function h$(e,t,r,n){let i=m$(r),a=`/${await(0,Jr.resolveEntitySetName)(e,t)}${i}`,s=(0,Dr.ensureSuccess)(await e.patch(a,gu(n)),e.apiUrl(a)),l=s.status===201,u=(0,Dr.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,mt.normalizeGuid)(r.id,"id"):""),created:l}}Oe.upsertRecord=h$;async function g$(e,t,r){var n,i;if(r.length===0)return[];let o=await(0,Jr.resolveEntitySetName)(e,t),a=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...gu(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Dr.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 hu.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Oe.createRecordsBulk=g$;async function v$(e,t,r,n){let i=(0,mt.normalizeGuid)(r,"id"),o=(0,mt.normalizeGuid)(n.targetId,"targetId"),a=await(0,Jr.resolveEntitySetName)(e,t),s=await(0,Jr.resolveEntitySetName)(e,n.targetEntity),l=(0,mt.assertODataName)(n.relationshipName,"relationshipName"),u=`/${a}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,Dr.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Oe.associateRecords=v$;async function y$(e,t,r,n,i){let o=(0,mt.normalizeGuid)(r,"id"),a=(0,mt.normalizeGuid)(i,"targetId"),s=await(0,Jr.resolveEntitySetName)(e,t),l=(0,mt.assertODataName)(n,"relationshipName"),u=`/${s}(${o})/${l}(${a})/$ref`;(0,Dr.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Oe.disassociateRecords=y$});var bu=b(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.base64ToUtf8=Qr.base64ToBytes=Qr.bytesToBase64=Qr.utf8ToBase64=void 0;var hf=32768,Ut="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function yu(){return globalThis}function b$(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 w$(e){let t="";for(let r=0;r<e.length;r+=hf)t+=String.fromCharCode(...e.subarray(r,r+hf));return t}function A$(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+="/":Ut.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function E$(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+=Ut[i>>18&63]+Ut[i>>12&63]+Ut[i>>6&63]+Ut[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Ut[i>>18&63]}${Ut[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,o=Ut[i>>18&63],a=Ut[i>>12&63],s=Ut[i>>6&63];t+=`${o}${a}${s}=`}return t}function C$(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=Ut.indexOf(e[o])<<18|Ut.indexOf(e[o+1])<<12|(e[o+2]==="="?0:Ut.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:Ut.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 S$(e){let t=yu();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return Aw(r?new r().encode(e):b$(e))}Qr.utf8ToBase64=S$;function Aw(e){let t=yu();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(w$(e)):E$(e)}Qr.bytesToBase64=Aw;function Ew(e){let t=yu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=A$(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return C$(r)}Qr.base64ToBytes=Ew;function N$(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>=hf&&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,p=!0;for(let f=0;f<s;f+=1,d+=1){let m=d<e.length?e[d]:-1;if(m<u||m>c){p=!1;break}u=128,c=191,l=l<<6|m&63}p?(i(l),o=d):(i(65533),o=d)}return n(),r}function D$(e){let t=yu();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):N$(Ew(e))}Qr.base64ToUtf8=D$});var Dw=b(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.deleteWebResource=Xr.getWebResource=Xr.updateWebResource=Xr.createWebResource=void 0;var _$=nr(),bs=be(),wu=ae(),I$=bu(),Cw=re(),T$={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function Sw(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,I$.utf8ToBase64)(e.content)}async function Nw(e,t){return(0,_$.publishWebResourceById)(e,t)}async function P$(e,t){var r;let n=Sw(t);if(n===void 0)throw new Cw.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:T$[t.type],content:n};t.description&&(i.description=t.description);let o=(0,bs.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,bs.readCreatedId)(o,"webresourceid");if(!a)throw new Cw.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await Nw(e,a),{id:a,name:t.name}}Xr.createWebResource=P$;async function R$(e,t,r){let n=(0,wu.normalizeGuid)(t,"id"),i={},o=Sw(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,bs.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),r.publish!==!1&&await Nw(e,n)}Xr.updateWebResource=R$;async function O$(e,t){var r;let i=`/webresourceset(${(0,wu.normalizeGuid)(t,"id")})${(0,wu.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,bs.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}Xr.getWebResource=O$;async function x$(e,t){let n=`/webresourceset(${(0,wu.normalizeGuid)(t,"id")})`;(0,bs.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Xr.deleteWebResource=x$});var Au=b(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.applyAppSettings=Ze.setAppSetting=Ze.readAppSettings=Ze.resolveSettingDefinitions=Ze.APP_SETTING_UNSET=Ze.APP_SETTING_OFF=Ze.APP_SETTING_ON=Ze.HEADER_AND_NAVIGATION_REFRESH=void 0;var Bo=be(),Dn=ae();Ze.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";Ze.APP_SETTING_ON="2";Ze.APP_SETTING_OFF="1";Ze.APP_SETTING_UNSET="0";function Tw(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Dn.odataQuery)([["$select",e],["$filter",t]])}async function Pw(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,Dn.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,Dn.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",a]])}`,u=((n=(r=(0,Bo.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}Ze.resolveSettingDefinitions=Pw;async function L$(e,t){var r,n,i,o;let a=(0,Dn.normalizeGuid)(t,"App id"),s=Tw("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${a}`),u=((n=(r=(0,Bo.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);if(u.length===0)return[];let c=[...new Set(u.map(p=>p._settingdefinitionid_value).filter(Boolean))],d=new Map;if(c.length>0){let p=c.map(h=>`settingdefinitionid eq ${(0,Dn.normalizeGuid)(h,"Setting definition id")}`).join(" or "),f=`/settingdefinitions${(0,Dn.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",p]])}`,m=(0,Bo.ensureSuccess)(await e.get(f),e.apiUrl(f));for(let h of((o=(i=m.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[]).filter(Boolean))h.settingdefinitionid&&d.set(h.settingdefinitionid.toLowerCase(),h)}return u.map(p=>{var f,m,h,g,y;let w=d.get(((f=p._settingdefinitionid_value)!==null&&f!==void 0?f:"").toLowerCase());return{id:(m=p.appsettingid)!==null&&m!==void 0?m:"",name:(g=(h=w?.uniquename)!==null&&h!==void 0?h:p._settingdefinitionid_value)!==null&&g!==void 0?g:"",value:(y=p.value)!==null&&y!==void 0?y:"",...w?.displayname?{displayName:w.displayname}:{}}})}Ze.readAppSettings=L$;async function _w(e,t,r){var n,i,o;let a=Tw("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,Bo.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 Rw(e,t,r,n){let i=(0,Dn.normalizeGuid)(t,"App id"),a=(await Pw(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,Dn.normalizeGuid)(s,"Setting definition id"),u=await _w(e,i,l);if(u)return Iw(e,u,n);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${l})`,value:n},p,f;try{if(p=await e.post(c,d),p.status>=200&&p.status<300)return"created"}catch(h){f=h}let m;try{m=await _w(e,i,l)}catch{m=void 0}if(m)return Iw(e,m,n);throw p&&(0,Bo.ensureSuccess)(p,e.apiUrl(c)),f}Ze.setAppSetting=Rw;async function Iw(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,Dn.normalizeGuid)(t.id,"App setting id")})`;return(0,Bo.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function k$(e,t,r){var n;let i=[];for(let[o,a]of Object.entries(r??{}))try{await Rw(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}Ze.applyAppSettings=k$});var Cu=b(Eu=>{"use strict";Object.defineProperty(Eu,"__esModule",{value:!0});Eu.HEADER_NAV_BOOLEAN_RULE=void 0;Eu.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var Mw=b(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.deleteSolution=ue.importSolution=ue.exportSolution=ue.removeSolutionComponent=ue.addSolutionComponent=ue.setSolutionVersion=ue.createSolution=ue.createPublisher=ue.getSolution=ue.fetchSolutionComponents=ue.resolveGenPageComponentType=ue.SolutionComponentType=void 0;var kw=Rt(),ur=be(),At=ae(),li=re();ue.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80};var Ow=[ue.SolutionComponentType.SavedQuery,ue.SolutionComponentType.Workflow,ue.SolutionComponentType.SavedQueryVisualization,ue.SolutionComponentType.SystemForm,ue.SolutionComponentType.AppModule],xw="uxagentproject",Lw=new WeakMap;async function Fw(e){var t;let r=Lw.get(e);if(r!==void 0)return r;let n=`/EntityDefinitions(LogicalName='${xw}')${(0,At.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status===404)return;(0,ur.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 li.SdkError("GENPAGE_COMPONENT_TYPE_UNRESOLVED",`A generative page's solution component type \u2014 the ObjectTypeCode of '${xw}' \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 Lw.set(e,o),o}ue.resolveGenPageComponentType=Fw;async function F$(e,t){let r=(0,At.normalizeGuid)(t,"solutionId"),n=await Fw(e),o=(n===void 0?Ow:[...Ow,n]).map(u=>`msdyn_componenttype eq ${u}`).join(" or "),a=`/msdyn_solutioncomponentsummaries${(0,At.odataQuery)([["$select","msdyn_objectid,msdyn_componenttype,msdyn_workflowcategory,msdyn_displayname,msdyn_name"],["$filter",`msdyn_solutionid eq ${r} and (${o})`]])}`,l=(await(0,kw.collectPages)(e,a,"fetchSolutionComponents")).filter(u=>typeof u.msdyn_objectid=="string").map(u=>{let c=Number(u.msdyn_componenttype);return{objectId:u.msdyn_objectid,componentType:c,...n!==void 0&&c===n?{genPage:!0}:{},workflowCategory:u.msdyn_workflowcategory==null?void 0:Number(u.msdyn_workflowcategory),displayName:u.msdyn_displayname,name:u.msdyn_name}});return n===void 0?l:[...l,...await M$(e,r,l,n)]}ue.fetchSolutionComponents=F$;async function M$(e,t,r,n){let i=new Set(r.map(l=>l.objectId.toLowerCase())),o=`/solutioncomponents${(0,At.odataQuery)([["$select","objectid,componenttype"],["$filter",`_solutionid_value eq ${t} and componenttype eq ${n}`]])}`,a=await(0,kw.collectPages)(e,o,"fetchSolutionComponents(draft pages)"),s=[];for(let l of a){let u=typeof l.objectid=="string"?l.objectid:void 0;u&&!i.has(u.toLowerCase())&&(i.add(u.toLowerCase()),s.push({objectId:u,componentType:n,genPage:!0}))}return s}function B$(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 $$(e,t){var r,n,i,o,a,s,l,u,c,d;let p=String(t??"").trim();if(!p)throw new li.InvalidArgumentError("getSolution: a solution unique name or id is required.");let f=B$(p)?`solutionid eq ${(0,At.normalizeGuid)(p,"solutionId")}`:`uniquename eq '${(0,At.odataLiteral)(p)}'`,m=`/solutions${(0,At.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",f]])}`,y=((n=(r=(0,ur.ensureSuccess)(await e.get(m),e.apiUrl(m)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!y?.solutionid)throw new li.InvalidArgumentError(`No solution found for '${t}'.`);let w=y.publisherid;if(!w?.publisherid)throw new li.InvalidArgumentError(`Solution '${(i=y.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in w))throw new li.InvalidArgumentError(`Solution '${(o=y.uniquename)!==null&&o!==void 0?o:t}' returned a publisher without a customizationprefix property (partial expansion), so its prefix cannot be determined.`);return{solutionId:(0,At.normalizeGuid)(y.solutionid,"solutionId"),uniqueName:(a=y.uniquename)!==null&&a!==void 0?a:"",friendlyName:(s=y.friendlyname)!==null&&s!==void 0?s:"",version:(l=y.version)!==null&&l!==void 0?l:"",isManaged:!!y.ismanaged,publisherId:(0,At.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}}ue.getSolution=$$;async function U$(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,ur.ensureSuccess)(await e.post("/publishers",n),e.apiUrl("/publishers")),o=(0,ur.readCreatedId)(i,"publisherid");if(!o)throw new li.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}ue.createPublisher=U$;async function q$(e,t){var r;let n=(0,At.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,ur.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,ur.readCreatedId)(o,"solutionid");if(!a)throw new li.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}ue.createSolution=q$;async function V$(e,t,r){let i=`/solutions(${(0,At.normalizeGuid)(t,"solutionId")})`;(0,ur.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}ue.setSolutionVersion=V$;async function G$(e,t){var r;let i={ComponentId:(0,At.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,ur.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}ue.addSolutionComponent=G$;async function z$(e,t,r,n){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,At.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,ur.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}ue.removeSolutionComponent=z$;async function W$(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},a=(n=(0,ur.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!a)throw new li.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}ue.exportSolution=W$;async function j$(e,t){var r,n;let i={OverwriteUnmanagedCustomizations:(r=t.overwriteUnmanagedCustomizations)!==null&&r!==void 0?r:!0,PublishWorkflows:(n=t.publishWorkflows)!==null&&n!==void 0?n:!0,CustomizationFile:t.base64};t.importJobId&&(i.ImportJobId=(0,At.normalizeGuid)(t.importJobId,"importJobId")),(0,ur.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution"))}ue.importSolution=j$;async function H$(e,t){let n=`/solutions(${(0,At.normalizeGuid)(t,"solutionId")})`;(0,ur.ensureSuccess)(await e.delete(n),e.apiUrl(n))}ue.deleteSolution=H$});var bf=b(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.compileGenPage=Ee.legacyEnumsNeeded=Ee.createGenPageTypeScriptLoader=Ee.acceptGenPageTypeScript=Ee.isLoadableGenPageOutput=Ee.GENPAGE_RUNTIME_TYPES_END=Ee.GENPAGE_RUNTIME_TYPES_BEGIN=Ee.GENPAGE_TYPESCRIPT_VERSION=void 0;var $o=re();Ee.GENPAGE_TYPESCRIPT_VERSION="5.8.3";Ee.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";Ee.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var K$=/(import\s+[^'"]+)(['"`])(\.\/RuntimeTypes)\2;?\s*/g,ui="./RuntimeTypes",J$=/\b(import\s.+from\s+['"]|import\s*['"]|export\s)/;function Q$(e){return e!==void 0&&e!==""&&J$.test(e)}Ee.isLoadableGenPageOutput=Q$;var Bw=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function qw(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?Bw.filter(s=>typeof n?.[s]!="function"):[...Bw];if(!n||i.length>0)throw new $o.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@${Ee.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof n.version=="string"?n.version:"",a=Ee.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new $o.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 (${Ee.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${Ee.GENPAGE_TYPESCRIPT_VERSION}.`);return n}Ee.acceptGenPageTypeScript=qw;function X$(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new $o.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@${Ee.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(qw).catch(r=>{throw t=void 0,r instanceof $o.SdkError?r:new $o.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}}Ee.createGenPageTypeScriptLoader=X$;var Vw=e=>`${e.kind}:${e.pos}:${e.end}`;function Y$(e,t){return()=>r=>{let n=i=>{let o=e.getParseTreeNode(i);o&&t.add(Vw(o)),e.forEachChild(i,n)};return n(r),r}}function yf(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}var Z$=2301;function $w(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:yf(e),reportDiagnostics:!0,...r?{transformers:{after:[Y$(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 Uw=e=>e.startsWith(".")||e.startsWith("/"),gf={line:1,column:1};function vf(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):gf},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(p=>p.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 gf}}}function eU(e,t,r,n){var i,o;let a=[],s=vf(e,r),l=(m,h,g)=>{a.push({...m,rule:h,code:0,message:g})},u=(m,h)=>{var g;return(e.canHaveModifiers(m)?(g=e.getModifiers(m))!==null&&g!==void 0?g:[]:[]).some(y=>y.kind===h)},c=(m,h)=>l(m,"genpage-relative-import",`'${h}' cannot resolve at runtime: the page is loaded as a single module from a blob URL, so the only relative import it may have is './RuntimeTypes'`),d="genpage-runtime-types-import-form",p=!1,f=new Set;for(let m of t.statements){if(e.isExportAssignment(m)){p=p||!m.isExportEquals;continue}if(e.isFunctionDeclaration(m)||e.isClassDeclaration(m)){u(m,e.SyntaxKind.ExportKeyword)&&u(m,e.SyntaxKind.DefaultKeyword)&&(p=!0),m.name&&f.add(m.name.text);continue}if(e.isExportDeclaration(m)){let w=m.exportClause;w&&e.isNamedExports(w)&&w.elements.some(S=>S.name.text==="default")&&(p=!0);let C=m.moduleSpecifier&&e.isStringLiteral(m.moduleSpecifier)?m.moduleSpecifier.text:void 0;C===ui?l(s.statement(C,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):C!==void 0&&Uw(C)&&c(s.statement(C,"export"),C);continue}if(!e.isImportDeclaration(m)||!e.isStringLiteral(m.moduleSpecifier))continue;let h=m.moduleSpecifier.text,g=m.importClause;if(h!==ui){Uw(h)&&c(s.statement(h,"import"),h),g?.name&&f.add(g.name.text);let w=g?.namedBindings;w&&e.isNamespaceImport(w)?f.add(w.name.text):w&&e.isNamedImports(w)&&w.elements.forEach(C=>f.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 y=g.namedBindings;if(y&&e.isNamespaceImport(y))l(s.binding(y.name.text),d,"a namespace import of './RuntimeTypes' is undefined at runtime \u2014 its enums are inlined under their own names; import the names instead");else if(y&&e.isNamedImports(y))for(let w of y.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,T=s.element(h,C);S!==C?l(T,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(T,"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(T,"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(p||l(gf,"genpage-no-default-export","the page has no default export \u2014 the runtime renders the module's default export as the page component"),n?.text)for(let m of f)n.enums.has(m)&&l(s.binding(m),"genpage-runtime-types-collision",`'${m}' is declared at the page's module scope and is also one of its inlined choice enums, so the compiled page would declare it twice and fail to load. Rename the page's binding, or import the enum from './RuntimeTypes'.`);return a}function Gw(e,t,r){let n,i=()=>{if(!n){let m={getSourceFile:g=>g===t.fileName?t:void 0,getDefaultLibFileName:()=>"lib.d.ts",writeFile:()=>{},getCurrentDirectory:()=>"",getCanonicalFileName:g=>g,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>`
-`,fileExists:g=>g===t.fileName,readFile:()=>{},directoryExists:()=>!0,getDirectories:()=>[]},h={...r,noLib:!0,noResolve:!0,allowJs:!0,types:[],alwaysStrict:!0,moduleDetection:e.ModuleDetectionKind.Force};n=e.createProgram({rootNames:[t.fileName],options:h,host:m})}return n},o,a=()=>(o||(o=i().getTypeChecker()),o),s,l=()=>{if(!s){s=new Map;try{for(let m of i().getSemanticDiagnostics(t))m.code===Z$&&typeof m.start=="number"&&s.set(m.start,e.flattenDiagnosticMessageText(m.messageText," "))}catch{}}return s},u=m=>e.isImportSpecifier(m)?m.parent.parent.parent:e.isImportClause(m)?m.parent:e.isNamespaceImport(m)?m.parent.parent:void 0,c=m=>{let h=u(m);return h!==void 0&&e.isImportDeclaration(h)&&e.isStringLiteral(h.moduleSpecifier)&&h.moduleSpecifier.text===ui},d=m=>{var h;for(let g=m;g;g=g.parent)if(e.canHaveModifiers(g)&&((h=e.getModifiers(g))!==null&&h!==void 0?h:[]).some(y=>y.kind===e.SyntaxKind.DeclareKeyword))return!0;return!1},p=m=>d(m)||e.isImportEqualsDeclaration(m)&&(m.isTypeOnly||e.isExternalModuleReference(m.moduleReference))||e.isImportClause(m)&&m.isTypeOnly||e.isNamespaceImport(m)&&m.parent.isTypeOnly||e.isImportSpecifier(m)&&(m.isTypeOnly||m.parent.parent.isTypeOnly),f=m=>{var h;return((h=m?.declarations)!==null&&h!==void 0?h:[]).some(g=>!c(g)&&!p(g))};return{pageOwns:m=>{let h=m.parent;return f(e.isShorthandPropertyAssignment(h)&&h.name===m?a().getShorthandAssignmentValueSymbol(h):a().getSymbolAtLocation(m))},pageOwnsLocalExport:m=>f(a().getExportSpecifierLocalTargetSymbol(m)),initializerShadow:m=>l().get(m.getStart(t))}}function tU(e,t,r,n){let i=[],o=r?.enums;if(!o||o.size===0)return i;let a=(u,c,d)=>{let p=t.getLineAndCharacterOfPosition(u.getStart(t));i.push({line:p.line+1,column:p.character+1,rule:c,code:0,message:d})},s=Gw(e,t,yf(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 f=u.argumentExpression;e.isStringLiteral(f)||e.isNoSubstitutionTemplateLiteral(f)?(c=u.expression,d=f.text):e.isNumericLiteral(f)&&(c=u.expression,d=String(Number(f.text)))}let p=c&&o.has(c.text)&&n.has(Vw(u))&&!s.pageOwns(c)?o.get(c.text):void 0;if(c&&p&&d!==void 0){let f=e.isPropertyAccessExpression(u)?`${p.name}.${d}`:`${p.name}[${JSON.stringify(d)}]`,m=Object.prototype.hasOwnProperty.call(p.runtime,d)?p.runtime[d]:void 0,h=p.labels.get(d),g;m===void 0?g={rule:"genpage-enum-member-unknown",message:`${f} is undefined at runtime: '${p.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: ${[...p.labels.keys()].map(w=>`'${w}'`).join(", ")}`}:h&&typeof m!="number"?g={rule:"genpage-enum-member-clobbered",message:`${f} is the string '${String(m)}' at runtime, not a choice value: the label '${d}' looks like a number, and another option's reverse mapping overwrites it. Use the choice's numeric value instead.`}:h&&h.length>1&&(g={rule:"genpage-enum-member-ambiguous",message:`${f} labels more than one choice (${h.join(", ")}); the compiled value is whichever option comes last. Use the choice's numeric value instead.`});let y=g?s.initializerShadow(c):void 0;g&&y!==void 0?a(u,"genpage-enum-initializer-shadowed",`${f} does not read the choice enum at runtime. ${y} (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 rU(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===ui)}function nU(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=new Set(r.statements.filter(a=>e.isImportDeclaration(a)&&e.isStringLiteral(a.moduleSpecifier)&&a.moduleSpecifier.text===ui).map(a=>a.getStart(r))),i=!0;return{code:t.replace(K$,(...a)=>(n.has(a[a.length-2])||(i=!1),"")),exact:i}}function zw(e,t,r){if(!r||r.size===0)return[];let n=Gw(e,t,{...yf(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===ui&&((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))}Ee.legacyEnumsNeeded=zw;function iU(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 oU(e,t,r,n){let i=new Set,o=$w(e,t,i);if(o.diagnostics.length>0)return o;let a=e.createSourceFile("page.tsx",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.TSX),s=e.createSourceFile("page.js",o.code,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),l=iU(r,n,zw(e,s,n)),u=[...eU(e,s,a,l),...tU(e,a,l,i)];if(!l?.text)return{code:o.code,diagnostics:u};let c=$w(e,l.text);if(c.diagnostics.length>0)throw new $o.SdkError("GENPAGE_RUNTIME_TYPES_INVALID",`The generated runtime types do not compile (${c.diagnostics.map(m=>`${m.line}:${m.column} ${m.message}`).join("; ")}). This is an SDK defect: the page was not written.`);let d=nU(e,o.code),p=d.code;return u.length===0&&!d.exact?u.push({...vf(e,a).statement(ui,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"the maker portal's patch would remove more than this './RuntimeTypes' import: a comment or other text before it contains the word 'import', and the pattern would delete from there \u2014 taking the code in between with it. Reword or move that text."}):u.length===0&&rU(e,p)&&u.push({...vf(e,a).statement(ui,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"this './RuntimeTypes' import is not one the maker portal's patch can remove (a comment holding a quote inside it stops the pattern), so it would reach the runtime, which cannot load it. Write it on one line, as 'import { name } from './RuntimeTypes';'."}),{code:[Ee.GENPAGE_RUNTIME_TYPES_BEGIN,c.code,Ee.GENPAGE_RUNTIME_TYPES_END,p].join(`
+`);if(p===-1)return;let m=f.slice(0,p),h=f.slice(p+4);if(!/^Content-Type:\s*application\/http\b/im.test(m))return;let g=/^HTTP\/1\.[01] (\d{3})\b/.exec(h);if(!g||((i=h.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let v=(o=/^Content-ID:\s*(\S+)/im.exec(m))===null||o===void 0?void 0:o[1];if(v===void 0||d.has(v)||!u.has(v))return;d.add(v),c.push({status:Number(g[1]),text:h,contentId:v})}return c.length===0?void 0:c}Xt.parseChangeSetParts=sm;async function iq(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:o}=am(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,om.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new Ii.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`);let l=FA(a.body,o);if(l===void 0)throw new Ii.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`);if(l.length!==t.length)throw new Ii.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the change set reported ${l.length} result(s) for ${t.length} operation(s)`);let u=l.find(c=>c<200||c>=300);if(u!==void 0)throw new Ii.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}Xt.postChangeSet=iq;function MA(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}}Xt.partResponse=MA;async function oq(e,t,r){let{body:n,batchId:i,contentIds:o}=am(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch"),l=sm(a.body,o),u=l?.find(c=>c.status<200||c.status>=300);if(u&&(0,om.ensureSuccess)(MA(u),e.apiUrl(t[o.indexOf(u.contentId)].path)),(0,om.ensureSuccess)(a,s),!l||l.length!==t.length)throw new Ii.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))}Xt.sendChangeSet=oq});var rc=b(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.updateTable=re.deleteAlternateKey=re.createAlternateKey=re.deleteGlobalOptionSet=re.createGlobalOptionSet=re.deleteRelationship=re.deleteColumn=re.updateColumn=re.deleteTable=re.createRelationship=re.insertStatusValue=re.createCustomerColumn=re.createColumns=re.setColumnVisualization=re.getColumnVisualization=re.createColumn=re.createTable=re.resolveEntitySetName=re.pluralFallback=void 0;var ve=we(),te=ae(),bn=ho(),Ne=X(),aq=Qs(),sq={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 qe(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:lq(e,t)}}var $A=65535;function lq(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 Ne.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 Ne.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>$A)throw new Ne.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${$A})`);if(i.has(s))throw new Ne.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new Ne.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(a,s)})}function VA(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new Ne.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}re.pluralFallback=VA;function Ys(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}function cm(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function BA(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function Xs(e){let t=(0,ve.readCreatedId)(e,"MetadataId");if(!t)throw new Ne.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function uq(e,t,r){var n,i,o,a,s,l,u,c,d,f,p,m,h,g,v,w,C,E,k,R,T,I,P,F;if(t.defaultValue!==void 0&&e!=="boolean")throw new Ne.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new Ne.InvalidArgumentError(`createColumn: 'integerFormat' applies to integer columns, but '${t.schemaName}' is of type '${e}'.`);switch(e){case"string":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},MaxLength:(n=t.maxLength)!==null&&n!==void 0?n:100,FormatName:{Value:(i=t.stringFormat)!==null&&i!==void 0?i:"Text"}};case"memo":return{"@odata.type":"Microsoft.Dynamics.CRM.MemoAttributeMetadata",AttributeType:"Memo",AttributeTypeName:{Value:"MemoType"},MaxLength:(o=t.maxLength)!==null&&o!==void 0?o:2e3,Format:"TextArea"};case"integer":return{"@odata.type":"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",AttributeType:"Integer",AttributeTypeName:{Value:"IntegerType"},Format:(a=t.integerFormat)!==null&&a!==void 0?a:"None",MinValue:(s=t.minValue)!==null&&s!==void 0?s:-2147483648,MaxValue:(l=t.maxValue)!==null&&l!==void 0?l:2147483647};case"bigint":return{"@odata.type":"Microsoft.Dynamics.CRM.BigIntAttributeMetadata",AttributeType:"BigInt",AttributeTypeName:{Value:"BigIntType"}};case"double":return{"@odata.type":"Microsoft.Dynamics.CRM.DoubleAttributeMetadata",AttributeType:"Double",AttributeTypeName:{Value:"DoubleType"},Precision:(u=t.precision)!==null&&u!==void 0?u:2,MinValue:(c=t.minValue)!==null&&c!==void 0?c:-1e11,MaxValue:(d=t.maxValue)!==null&&d!==void 0?d:1e11};case"decimal":return{"@odata.type":"Microsoft.Dynamics.CRM.DecimalAttributeMetadata",AttributeType:"Decimal",AttributeTypeName:{Value:"DecimalType"},Precision:(f=t.precision)!==null&&f!==void 0?f:2,MinValue:(p=t.minValue)!==null&&p!==void 0?p:-1e11,MaxValue:(m=t.maxValue)!==null&&m!==void 0?m:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(h=t.precision)!==null&&h!==void 0?h:2,PrecisionSource:2,MinValue:(g=t.minValue)!==null&&g!==void 0?g:0,MaxValue:(v=t.maxValue)!==null&&v!==void 0?v: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:qe((C=t.trueLabel)!==null&&C!==void 0?C:"Yes",r)},FalseOption:{Value:0,Label:qe((E=t.falseLabel)!==null&&E!==void 0?E:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(k=t.dateFormat)!==null&&k!==void 0?k:"DateAndTime"};case"choice":return UA(t,r,!1);case"multiChoice":return UA(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(R=t.maxSizeKb)!==null&&R!==void 0?R:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(T=t.isPrimaryImage)!==null&&T!==void 0?T:!1,MaxSizeInKB:(I=t.maxSizeKb)!==null&&I!==void 0?I:10240};case"autonumber":return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(P=t.maxLength)!==null&&P!==void 0?P:100,AutoNumberFormat:(F=t.autoNumberFormat)!==null&&F!==void 0?F:""};default:throw new Ne.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function UA(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 Ne.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:qe(o.label,t)}))},i}var lm=new WeakMap;async function cq(e,t){var r,n;let i=(r=lm.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,ve.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new Ne.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,te.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=lm.get(e);return l||(l=new Map,lm.set(e,l)),l.set(t,s),s}re.resolveEntitySetName=cq;async function dq(e,t){var r,n,i,o,a,s,l,u,c,d,f,p,m,h,g;let v=(r=t.languageCode)!==null&&r!==void 0?r:bn.DEFAULT_LCID,w=cm(t.schemaName),C=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${w}_Name`,E={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:C,RequiredLevel:Ys("None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:qe((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",v),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(E.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&zA(t.columns,"createTable");let k={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:qe(t.displayName,v),DisplayCollectionName:qe((a=t.pluralName)!==null&&a!==void 0?a:VA(t.displayName),v),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:[E,...((c=t.columns)!==null&&c!==void 0?c:[]).map(Te=>dm(Te,v))]};t.description&&(k.Description=qe(t.description,v));let R="/EntityDefinitions",T=(0,ve.ensureSuccess)(await e.post(R,k),e.apiUrl(R)),I=Xs(T),P=`/EntityDefinitions(${I})`+(0,te.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),F=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),z=Math.max(0,(f=t.readBackDelayMs)!==null&&f!==void 0?f:1e3),Ie;for(let Te=1;Te<=F;Te+=1){let Qe=await e.get(P);if(Qe.status>=200&&Qe.status<300){Ie=Qe;break}Qe.status!==404&&(0,ve.ensureSuccess)(Qe,e.apiUrl(P)),Te<F&&z>0&&await new Promise(ce=>setTimeout(ce,z))}if(!Ie)throw new Ne.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${I}) but its metadata was still not readable after ${F} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${I}) once the environment catches up, or raise 'readBackAttempts'.`);let yt=Ie.body;return{logicalName:(p=yt.LogicalName)!==null&&p!==void 0?p:t.schemaName.toLowerCase(),metadataId:I,entitySetName:(m=yt.EntitySetName)!==null&&m!==void 0?m:"",primaryIdAttribute:(h=yt.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=yt.PrimaryNameAttribute)!==null&&g!==void 0?g:C.toLowerCase()}}re.createTable=dq;function dm(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,o={...uq(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:Ys((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:qe(e.displayName,i)};return e.description&&(o.Description=qe(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),GA(o,e),o}function GA(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 fq(e,t,r){var n;let i=dm(r,(n=r.languageCode)!==null&&n!==void 0?n:bn.DEFAULT_LCID),o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,a=(0,ve.ensureSuccess)(await e.post(o,i),e.apiUrl(o)),s={logicalName:r.schemaName.toLowerCase(),metadataId:Xs(a)};if(r.visualization&&r.visualization!=="None")try{await KA(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new Ne.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,Ne.attachCause)(u,l),u}return s}re.createColumn=fq;var Ca="/controlconfigurations",WA="CustomRenderersConfiguration",um={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 zA(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new Ne.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 jA(e){return JSON.stringify({type:um[e]})}function pq(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(um).find(i=>um[i]===r);return n??"None"}async function HA(e,t,r){var n,i;let o=`entitylogicalname eq '${(0,te.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,te.odataLiteral)(r)}'`,a=`${Ca}${(0,te.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",o]])}`,l=(i=(n=(0,ve.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 mq(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,ve.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!a)throw new Ne.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,te.normalizeGuid)(a,"MetadataId")}async function KA(e,t,r,n,i){let o={name:WA,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:jA(i),"[email protected]":`/attributes(${(0,te.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,ve.ensureSuccess)(await e.post(Ca,o),e.apiUrl(Ca))}async function hq(e,t,r){var n;let i=await HA(e,t,r);return pq((n=i[0])===null||n===void 0?void 0:n.metadatajson)}re.getColumnVisualization=hq;async function gq(e,t,r,n){let o=(await HA(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of o){let c=`${Ca}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,ve.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,l=await mq(e,t,r);if(a){let u=`${Ca}(${(0,te.normalizeGuid)(a,"controlconfigurationid")})`,c={name:WA,metadatajson:jA(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,ve.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await KA(e,t,r,l,n);for(let u of s){let c=`${Ca}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,ve.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}re.setColumnVisualization=gq;async function yq(e,t,r){if(r.length===0)return;if(zA(r,"createColumns"),!e.supportsAtomicBatch)throw new Ne.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,aq.postChangeSet)(e,r.map(i=>{var o;return{method:"POST",path:n,body:dm(i,(o=i.languageCode)!==null&&o!==void 0?o:bn.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}re.createColumns=yq;async function vq(e,t,r){var n,i,o,a;let s=(n=r.languageCode)!==null&&n!==void 0?n:bn.DEFAULT_LCID,l=cm(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:qe(r.displayName,s),RequiredLevel:Ys((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,ve.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}re.createCustomerColumn=vq;async function bq(e,t,r){var n,i,o,a,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:bn.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:qe(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,ve.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)}re.insertStatusValue=bq;async function wq(e,t){var r,n,i,o,a;let s=(r=t.languageCode)!==null&&r!==void 0?r:bn.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new Ne.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let f=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${cm(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:Ys((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:qe((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new Ne.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,ve.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:Xs(d),lookupLogicalName:u}}re.createRelationship=wq;async function Aq(e,t){let r=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`;(0,ve.ensureSuccess)(await e.delete(r),e.apiUrl(r))}re.deleteTable=Aq;async function Cq(e,t,r,n){var i,o;let a=(i=n.languageCode)!==null&&i!==void 0?i:bn.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,ve.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=sq[(o=c.AttributeType)!==null&&o!==void 0?o:""];if(!c.MetadataId||!d)throw new Ne.InvalidArgumentError(`cannot update column '${r}' on '${t}' (type '${c.AttributeType}' not supported)`);let f=(0,te.normalizeGuid)(c.MetadataId,"MetadataId"),p=`${s}(${f})/${d}`,m=(0,ve.ensureSuccess)(await e.get(p),e.apiUrl(p)).body;for(let g of Object.keys(m))g.startsWith("@odata.")&&delete m[g];if(m["@odata.type"]=d,n.displayName!==void 0&&(m.DisplayName=qe(n.displayName,a)),n.description!==void 0&&(m.Description=qe(n.description,a)),n.required!==void 0&&(m.RequiredLevel=Ys(n.required)),n.maxLength!==void 0&&(m.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(m.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new Ne.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 Ne.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(m.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(m.Format=n.integerFormat),GA(m,n);let h=`${s}(${f})`;(0,ve.ensureSuccess)(await e.put(h,m,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}re.updateColumn=Cq;async function Eq(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,ve.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new Ne.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,ve.ensureSuccess)(await e.delete(l),e.apiUrl(l))}re.deleteColumn=Eq;async function Sq(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,ve.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 Ne.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,ve.ensureSuccess)(await e.delete(l),e.apiUrl(l))}re.deleteRelationship=Sq;async function qA(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,ve.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 Nq(e,t){var r;let n=t.name.toLowerCase(),i=await qA(e,n);if(i)return{name:n,metadataId:i};let o=(r=t.languageCode)!==null&&r!==void 0?r:bn.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:qe(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:qe(l.label,o)}))};t.description&&(a.Description=qe(t.description,o));let s="/GlobalOptionSetDefinitions";try{let l=(0,ve.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:n,metadataId:Xs(l)}}catch(l){let u;try{u=await qA(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}re.createGlobalOptionSet=Nq;async function Dq(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t.toLowerCase())}')`;(0,ve.ensureSuccess)(await e.delete(r),e.apiUrl(r))}re.deleteGlobalOptionSet=Dq;async function _q(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:bn.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:qe(r.displayName,i),KeyAttributes:r.keyAttributes},a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,s=(0,ve.ensureSuccess)(await e.post(a,o),e.apiUrl(a));return{logicalName:r.schemaName.toLowerCase(),metadataId:Xs(s)}}re.createAlternateKey=_q;async function Iq(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,ve.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new Ne.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,ve.ensureSuccess)(await e.delete(l),e.apiUrl(l))}re.deleteAlternateKey=Iq;async function Tq(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:bn.DEFAULT_LCID,o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`,s=(0,ve.ensureSuccess)(await e.get(o),e.apiUrl(o)).body,l=s.MetadataId;if(!l)throw new Ne.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=qe(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=qe(r.pluralName,i)),r.description!==void 0&&(s.Description=qe(r.description,i)),r.auditEnabled!==void 0&&BA(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&BA(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,ve.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}re.updateTable=Tq});var Pi=b(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.rebuildRaw=Zt.assembleChildren=Zt.spliceChildren=Zt.mergeAttrs=Zt.rawFromNode=Zt.emptyBag=void 0;var Ti=X(),JA=1e6,ic=512;function Pq(){return{a:[],c:[]}}Zt.emptyBag=Pq;function QA(e,t=0){if(t>ic)throw new Ti.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${ic}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>QA(r,t+1))}}Zt.rawFromNode=QA;function Oq(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}Zt.mergeAttrs=Oq;function nc(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>JA)throw new Ti.InvalidArgumentError(`Bag child index must be an integer in [0, ${JA}] (got ${String(l)})`);if(r.has(l))throw new Ti.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}Zt.spliceChildren=nc;function Rq(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:nc(e.w.c,t)};return nc(e.c,[r])}return nc(e.c,t)}Zt.assembleChildren=Rq;function YA(e,t,r,n=0){if(n>ic)throw new Ti.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${ic}`);kq(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,YA(o,t,i,n+1));return i}Zt.rebuildRaw=YA;function kq(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Ti.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new Ti.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 Ti.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 Ti.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var Oi=b(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.installDomShim=void 0;var XA=ya(),ZA=!1,xq={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 Lq(){if(ZA)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=XA.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=XA.XMLSerializer),typeof e.Node>"u"&&(e.Node=xq),ZA=!0}oc.installDomShim=Lq});var Ri=b(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.projectElementBag=Ve.serializeNode=Ve.domEngine=Ve.nodeLikeFromDom=Ve.parseXmlRoot=Ve.EMPTY_FORM_SENTINEL=Ve.TEXT_SENTINEL=void 0;var Fq=Pi(),Zs=X(),Mq=Oi();Ve.TEXT_SENTINEL="#text";Ve.EMPTY_FORM_SENTINEL="#empty";var sc=new WeakSet;function $q(e,t){(0,Mq.installDomShim)();let r=e&&e.trim()!==""?e:t,i=new DOMParser().parseFromString(r,"text/xml").documentElement;if(!i)throw new Zs.InvalidArgumentError("XML source has no root element (empty or malformed input)");return Uq(i),qq(i),Wq(i,r),i}Ve.parseXmlRoot=$q;var Bq=new Set([1,3]);function Uq(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(!Bq.has(o.nodeType))throw new Zs.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 qq(e){var t,r;let n=(t=e.ownerDocument)!==null&&t!==void 0?t:e.parentNode;if(!n)return;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a!==e&&!(a.nodeType===3&&((r=a.nodeValue)!==null&&r!==void 0?r:"").trim()===""))throw new Zs.InvalidArgumentError(`Unsupported document-level XML node (type ${a.nodeType}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}}function Vq(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 Gq(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 tC(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 Wq(e,t){let r=Vq(t),n=Gq(e),i=Math.min(r.length,n.length);for(let o=0;o<i;o+=1){if(r[o])continue;let a=n[o];tC(a)||sc.add(a)}}function fm(e){let t=e.nodeType===3;return{getNodeName:()=>t?Ve.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:Ve.TEXT_SENTINEL,value:(r=e.nodeValue)!==null&&r!==void 0?r:""}];let n=e.attributes,i=[];for(let o=0;o<n.length;o+=1)i.push({key:n[o].name,value:n[o].value});return sc.has(e)&&!tC(e)&&i.push({key:Ve.EMPTY_FORM_SENTINEL,value:"1"}),i},getAllChildren:()=>{if(t)return[];let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];(o.nodeType===1||o.nodeType===3)&&r.push(fm(o))}return r}}}Ve.nodeLikeFromDom=fm;function zq(e){return{make:t=>t===Ve.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===Ve.EMPTY_FORM_SENTINEL?sc.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}Ve.domEngine=zq;function rC(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 ac(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw ac(r);t+=1;continue}if(r>=56320&&r<=57343)throw ac(r)}}function ac(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new Zs.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 jq(e){return rC(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\r/g,"&#xD;").replace(/\n/g,"&#xA;").replace(/\t/g,"&#x9;")}function Hq(e){return rC(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Kq(e){return nC(e,0)}Ve.serializeNode=Kq;var eC=512;function nC(e,t){var r;if(t>eC)throw new Zs.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${eC}`);if(e.nodeType===3)return Hq((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+'="'+jq(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 sc.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of a)i+=nC(l,t+1);return i+"</"+n.tagName+">"}function Jq(e){let t=fm(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,Fq.rawFromNode)(r)}))}}Ve.projectElementBag=Jq});var kr=b(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.rejectUnknownKeys=It.childObjects=It.optionalGuidId=It.optionalEnum=It.eachObject=It.issue=It.isJsonObject=void 0;function iC(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}It.isJsonObject=iC;function Ea(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}It.issue=Ea;function oC(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{iC(o)?i.push({node:o,index:a}):n.push(Ea(`${t}/${a}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}It.eachObject=oC;function Qq(e,t,r,n,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!r.includes(a))&&o.push(Ea(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}It.optionalEnum=Qq;var Yq=/^(?:\{[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 Xq(e,t,r,n,i){let o=e[t];typeof o=="string"&&o!==""&&!Yq.test(o)&&i.push(Ea(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${o}'`))}It.optionalGuidId=Xq;function Zq(e,t,r,n,i){let o=e[t],a=`${r}/${t}`;return o===void 0?[]:Array.isArray(o)?oC(o,a,n,i):(i.push(Ea(a,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}It.childObjects=Zq;function e3(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(Ea(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}It.rejectUnknownKeys=e3});var fc=b(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 t3=ya(),r3=ra(),pm=lt(),xr=kr();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 n3=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function er(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),n3.test(t)?t:""}B.normGuid=er;function ki(e,t){let r=pe(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=ki;function tl(e){return pe(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=tl;function pe(e){return Array.isArray(e)?e:[]}function bm(e,t){let r=pe(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function lC(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function uC(e){return Qr(e).map(t=>t.cell)}B.typedCells=uC;function Qr(e){let t=[];return pe(e?.tabs).forEach((r,n)=>{pe(Se(r)?r.columns:void 0).forEach((i,o)=>{pe(Se(i)?i.sections:void 0).forEach((a,s)=>{pe(Se(a)?a.rows:void 0).forEach((l,u)=>{pe(Se(l)?l.cells:void 0).forEach((c,d)=>{Se(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${o}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}B.typedCellSites=Qr;function Xn(e){return Se(e)?er(bm(e.bag,"uniqueid")):""}B.controlUniqueId=Xn;function i3(e){let t=new Set;for(let{cell:r}of Qr(e)){let n=vo(r.control)?Xn(r.control):"";n&&t.add(n)}return t}function o3(e){let t=new Map;for(let{cell:r}of Qr(e)){let n=Se(r.control)?Xn(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function a3(e){return e!==void 0&&e.genPage===void 0&&(Cm(e)!==B.CUSTOM_CONTROL_CLASS_ID||!dc(e))}function mm(e,t){if(Se(e)){t(e);for(let r of pe(e.c))mm(r,t)}}function go(e,t){var r;if(Se(e)){for(let n of pe(e.c))mm(n?.node,t);for(let n of pe((r=e.w)===null||r===void 0?void 0:r.c))mm(n?.node,t)}}function uc(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(er(ki(i,"uniqueid")))};return go(e?.bag,n),pe(e?.tabs).forEach(i=>{Se(i)&&(go(i.bag,n),pe(i.columns).forEach(o=>{Se(o)&&(go(o.bag,n),pe(o.sections).forEach(a=>{Se(a)&&(go(a.bag,n),pe(a.rows).forEach(s=>{Se(s)&&(go(s.bag,n),pe(s.cells).forEach(l=>{Se(l)&&(go(l.bag,n),Se(l.control)&&(r(Xn(l.control)),go(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=uc;function Sa(e){return pe(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=Sa;function yo(e,t){var r;let n=er(t);if(n)return pe((r=Sa(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&er(ki(i,"forControl"))===n)}B.descriptionFor=yo;function rl(e){return pe(e.c).filter(cC)}B.pageEntries=rl;function cC(e){return e?.n==="customControl"&&ki(e,"name")===B.GENPAGE_CONTROL_NAME}function hm(e,t){let r=pe(e.c).find(n=>n?.n==="parameters");return pe(r?.c).find(n=>n?.n===t)}B.entryParameter=hm;function gm(e){return ki(e,"static")==="true"}B.isStaticParameter=gm;function nl(e){let t=rl(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let o=hm(t[i],"RefId");if(!o||!gm(o))return{kind:"unsupported"};let a=er(tl(o));if(!a)return{kind:"unsupported"};let s=hm(t[i],"PageInput");if(s&&!gm(s))return{kind:"unsupported"};let l=s?tl(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=nl;function Se(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function wm(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return Se(t)&&Se(t.data)?t.data:void 0}B.inputDataFrom=wm;function Am(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=Am;function Cm(e){return lC(e.classId!==void 0?e.classId:bm(e.bag,"classid"))}B.effectiveClassId=Cm;function dc(e){return!e.fieldName}B.isUnbound=dc;function Em(e,t){if(Am(e)!=="Main"||!dc(t)||Cm(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=Xn(t),n=r?yo(e.bag,r):void 0;return n!==void 0&&nl(n).kind==="projectable"}B.isRecognizedEmbed=Em;function s3(e){for(let t of uC(e)){let r=t.control;if(!r||!Em(e,r))continue;let n=nl(yo(e.bag,Xn(r)));if(n.kind!=="projectable")continue;let i=wm(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=s3;var l3=new Set(["pageId","inputData"]);function el(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 u3(e){let t=[],r=u=>c=>t.push(`${u}: ${c}`),i=new t3.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new Error(`the formxml does not parse cleanly${t.length>0?` (${t[0]})`:""}`);let o=new Set,a=i.getElementsByTagName("control");for(let u=0;u<a.length;u+=1){let c=er(a[u].getAttribute("uniqueid"));c&&o.add(c)}let s=el(i).find(u=>u.nodeName==="controlDescriptions"),l=new Map;for(let u of s?el(s):[]){let c=er(u.getAttribute("forControl"));if(!(u.nodeName!=="controlDescription"||!c||!o.has(c)))for(let d of el(u)){if(d.nodeName!=="customControl"||d.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let f=el(d).find(h=>h.nodeName==="parameters"),p=f?el(f).find(h=>h.nodeName==="RefId"):void 0,m=p&&p.getAttribute("static")==="true"?er(p.textContent):"";m&&l.set(`${c}|${m}`,[c,m])}}return[...l.values()]}B.activeEmbedBindings=u3;function lc(e){return{n:`<${e}`,a:[],c:[]}}function ym(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[lc(t)]}}function vm(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);Se(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function c3(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:[ym("RefId",t),...r===void 0?[]:[ym("PageInput",vm(r))]]}]}))}}function cc(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>cc(r,t[n]));if(Se(e)&&Se(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&cc(e[n],t[n]))}return e===t}function d3(e,t,r){let n=pe(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&er(tl(i))!==t&&(i.c=[lc(t)]);let o=n.c.findIndex(u=>u?.n==="PageInput"),a=o>=0?n.c[o]:void 0,s=a?tl(a):void 0;if(cc(wm(s),r))return;if(r!==void 0){a?a.c=[lc(vm(r,s))]:n.c.push(ym("PageInput",vm(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(o,1):a.c=[lc(JSON.stringify(l))]}function Sm(e){let t=pe(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=Sm;function f3(e,t){var r;let n=e.bag,i=Sa(n);if(i&&t){let o=uc(t),a=uc(e),s=i3(t),l=o3(e),u=pe(i.node.c),c=[];for(let d of u){let f=d?.n==="controlDescription"&&rl(d).length>0?er(ki(d,"forControl")):"";if(!f||!o.has(f))c.push(d);else if(a.has(f))if(s.has(f)&&a3(l.get(f))&&cc(d,yo(t.bag,f))){let p=pe(d.c).filter(m=>!cC(m));p.length>0&&c.push({...d,c:p})}else c.push(d)}(c.length!==u.length||c.some((d,f)=>d!==u[f]))&&(i.node.c=c)}for(let{cell:o}of Qr(e)){let a=o.control;if(!vo(a)||!Se(a.genPage))continue;let s=er(a.genPage.pageId),l=a.genPage.inputData,u=Xn(a);if(!u){if(il(a)!==void 0)continue;u=Nm(a)}let c=yo(n,u);if(c){for(let p of rl(c))d3(p,s,l);continue}i||(i={i:Sm(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=bm(a.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),f=d.startsWith("{")?d:`{${u}}`;i.node.c.push(c3(f,s,l))}}B.reconcileEmbedDescriptions=f3;function p3(e,t){let r=Sa(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=Qr(e).some(({cell:a})=>vo(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=Sa(o.bag);s?s.node=a:(o.bag=Se(o.bag)?o.bag:{a:[],c:[]},o.bag.c=pe(o.bag.c),o.bag.c.push({i:Sm(e.bag),node:a}))}for(let{cell:a}of Qr(o))vo(a.control)&&(dC(a.control),fC(a));return o}B.commitEmbedState=p3;function m3(e){if(Qr(e).some(({cell:r})=>vo(r.control)))return!0;let t=Sa(e.bag);return pe(t?.node.c).some(r=>r?.n==="controlDescription"&&rl(r).length>0)}B.mayCommitEmbedState=m3;function dC(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=dC;function fC(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=fC;function vo(e){return Se(e)&&e.genPage!==void 0}B.hasGenPage=vo;function aC(e){return vo(e.control)&&(!e.control.id||!e.id||il(e.control)===void 0)}function il(e){let t=pe(Se(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=il;function h3(e){if(!Qr(e).some(({cell:r})=>aC(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of Qr(t)){if(!aC(r))continue;let n=r.control;n.id||(n.id=(0,pm.newId)()),r.id||(r.id=(0,pm.newId)()),il(n)===void 0&&Nm(n)}return t}B.mintEmbedIdentity=h3;function Nm(e){let t=(0,pm.newId)(),r=`{${t}}`;if(!Se(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=pe(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=pe(e.bag.c),t}B.setUniqueId=Nm;function sC(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function g3(e){let t=pe(e.c).filter(r=>r?.n==="customControl").map(r=>{var n,i;return(i=(n=ki(r,"name"))!==null&&n!==void 0?n:ki(r,"id"))!==null&&i!==void 0?i:"(unnamed)"});return[...new Set(t)].join(", ")||"(no custom control)"}function y3(e){let t=[],r;for(let{cell:n,pointer:i}of Qr(e)){let o=n.control;if(!Se(o))continue;let a=`${i}/control`;if(o.genPage===void 0){v3(e,o,a,t);continue}r=r??uc(e),b3(e,o,a,r,t)}return t}B.genPageEmbedIssues=y3;function v3(e,t,r,n){if(!Em(e,t))return;let i=nl(yo(e.bag,Xn(t)));n.push((0,xr.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 b3(e,t,r,n,i){var o;let a=`${r}/genPage`,s=t.genPage;if(!Se(s))i.push((0,xr.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${sC(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!er(s.pageId))&&i.push((0,xr.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&&!Se(s.inputData)&&i.push((0,xr.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${sC(s.inputData)}`));for(let p of Object.keys(s))l3.has(p)||i.push((0,xr.issue)(r3.JsonPointer.append(a,p),"genpage-embed-unknown-key",`'${p}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}dc(t)||i.push((0,xr.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&&lC(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,xr.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=Am(e);l!=="Main"&&i.push((0,xr.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=il(t);u!==void 0&&!er(u)&&i.push((0,xr.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=Xn(t);if(!c)return;let d=yo(e.bag,c),f=d?nl(d):void 0;d&&f?.kind==="none"?i.push((0,xr.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${g3(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,xr.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,xr.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 _m=b(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});xi.findMissingGenPages=xi.GENPAGE_LOOKUP_CHUNK=void 0;var w3=Mt(),Dm=ae();xi.GENPAGE_LOOKUP_CHUNK=50;async function A3(e,t,r){let n=[...new Set(t.map(o=>(0,Dm.normalizeGuid)(o,"uxagentprojectid")))],i=new Set;for(let o=0;o<n.length;o+=xi.GENPAGE_LOOKUP_CHUNK){let a=n.slice(o,o+xi.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Dm.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,w3.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,Dm.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(o=>!i.has(o))}xi.findMissingGenPages=A3});var ol=b(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.assertSystemFormKind=ut.readSystemFormType=ut.decodeCode=ut.assertSystemFormRecordKind=ut.describeSystemFormType=ut.systemFormKindOf=ut.SYSTEMFORM_KIND_MISMATCH_CODE=void 0;var mC=X(),C3=we(),pC=ae();ut.SYSTEMFORM_KIND_MISMATCH_CODE="SYSTEMFORM_KIND_MISMATCH";var E3={0:"dashboard",10:"dashboard",2:"form",6:"form",7:"form",11:"form"},S3={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 pc(e){return Number.isInteger(e)?E3[e]:void 0}ut.systemFormKindOf=pc;function hC(e){var t;return Number.isFinite(e)?`a ${(t=S3[e])!==null&&t!==void 0?t:"systemform"} (type ${e})`:"a systemform whose type could not be read"}ut.describeSystemFormType=hC;function gC(e,t,r,n){let i=hC(r),o=pc(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 N3(e,t,r,n){let i=Im(e?.type);if(pc(i)!==r)throw new mC.SdkError(ut.SYSTEMFORM_KIND_MISMATCH_CODE,gC(t,r,i,n));return i}ut.assertSystemFormRecordKind=N3;function Im(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}ut.decodeCode=Im;async function D3(e,t){return await yC(e,t,!1)}ut.readSystemFormType=D3;async function _3(e,t){return yC(e,t,!0)}async function yC(e,t,r){var n;let o=`/systemforms(${(0,pC.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,pC.odataQuery)([["$select","type"]]),a=await e.get(o);if(!(r&&a.status===404))return(0,C3.ensureSuccess)(a,e.apiUrl(o)),Im((n=a.body)===null||n===void 0?void 0:n.type)}async function I3(e,t,r){let n=await _3(e,t);if(!(n===void 0||pc(n)===r))throw new mC.SdkError(ut.SYSTEMFORM_KIND_MISMATCH_CODE,gC(t,r,n,"delete"))}ut.assertSystemFormKind=I3});var Pm=b(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});br.patchSystemForm=br.assertSystemFormContentUnchanged=br.readSystemFormRowEtag=br.unpublishedSystemFormPath=br.FORM_TYPE_IMMUTABLE_CODE=void 0;var Lr=we(),T3=ae(),mc=X(),Li=ol();br.FORM_TYPE_IMMUTABLE_CODE="FORM_TYPE_IMMUTABLE";function Tm(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,T3.odataQuery)([["$select",t]])}br.unpublishedSystemFormPath=Tm;function vC(e,t){return(0,Lr.readRowEtag)(e,"systemforms","formid",t)}br.readSystemFormRowEtag=vC;async function bC(e,t,r,n,i){(0,Lr.requireEtag)(i,r,t);let o=(0,Lr.ensureSuccess)(await e.get(n),e.apiUrl(n)),a=(0,Li.assertSystemFormRecordKind)(o.body,t,r,"write"),s=(0,Lr.readEtag)(o);if(s===null)throw new mc.SdkError(Lr.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 mc.SdkError(Lr.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}br.assertSystemFormContentUnchanged=bC;async function P3(e,t,r,n,i,o){(0,Lr.requireEtag)(i,r,t);let a=await vC(e,t);if(a===null)throw new mc.SdkError(Lr.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 bC(e,t,r,Tm(t,"formid,type"),i);if(n.type!==void 0&&(0,Li.decodeCode)(n.type)!==s)throw new mc.SdkError(br.FORM_TYPE_IMMUTABLE_CODE,`Refusing to push ${r} '${t}': it would change it from ${(0,Li.describeSystemFormType)(s)} to ${(0,Li.describeSystemFormType)((0,Li.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,Lr.echoWrite)("formid",{"If-Match":a}),u=`/systemforms(${t})${l.query}`;return(0,Lr.ensureSuccess)(await e.patch(u,n,l.options),e.apiUrl(u)),O3(e,t,r,o)}br.patchSystemForm=P3;async function O3(e,t,r,n){let i;try{let o=Tm(t,n.select),a=(0,Lr.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,l=(0,Lr.readEtag)(a),u=typeof s?.formid=="string"&&s.formid.replace(/[{}]/g,"").toLowerCase()===t,c=typeof s?.formxml=="string"&&s.formxml.trim()!=="",d=n.required.filter(m=>s?.[m]===void 0||s?.[m]===null),f=(0,Li.decodeCode)(s?.type),p=(0,Li.systemFormKindOf)(f)===r;if(l&&u&&c&&d.length===0&&p)return{id:t,etag:l,readBack:s};i=l?!u||!c?`the read did not return this ${r}'s document`:d.length>0?`the read did not return its ${d.join(", ")}`:`the read returned ${(0,Li.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 Lm=b(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.getFormSecurityRoles=wt.setFormSecurityRoles=wt.formApi=wt.readPrimaryCreateRefusal=wt.FORM_GENPAGE_TARGET_UNVERIFIABLE=wt.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var R3=Mt(),ct=we(),Fr=ae(),bo=X(),Om=Ri(),AC=fc(),k3=_m(),Rm=Pm(),al=ol();wt.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";wt.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var CC="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",x3={select:CC,required:["name","type","objecttypecode"]},L3="formid,name,type,objecttypecode",F3=2,M3={Main:F3,QuickView:6,QuickCreate:7,Card:11},EC=new WeakMap;function $3(e){return typeof e=="object"&&e!==null?EC.get(e):void 0}wt.readPrimaryCreateRefusal=$3;wt.formApi={async get(e,t){let r=(0,Fr.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Fr.odataQuery)([["$select",CC]]),i=(0,ct.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,al.assertSystemFormRecordKind)(i.body,r,"form","fetch"),{raw:i.body,etag:(0,ct.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=>M3[u]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,Fr.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,Fr.odataQuery)([["$select",L3],["$filter",a.join(" and ")]])}`;return(await(0,R3.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=wC(t);n!==void 0&&await SC(e,xm(n,"payload"),[]);let i=(0,ct.echoWrite)("formid"),o=`/systemforms${i.query}`,a=(0,ct.withClientMintedId)(t,"formid",r),s=Object.freeze({...a}),l=await(0,ct.resendDeadlockVictim)(()=>e.post(o,{...s},i.options));try{(0,ct.ensureSuccess)(l,e.apiUrl(o))}catch(u){throw typeof u=="object"&&u!==null&&EC.set(u,{status:l.status,sent:s,desiredId:r}),u}return{id:(0,ct.resolveCreatedId)(l,"formid","form",r),etag:(0,ct.readEtag)(l)}},async update(e,t,r,n){let i=(0,Fr.normalizeGuid)(t,"id"),o=wC(r);return o!==void 0&&await U3(e,i,o,n),(0,Rm.patchSystemForm)(e,i,"form",r,n,x3)},readContentThenToken(e,t){return wt.formApi.get(e,t)},async delete(e,t){let r=(0,Fr.normalizeGuid)(t,"id");return await(0,al.assertSystemFormKind)(e,r,"form"),(0,ct.deleteRecord)(e,"systemforms",r)}};var km="DisplayConditions";async function B3(e,t,r){var n,i,o,a;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new bo.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,Fr.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Fr.odataQuery)([["$select","formid,formxml,type"]]),u=(0,ct.ensureSuccess)(await e.get(l),e.apiUrl(l));(0,al.assertSystemFormRecordKind)(u.body,s,"form","set the security roles of");let c=(0,ct.readEtag)(u),d=u.body,f=d?.formxml;if(!f)throw new bo.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let p=(0,Om.parseXmlRoot)(f,"<form/>"),m=p.ownerDocument;if(!m)throw new bo.InvalidArgumentError(`form '${s}' produced no owner document`);let h=NC(p,km),g=h?.hasAttribute("Order")&&(n=h.getAttribute("Order"))!==null&&n!==void 0?n:void 0,v=h?.getAttribute("FallbackForm")||void 0;h&&p.removeChild(h);let w=!!r.everyone||((o=(i=r.roleIds)===null||i===void 0?void 0:i.length)!==null&&o!==void 0?o:0)>0;if(!w&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!h)throw new bo.InvalidArgumentError("setFormSecurityRoles: `order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to. Pass the roles as well.");r.order!==void 0&&h.setAttribute("Order",String(r.order)),r.fallbackForm!==void 0&&h.setAttribute("FallbackForm",String(r.fallbackForm)),p.appendChild(h)}else if(w){let T=m.createElement(km),I=r.order!==void 0?String(r.order):g;I!==void 0&&T.setAttribute("Order",I);let P=r.fallbackForm!==void 0?String(r.fallbackForm):v??"false";if(T.setAttribute("FallbackForm",P),r.everyone)T.appendChild(m.createElement("Everyone"));else for(let F of(a=r.roleIds)!==null&&a!==void 0?a:[]){let z=m.createElement("Role");z.setAttribute("Id",`{${(0,Fr.normalizeGuid)(F,"roleId")}}`),T.appendChild(z)}p.appendChild(T)}let E=(0,Om.serializeNode)(p);await(0,Rm.assertSystemFormContentUnchanged)(e,s,"form",l,c);let k=await(0,Rm.readSystemFormRowEtag)(e,s),R=`/systemforms(${s})`;(0,ct.ensureSuccess)(await e.patch(R,{formxml:E},{headers:{"Content-Type":"application/json","If-Match":(0,ct.requireEtag)(k,"form",s)}}),e.apiUrl(R))}wt.setFormSecurityRoles=B3;function wC(e){let t=e?.formxml;return typeof t=="string"&&t.includes(AC.GENPAGE_CONTROL_NAME)?t:void 0}function xm(e,t){try{return(0,AC.activeEmbedBindings)(e)}catch(r){throw new bo.SdkError(wt.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 SC(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,k3.findMissingGenPages)(e,i,"form generative-page preflight");if(o.length>0)throw new bo.SdkError(wt.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 U3(e,t,r,n){var i;(0,ct.requireEtag)(n,"form",t);let o=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Fr.odataQuery)([["$select","formid,formxml,type"]]),a=(0,ct.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,al.assertSystemFormRecordKind)(a.body,t,"form","write");let s=(0,ct.readEtag)(a);if(s===null||s!==n)throw new bo.SdkError(ct.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!==""?xm(l,"server"):[];await SC(e,xm(r,"payload"),u)}function NC(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 q3(e,t){var r,n;let i=(0,Fr.normalizeGuid)(t,"formId"),o=`/systemforms(${i})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Fr.odataQuery)([["$select","formid,formxml,type"]]),a=(0,ct.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,al.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,Om.parseXmlRoot)(s,"<form/>"),u=NC(l,km);if(!u)return;let c=[],d=!1,f=u.childNodes;for(let m=0;m<f.length;m+=1){let h=f[m];if(h.nodeType!==1)continue;let g=h;if(g.tagName==="Everyone")d=!0;else if(g.tagName==="Role"){let v=(n=g.getAttribute("Id"))!==null&&n!==void 0?n:"";v&&c.push(v.replace(/[{}]/g,"").toLowerCase())}}let p=u.getAttribute("Order");return{...d?{everyone:!0}:{},...c.length>0?{roleIds:c}:{},fallbackForm:u.getAttribute("FallbackForm")==="true",...p!==null&&p!==""?{order:Number(p)}:{}}}wt.getFormSecurityRoles=q3});var Fm=b(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.deleteSolution=me.importSolution=me.exportSolution=me.removeSolutionComponent=me.addSolutionComponent=me.setSolutionVersion=me.createSolution=me.createPublisher=me.getSolution=me.fetchSolutionComponents=me.resolveGenPageComponentType=me.SolutionComponentType=void 0;var V3=Mt(),wr=we(),tr=ae(),Zn=X();me.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80};var G3=[me.SolutionComponentType.SavedQuery,me.SolutionComponentType.Workflow,me.SolutionComponentType.SavedQueryVisualization,me.SolutionComponentType.SystemForm,me.SolutionComponentType.AppModule],DC="uxagentproject",_C=new WeakMap;async function PC(e){var t;let r=_C.get(e);if(r!==void 0)return r;let n=`/EntityDefinitions(LogicalName='${DC}')${(0,tr.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status===404)return;(0,wr.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 Zn.SdkError("GENPAGE_COMPONENT_TYPE_UNRESOLVED",`A generative page's solution component type \u2014 the ObjectTypeCode of '${DC}' \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 _C.set(e,o),o}me.resolveGenPageComponentType=PC;var IC=1,TC=0;async function W3(e,t){let r=(0,tr.normalizeGuid)(t,"solutionId"),n=await PC(e),o=[IC,...G3,...n===void 0?[]:[n]].map(c=>`componenttype eq ${c}`).join(" or "),a=`/solutioncomponents${(0,tr.odataQuery)([["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${r} and (${o})`]])}`,s=await(0,V3.collectPages)(e,a,"fetchSolutionComponents"),l=[];for(let c of s){if(typeof c.objectid!="string")continue;let d=Number(c.componenttype);if(d===IC){let f=c.rootcomponentbehavior;(f===TC||f===String(TC))&&l.push({objectId:c.objectid,componentType:d,includesAllSubcomponents:!0});continue}l.push({objectId:c.objectid,componentType:d,...n!==void 0&&d===n?{genPage:!0}:{}})}let u=c=>c.objectId.toLowerCase().replace(/^\{|\}$/g,"");return l.sort((c,d)=>c.componentType-d.componentType||(u(c)<u(d)?-1:u(c)>u(d)?1:0))}me.fetchSolutionComponents=W3;function z3(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 j3(e,t){var r,n,i,o,a,s,l,u,c,d;let f=String(t??"").trim();if(!f)throw new Zn.InvalidArgumentError("getSolution: a solution unique name or id is required.");let p=z3(f)?`solutionid eq ${(0,tr.normalizeGuid)(f,"solutionId")}`:`uniquename eq '${(0,tr.odataLiteral)(f)}'`,m=`/solutions${(0,tr.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",p]])}`,v=((n=(r=(0,wr.ensureSuccess)(await e.get(m),e.apiUrl(m)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!v?.solutionid)throw new Zn.InvalidArgumentError(`No solution found for '${t}'.`);let w=v.publisherid;if(!w?.publisherid)throw new Zn.InvalidArgumentError(`Solution '${(i=v.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 Zn.InvalidArgumentError(`Solution '${(o=v.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,tr.normalizeGuid)(v.solutionid,"solutionId"),uniqueName:(a=v.uniquename)!==null&&a!==void 0?a:"",friendlyName:(s=v.friendlyname)!==null&&s!==void 0?s:"",version:(l=v.version)!==null&&l!==void 0?l:"",isManaged:!!v.ismanaged,publisherId:(0,tr.normalizeGuid)(w.publisherid,"publisherId"),publisherUniqueName:(u=w.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=w.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=w.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}me.getSolution=j3;async function H3(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,wr.ensureSuccess)(await(0,wr.resendDeadlockVictim)(()=>e.post("/publishers",{...n})),e.apiUrl("/publishers")),o=(0,wr.readCreatedId)(i,"publisherid");if(!o)throw new Zn.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}me.createPublisher=H3;async function K3(e,t){var r;let n=(0,tr.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,wr.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,wr.readCreatedId)(o,"solutionid");if(!a)throw new Zn.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}me.createSolution=K3;async function J3(e,t,r){let i=`/solutions(${(0,tr.normalizeGuid)(t,"solutionId")})`;(0,wr.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}me.setSolutionVersion=J3;async function Q3(e,t){var r;let i={ComponentId:(0,tr.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,wr.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}me.addSolutionComponent=Q3;async function Y3(e,t,r,n){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,tr.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,wr.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}me.removeSolutionComponent=Y3;async function X3(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},a=(n=(0,wr.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!a)throw new Zn.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}me.exportSolution=X3;async function Z3(e,t){let r=[["overwriteUnmanagedCustomizations","overwrote unmanaged customizations made over the solution's components"],["publishWorkflows","activated the solution's workflows"]];for(let[i,o]of r)if(typeof t?.[i]!="boolean")throw new Zn.InvalidArgumentError(`importSolution: '${i}' is required and must be true or false (it was ${String(t?.[i])}). It used to default to true, which ${o} unless the caller said otherwise. Nothing was imported.`);let n={OverwriteUnmanagedCustomizations:t.overwriteUnmanagedCustomizations,PublishWorkflows:t.publishWorkflows,CustomizationFile:t.base64};t.importJobId&&(n.ImportJobId=(0,tr.normalizeGuid)(t.importJobId,"importJobId")),(0,wr.ensureSuccess)(await e.post("/ImportSolution",n),e.apiUrl("/ImportSolution"))}me.importSolution=Z3;async function e4(e,t){let n=`/solutions(${(0,tr.normalizeGuid)(t,"solutionId")})`;(0,wr.ensureSuccess)(await e.delete(n),e.apiUrl(n))}me.deleteSolution=e4});var FC=b(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.recoverFormCreate=Ye.solutionMembershipProblem=Ye.formWriteMismatches=Ye.validateExistingForm=Ye.formExistsAtId=Ye.isFormRecordAt=Ye.MAIN_FORM_TYPE=void 0;var Na=ae(),OC=Mt(),RC=Fm();Ye.MAIN_FORM_TYPE=2;function hc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gc(e){return e instanceof Error?e.message:String(e)}function Mm(e,t){if(typeof e!="string"||typeof t!="string")return!1;try{return(0,Na.normalizeGuid)(e,"a GUID")===(0,Na.normalizeGuid)(t,"a GUID")}catch{return!1}}function $m(e,t){return hc(e)&&Mm(e.formid,t)}Ye.isFormRecordAt=$m;async function t4(e,t){try{return $m((await e()).raw,t)}catch{return!1}}Ye.formExistsAtId=t4;function kC(e,t){let r=e.raw;if(!hc(r))return{problem:"it is not a record"};if(!$m(r,t))return{problem:"its formid is not the id this create sent"};if(r.type!==Ye.MAIN_FORM_TYPE)return{problem:`its type is not ${Ye.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}}Ye.validateExistingForm=kC;function xC(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}Ye.formWriteMismatches=xC;async function LC(e,t){let r=e.solutionName;if(r)try{let n=await(0,OC.collectPages)(e,`/solutions${(0,Na.odataQuery)([["$select","solutionid,uniquename"],["$filter",`uniquename eq '${(0,Na.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 hc(i)&&typeof i.uniquename=="string"&&typeof i.solutionid=="string"&&i.uniquename.toLowerCase()===r.toLowerCase()&&(o=(0,Na.normalizeGuid)(i.solutionid,"solutionid")),o===void 0?`the configured solution '${r}' did not resolve to a valid solution of that name`:(await(0,OC.collectPages)(e,`/solutioncomponents${(0,Na.odataQuery)([["$select","objectid,componenttype,_solutionid_value"],["$filter",`_solutionid_value eq ${o} and componenttype eq ${RC.SolutionComponentType.SystemForm} and objectid eq ${t}`]])}`,"createRecovery solution membership")).some(l=>hc(l)&&l.componenttype===RC.SolutionComponentType.SystemForm&&Mm(l.objectid,t)&&Mm(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 (${gc(n)})`}}Ye.solutionMembershipProblem=LC;async function r4(e){try{return await n4(e)}catch(t){return{refused:`the recovery could not be completed (${gc(t)})`}}}Ye.recoverFormCreate=r4;async function n4(e){let{client:t,read:r,sent:n,authoredFormType:i,project:o}=e;if(i!=="Main"||n.type!==Ye.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 (${gc(f)})`}}let l=kC(s,a);if("problem"in l)return{refused:`the existing row cannot be trusted: ${l.problem}`};let u=xC(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 (${gc(f)})`}}let d=await LC(t,a);return d!==void 0?{refused:d}:{adopted:{artifact:c,etag:l.etag}}}});var bc=b(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.disassociateRecords=Ue.associateRecords=Ue.createRecordsBulk=Ue.upsertRecord=Ue.queryAllRecords=Ue.queryRecords=Ue.getRecord=Ue.deleteRecord=Ue.updateRecord=Ue.createRecord=void 0;var i4=Mt(),Yr=we(),Tt=ae(),yc=X(),wn=rc();function vc(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 o4(e,t,r){let i=`/${await(0,wn.resolveEntitySetName)(e,t)}`,o=(0,Yr.ensureSuccess)(await e.post(i,vc(r)),e.apiUrl(i)),a=(0,Yr.readCreatedId)(o,`${t}id`);if(!a)throw new yc.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}Ue.createRecord=o4;async function a4(e,t,r,n){let i=(0,Tt.normalizeGuid)(r,"id"),a=`/${await(0,wn.resolveEntitySetName)(e,t)}(${i})`;(0,Yr.ensureSuccess)(await e.patch(a,vc(n)),e.apiUrl(a))}Ue.updateRecord=a4;async function s4(e,t,r){let n=(0,Tt.normalizeGuid)(r,"id"),o=`/${await(0,wn.resolveEntitySetName)(e,t)}(${n})`;(0,Yr.ensureSuccess)(await e.delete(o),e.apiUrl(o))}Ue.deleteRecord=s4;async function l4(e,t,r,n){var i;let o=(0,Tt.normalizeGuid)(r,"id"),a=await(0,wn.resolveEntitySetName)(e,t),s=(0,Tt.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),l=`/${a}(${o})${s}`;return(i=(0,Yr.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)!==null&&i!==void 0?i:{}}Ue.getRecord=l4;function u4(e){return e?.fetchXml?(0,Tt.odataQuery)([["fetchXml",e.fetchXml]]):(0,Tt.odataQuery)([["$select",e?.select&&e.select.length>0?e.select.join(","):void 0],["$filter",e?.filter],["$orderby",e?.orderBy],["$expand",e?.expand],["$top",e?.top]])}async function MC(e,t,r){var n,i;if(r?.paginate){if(r.top!==void 0)throw new yc.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 yc.InvalidArgumentError("queryRecords: `paginate` is not supported with `fetchXml` \u2014 FetchXML paging uses a paging cookie (page / fetchxmlpagingcookie), not @odata.nextLink. Page the FetchXML manually, or use an OData query.")}let a=`/${await(0,wn.resolveEntitySetName)(e,t)}${u4(r)}`;return r?.paginate?(0,i4.collectPages)(e,a,"queryRecords"):(i=(n=(0,Yr.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]}Ue.queryRecords=MC;async function c4(e,t,r){return MC(e,t,{...r,paginate:!0})}Ue.queryAllRecords=c4;function d4(e){if("id"in e)return`(${(0,Tt.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,Tt.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,Tt.assertODataName)(e.key,"alternate key name")}=${t})`}async function f4(e,t,r,n){let i=d4(r),a=`/${await(0,wn.resolveEntitySetName)(e,t)}${i}`,s=(0,Yr.ensureSuccess)(await e.patch(a,vc(n)),e.apiUrl(a)),l=s.status===201,u=(0,Yr.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,Tt.normalizeGuid)(r.id,"id"):""),created:l}}Ue.upsertRecord=f4;async function p4(e,t,r){var n,i;if(r.length===0)return[];let o=await(0,wn.resolveEntitySetName)(e,t),a=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...vc(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Yr.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 yc.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Ue.createRecordsBulk=p4;async function m4(e,t,r,n){let i=(0,Tt.normalizeGuid)(r,"id"),o=(0,Tt.normalizeGuid)(n.targetId,"targetId"),a=await(0,wn.resolveEntitySetName)(e,t),s=await(0,wn.resolveEntitySetName)(e,n.targetEntity),l=(0,Tt.assertODataName)(n.relationshipName,"relationshipName"),u=`/${a}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,Yr.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Ue.associateRecords=m4;async function h4(e,t,r,n,i){let o=(0,Tt.normalizeGuid)(r,"id"),a=(0,Tt.normalizeGuid)(i,"targetId"),s=await(0,wn.resolveEntitySetName)(e,t),l=(0,Tt.assertODataName)(n,"relationshipName"),u=`/${s}(${o})/${l}(${a})/$ref`;(0,Yr.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Ue.disassociateRecords=h4});var Ac=b(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.base64ToUtf8=An.base64ToBytes=An.bytesToBase64=An.utf8ToBase64=void 0;var Bm=32768,rr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function wc(){return globalThis}function g4(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 y4(e){let t="";for(let r=0;r<e.length;r+=Bm)t+=String.fromCharCode(...e.subarray(r,r+Bm));return t}function v4(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+="/":rr.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function b4(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+=rr[i>>18&63]+rr[i>>12&63]+rr[i>>6&63]+rr[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${rr[i>>18&63]}${rr[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,o=rr[i>>18&63],a=rr[i>>12&63],s=rr[i>>6&63];t+=`${o}${a}${s}=`}return t}function w4(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=rr.indexOf(e[o])<<18|rr.indexOf(e[o+1])<<12|(e[o+2]==="="?0:rr.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:rr.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 A4(e){let t=wc();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return $C(r?new r().encode(e):g4(e))}An.utf8ToBase64=A4;function $C(e){let t=wc();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(y4(e)):b4(e)}An.bytesToBase64=$C;function BC(e){let t=wc();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=v4(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return w4(r)}An.base64ToBytes=BC;function C4(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>=Bm&&n()},o=0;for(;o<e.length;){let a=e[o],s=0,l=0,u=128,c=191;if(a<128){i(a),o+=1;continue}else if(a>=194&&a<=223)s=1,l=a&31;else if(a>=224&&a<=239)s=2,l=a&15,u=a===224?160:128,c=a===237?159:191;else if(a>=240&&a<=244)s=3,l=a&7,u=a===240?144:128,c=a===244?143:191;else{i(65533),o+=1;continue}let d=o+1,f=!0;for(let p=0;p<s;p+=1,d+=1){let m=d<e.length?e[d]:-1;if(m<u||m>c){f=!1;break}u=128,c=191,l=l<<6|m&63}f?(i(l),o=d):(i(65533),o=d)}return n(),r}function E4(e){let t=wc();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):C4(BC(e))}An.base64ToUtf8=E4});var GC=b(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.deleteWebResource=Cn.getWebResource=Cn.updateWebResource=Cn.createWebResource=void 0;var S4=Tr(),sl=we(),Cc=ae(),N4=Ac(),UC=X(),D4={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function qC(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,N4.utf8ToBase64)(e.content)}async function VC(e,t){return(0,S4.publishWebResourceById)(e,t)}async function _4(e,t){var r;let n=qC(t);if(n===void 0)throw new UC.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:D4[t.type],content:n};t.description&&(i.description=t.description);let o=(0,sl.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,sl.readCreatedId)(o,"webresourceid");if(!a)throw new UC.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await VC(e,a),{id:a,name:t.name}}Cn.createWebResource=_4;async function I4(e,t,r){let n=(0,Cc.normalizeGuid)(t,"id"),i={},o=qC(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,sl.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),r.publish!==!1&&await VC(e,n)}Cn.updateWebResource=I4;async function T4(e,t){var r;let i=`/webresourceset(${(0,Cc.normalizeGuid)(t,"id")})${(0,Cc.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,sl.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}Cn.getWebResource=T4;async function P4(e,t){let n=`/webresourceset(${(0,Cc.normalizeGuid)(t,"id")})`;(0,sl.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Cn.deleteWebResource=P4});var Ec=b(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.applyAppSettings=dt.setAppSetting=dt.readAppSettings=dt.resolveSettingDefinitions=dt.APP_SETTING_UNSET=dt.APP_SETTING_OFF=dt.APP_SETTING_ON=dt.HEADER_AND_NAVIGATION_REFRESH=void 0;var Da=we(),ei=ae();dt.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";dt.APP_SETTING_ON="2";dt.APP_SETTING_OFF="1";dt.APP_SETTING_UNSET="0";function jC(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,ei.odataQuery)([["$select",e],["$filter",t]])}async function HC(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,ei.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,ei.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",a]])}`,u=((n=(r=(0,Da.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[]).filter(Boolean);for(let c of u)c.uniquename&&o.set(c.uniquename,c);return o}dt.resolveSettingDefinitions=HC;async function O4(e,t){var r,n,i,o;let a=(0,ei.normalizeGuid)(t,"App id"),s=jC("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${a}`),u=((n=(r=(0,Da.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,ei.normalizeGuid)(h,"Setting definition id")}`).join(" or "),p=`/settingdefinitions${(0,ei.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",f]])}`,m=(0,Da.ensureSuccess)(await e.get(p),e.apiUrl(p));for(let h of((o=(i=m.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[]).filter(Boolean))h.settingdefinitionid&&d.set(h.settingdefinitionid.toLowerCase(),h)}return u.map(f=>{var p,m,h,g,v;let w=d.get(((p=f._settingdefinitionid_value)!==null&&p!==void 0?p:"").toLowerCase());return{id:(m=f.appsettingid)!==null&&m!==void 0?m:"",name:(g=(h=w?.uniquename)!==null&&h!==void 0?h:f._settingdefinitionid_value)!==null&&g!==void 0?g:"",value:(v=f.value)!==null&&v!==void 0?v:"",...w?.displayname?{displayName:w.displayname}:{}}})}dt.readAppSettings=O4;async function WC(e,t,r){var n,i,o;let a=jC("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,Da.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 KC(e,t,r,n){let i=(0,ei.normalizeGuid)(t,"App id"),a=(await HC(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,ei.normalizeGuid)(s,"Setting definition id"),u=await WC(e,i,l);if(u)return zC(e,u,n);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${l})`,value:n},f,p;try{if(f=await e.post(c,d),f.status>=200&&f.status<300)return"created"}catch(h){p=h}let m;try{m=await WC(e,i,l)}catch{m=void 0}if(m)return zC(e,m,n);throw f&&(0,Da.ensureSuccess)(f,e.apiUrl(c)),p}dt.setAppSetting=KC;async function zC(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,ei.normalizeGuid)(t.id,"App setting id")})`;return(0,Da.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function R4(e,t,r){var n;let i=[];for(let[o,a]of Object.entries(r??{}))try{await KC(e,t,o,a)}catch(s){i.push(`App setting '${o}' was not applied: ${(n=s?.message)!==null&&n!==void 0?n:String(s)} The app was created; set it later with setAppSetting().`)}return i}dt.applyAppSettings=R4});var Nc=b(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});Sc.HEADER_NAV_BOOLEAN_RULE=void 0;Sc.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var Gm=b(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.compileGenPage=De.legacyEnumsNeeded=De.createGenPageTypeScriptLoader=De.acceptGenPageTypeScript=De.isLoadableGenPageOutput=De.runtimeTypesImportSpans=De.GENPAGE_RUNTIME_TYPES_END=De.GENPAGE_RUNTIME_TYPES_BEGIN=De.GENPAGE_TYPESCRIPT_VERSION=void 0;var _a=X();De.GENPAGE_TYPESCRIPT_VERSION="5.8.3";De.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";De.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var Xr="./RuntimeTypes",k4="'\"`",JC=/\s/;function x4(e){return e===10||e===13||e===8232||e===8233}function L4(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 ZC(e){let t=[],r=Xr.length;for(let l=e.indexOf(Xr);l!==-1;l=e.indexOf(Xr,l+1)){let u=l-1;u>=0&&k4.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&&JC.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&&JC.test(e[d]);)d+=1;n.push({start:l,end:d}),u=d}}l=e.indexOf("import",u)}return n}De.runtimeTypesImportSpans=ZC;var F4=/\b(?:import\s*['"]|export\s)/;function M4(e){let t=L4(/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&&!x4(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 $4(e){return e!==void 0&&e!==""&&(F4.test(e)||M4(e))}De.isLoadableGenPageOutput=$4;var QC=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function eE(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?QC.filter(s=>typeof n?.[s]!="function"):[...QC];if(!n||i.length>0)throw new _a.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@${De.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof n.version=="string"?n.version:"",a=De.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new _a.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 (${De.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${De.GENPAGE_TYPESCRIPT_VERSION}.`);return n}De.acceptGenPageTypeScript=eE;function B4(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new _a.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@${De.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(eE).catch(r=>{throw t=void 0,r instanceof _a.SdkError?r:new _a.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}}De.createGenPageTypeScriptLoader=B4;var tE=e=>`${e.kind}:${e.pos}:${e.end}`;function U4(e,t){return()=>r=>{let n=i=>{let o=e.getParseTreeNode(i);o&&t.add(tE(o)),e.forEachChild(i,n)};return n(r),r}}function Vm(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}var q4=2301;function YC(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:Vm(e),reportDiagnostics:!0,...r?{transformers:{after:[U4(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 XC=e=>e.startsWith(".")||e.startsWith("/"),Um={line:1,column:1};function qm(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):Um},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 Um}}}function V4(e,t,r,n){var i,o;let a=[],s=qm(e,r),l=(m,h,g)=>{a.push({...m,rule:h,code:0,message:g})},u=(m,h)=>{var g;return(e.canHaveModifiers(m)?(g=e.getModifiers(m))!==null&&g!==void 0?g:[]:[]).some(v=>v.kind===h)},c=(m,h)=>l(m,"genpage-relative-import",`'${h}' cannot resolve at runtime: the page is loaded as a single module from a blob URL, so the only relative import it may have is './RuntimeTypes'`),d="genpage-runtime-types-import-form",f=!1,p=new Set;for(let m of t.statements){if(e.isExportAssignment(m)){f=f||!m.isExportEquals;continue}if(e.isFunctionDeclaration(m)||e.isClassDeclaration(m)){u(m,e.SyntaxKind.ExportKeyword)&&u(m,e.SyntaxKind.DefaultKeyword)&&(f=!0),m.name&&p.add(m.name.text);continue}if(e.isExportDeclaration(m)){let w=m.exportClause;w&&e.isNamedExports(w)&&w.elements.some(E=>E.name.text==="default")&&(f=!0);let C=m.moduleSpecifier&&e.isStringLiteral(m.moduleSpecifier)?m.moduleSpecifier.text:void 0;C===Xr?l(s.statement(C,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):C!==void 0&&XC(C)&&c(s.statement(C,"export"),C);continue}if(!e.isImportDeclaration(m)||!e.isStringLiteral(m.moduleSpecifier))continue;let h=m.moduleSpecifier.text,g=m.importClause;if(h!==Xr){XC(h)&&c(s.statement(h,"import"),h),g?.name&&p.add(g.name.text);let w=g?.namedBindings;w&&e.isNamespaceImport(w)?p.add(w.name.text):w&&e.isNamedImports(w)&&w.elements.forEach(C=>p.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 v=g.namedBindings;if(v&&e.isNamespaceImport(v))l(s.binding(v.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(v&&e.isNamedImports(v))for(let w of v.elements){let C=w.name.text,E=(o=(i=w.propertyName)===null||i===void 0?void 0:i.text)!==null&&o!==void 0?o:C,k=s.element(h,C);E!==C?l(k,d,`'${E} as ${C}' would be undefined at runtime: the enum is inlined as '${E}', so import it under its own name`):n?.text?n.enums.has(C)||l(k,"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(k,"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(Um,"genpage-no-default-export","the page has no default export \u2014 the runtime renders the module's default export as the page component"),n?.text)for(let m of p)n.enums.has(m)&&l(s.binding(m),"genpage-runtime-types-collision",`'${m}' is declared at the page's module scope and is also one of its inlined choice enums, so the compiled page would declare it twice and fail to load. Rename the page's binding, or import the enum from './RuntimeTypes'.`);return a}function rE(e,t,r){let n,i=()=>{if(!n){let m={getSourceFile:g=>g===t.fileName?t:void 0,getDefaultLibFileName:()=>"lib.d.ts",writeFile:()=>{},getCurrentDirectory:()=>"",getCanonicalFileName:g=>g,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>`
+`,fileExists:g=>g===t.fileName,readFile:()=>{},directoryExists:()=>!0,getDirectories:()=>[]},h={...r,noLib:!0,noResolve:!0,allowJs:!0,types:[],alwaysStrict:!0,moduleDetection:e.ModuleDetectionKind.Force};n=e.createProgram({rootNames:[t.fileName],options:h,host:m})}return n},o,a=()=>(o||(o=i().getTypeChecker()),o),s,l=()=>{if(!s){s=new Map;try{for(let m of i().getSemanticDiagnostics(t))m.code===q4&&typeof m.start=="number"&&s.set(m.start,e.flattenDiagnosticMessageText(m.messageText," "))}catch{}}return s},u=m=>e.isImportSpecifier(m)?m.parent.parent.parent:e.isImportClause(m)?m.parent:e.isNamespaceImport(m)?m.parent.parent:void 0,c=m=>{let h=u(m);return h!==void 0&&e.isImportDeclaration(h)&&e.isStringLiteral(h.moduleSpecifier)&&h.moduleSpecifier.text===Xr},d=m=>{var h;for(let g=m;g;g=g.parent)if(e.canHaveModifiers(g)&&((h=e.getModifiers(g))!==null&&h!==void 0?h:[]).some(v=>v.kind===e.SyntaxKind.DeclareKeyword))return!0;return!1},f=m=>d(m)||e.isImportEqualsDeclaration(m)&&(m.isTypeOnly||e.isExternalModuleReference(m.moduleReference))||e.isImportClause(m)&&m.isTypeOnly||e.isNamespaceImport(m)&&m.parent.isTypeOnly||e.isImportSpecifier(m)&&(m.isTypeOnly||m.parent.parent.isTypeOnly),p=m=>{var h;return((h=m?.declarations)!==null&&h!==void 0?h:[]).some(g=>!c(g)&&!f(g))};return{pageOwns:m=>{let h=m.parent;return p(e.isShorthandPropertyAssignment(h)&&h.name===m?a().getShorthandAssignmentValueSymbol(h):a().getSymbolAtLocation(m))},pageOwnsLocalExport:m=>p(a().getExportSpecifierLocalTargetSymbol(m)),initializerShadow:m=>l().get(m.getStart(t))}}function G4(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=rE(e,t,Vm(e)),l=u=>{let c,d;if(e.isPropertyAccessExpression(u)&&e.isIdentifier(u.expression))c=u.expression,d=u.name.text;else if(e.isElementAccessExpression(u)&&e.isIdentifier(u.expression)){let p=u.argumentExpression;e.isStringLiteral(p)||e.isNoSubstitutionTemplateLiteral(p)?(c=u.expression,d=p.text):e.isNumericLiteral(p)&&(c=u.expression,d=String(Number(p.text)))}let f=c&&o.has(c.text)&&n.has(tE(u))&&!s.pageOwns(c)?o.get(c.text):void 0;if(c&&f&&d!==void 0){let p=e.isPropertyAccessExpression(u)?`${f.name}.${d}`:`${f.name}[${JSON.stringify(d)}]`,m=Object.prototype.hasOwnProperty.call(f.runtime,d)?f.runtime[d]:void 0,h=f.labels.get(d),g;m===void 0?g={rule:"genpage-enum-member-unknown",message:`${p} is undefined at runtime: '${f.name}' has no member '${d}' in this environment's metadata \u2014 members are the column's choice labels, so a renamed or differently localized label no longer matches. Known: ${[...f.labels.keys()].map(w=>`'${w}'`).join(", ")}`}:h&&typeof m!="number"?g={rule:"genpage-enum-member-clobbered",message:`${p} is the string '${String(m)}' at runtime, not a choice value: the label '${d}' looks like a number, and another option's reverse mapping overwrites it. Use the choice's numeric value instead.`}:h&&h.length>1&&(g={rule:"genpage-enum-member-ambiguous",message:`${p} labels more than one choice (${h.join(", ")}); the compiled value is whichever option comes last. Use the choice's numeric value instead.`});let v=g?s.initializerShadow(c):void 0;g&&v!==void 0?a(u,"genpage-enum-initializer-shadowed",`${p} does not read the choice enum at runtime. ${v} (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 W4(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===Xr)}function z4(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=new Set(r.statements.filter(s=>e.isImportDeclaration(s)&&e.isStringLiteral(s.moduleSpecifier)&&s.moduleSpecifier.text===Xr).map(s=>s.getStart(r))),i=!0,o="",a=0;for(let s of ZC(t))n.has(s.start)||(i=!1),o+=t.slice(a,s.start),a=s.end;return o+=t.slice(a),{code:o,exact:i}}function nE(e,t,r){if(!r||r.size===0)return[];let n=rE(e,t,{...Vm(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===Xr&&((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))}De.legacyEnumsNeeded=nE;function j4(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 H4(e,t,r,n){let i=new Set,o=YC(e,t,i);if(o.diagnostics.length>0)return o;let a=e.createSourceFile("page.tsx",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.TSX),s=e.createSourceFile("page.js",o.code,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),l=j4(r,n,nE(e,s,n)),u=[...V4(e,s,a,l),...G4(e,a,l,i)];if(!l?.text)return{code:o.code,diagnostics:u};let c=YC(e,l.text);if(c.diagnostics.length>0)throw new _a.SdkError("GENPAGE_RUNTIME_TYPES_INVALID",`The generated runtime types do not compile (${c.diagnostics.map(m=>`${m.line}:${m.column} ${m.message}`).join("; ")}). This is an SDK defect: the page was not written.`);let d=z4(e,o.code),f=d.code;return u.length===0&&!d.exact?u.push({...qm(e,a).statement(Xr,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"the maker portal's patch would remove more than this './RuntimeTypes' import: a comment or other text before it contains the word 'import', and the pattern would delete from there \u2014 taking the code in between with it. Reword or move that text."}):u.length===0&&W4(e,f)&&u.push({...qm(e,a).statement(Xr,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"this './RuntimeTypes' import is not one the maker portal's patch can remove (a comment holding a quote inside it stops the pattern), so it would reach the runtime, which cannot load it. Write it on one line, as 'import { name } from './RuntimeTypes';'."}),{code:[De.GENPAGE_RUNTIME_TYPES_BEGIN,c.code,De.GENPAGE_RUNTIME_TYPES_END,f].join(`
-`),diagnostics:u}}Ee.compileGenPage=oU});var wf=b(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.isFailureAfterPrimaryWrite=Uo.failedAfterPrimaryWrite=void 0;var Ww=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function aU(e){return typeof e=="object"&&e!==null&&(e[Ww]=!0),e}Uo.failedAfterPrimaryWrite=aU;function sU(e){return typeof e=="object"&&e!==null&&e[Ww]===!0}Uo.isFailureAfterPrimaryWrite=sU});var Nu=b(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.appApi=Yr.deleteAppResolvingOnce=Yr.mainFormSetShapeIssues=Yr.unpublishedAppModulesQuery=void 0;var Vo=Rt(),lU=Rf(),uU=lf(),jw=nr(),cU=Au(),dU=wf(),Ae=be(),oe=ae(),Nf=lt(),pU=ql(),fe=re(),fU=(0,oe.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),Af="appmoduleid,name,uniquename,description,aiappdescription";function If(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,oe.odataQuery)([["$select",e],["$filter",t],["$top",r]])}Yr.unpublishedAppModulesQuery=If;function Ef(e,t){return If(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function Su(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,oe.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function qo(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function mU(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Tf(e,t){if(typeof e!="string")return!1;try{return(0,oe.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function qi(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function hU(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function rA(e,t){var r,n;let i=u=>{throw new fe.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,oe.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,oe.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 gU(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,oe.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 Hw="627090ff-40a3-4053-8790-584edc5be201";function _n(e){return e instanceof Error?e.message:String(e)}async function vU(e,t){var r;try{let n=`/roles${(0,oe.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${Hw}`]])}`,i=await(0,Vo.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 ${Hw}) 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,Ae.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 (${_n(n)}); it will not be visible or playable until a role is granted access to it.`}}async function yU(e,t,r=!0){let n=[];async function i(l,u,c){try{return(await(0,Vo.collectPages)(e,l,`app assets (${c} for '${t}')`)).map(p=>String(p[u])).filter(p=>p&&p!=="undefined")}catch(d){return n.push(`App components: could not enumerate ${c} for table '${t}' (${_n(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([r?i(`/systemforms${(0,oe.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,oe.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,oe.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,oe.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,oe.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,oe.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:n}}var Kw=new WeakMap;async function bU(e,t){let r=Kw.get(e);r||(r=new Map,Kw.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await wU(e,t);return i&&r.set(t,i),i}async function Jw(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 wU(e,t){let r=`/EntityDefinitions(LogicalName='${(0,oe.odataPathLiteral)(t)}')${(0,oe.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 Qw(e,t,r){let n=[],i=qi(t.entities),o=4,a=await Jw(i,o,g=>bU(e,g)),s=i.filter((g,y)=>!a[y]);if(s.length>0)throw new fe.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${s.map(g=>`'${g}'`).join(", ")} could not be resolved to an EntityDefinitions MetadataId + EntitySetName. Pinning the rest would produce an app whose navigation references a table the app does not contain. Verify the table name(s) exist in this environment and retry.`);let l=a.filter(g=>!!g);for(let g of l)n.push({"@odata.id":`${g.entitySetName}(${g.metadataId})`});for(let g of qi(t.components.forms))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of qi(t.components.views))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of qi(t.components.charts))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of qi(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),p=new Map((r??[]).map(g=>[g.table,g])),f=await Jw(i,o,g=>yU(e,g,!p.has(g.toLowerCase()))),m=f.flatMap(g=>g.warnings),h=new Set([...qi(t.components.forms),...qi(t.components.dashboards)].map(cr));return f.forEach((g,y)=>{let w=p.get(i[y].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:m}}function cr(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var Df=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,_f="/components/mainFormsByTable",Xw=50;function nA(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function iA(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:_f,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=`${_f}/${nA(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 p=`${l}/${d}`;typeof c!="string"||!Df.test(cr(c))?r.push({pointer:p,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):u.has(cr(c))?r.push({pointer:p,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):u.add(cr(c))})}return r}Yr.mainFormSetShapeIssues=iA;async function Yw(e,t,r){let n=t.components.mainFormsByTable;if(n===void 0)return;let i=iA(n,t.entities);if(i.length>0)throw new fe.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,Vo.collectPages)(e,`/systemforms${(0,oe.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,oe.odataLiteral)(c)}' and type eq 2`]])}`,`app Main-form allow-list ('${c}')`),p=new Set,f=new Set;for(let h of d)typeof h.formid=="string"&&(p.add(cr(h.formid)),Number(h.formactivationstate)===1&&f.add(cr(h.formid)));let m=u.map(cr);m.forEach((h,g)=>{let y=`${_f}/${nA(l)}/${g}`;p.has(h)?f.has(h)||o.push({pointer:y,rule:"app-main-form-set-inactive",message:`Main form '${u[g]}' of '${c}' is inactive, so no app can offer it`}):o.push({pointer:y,rule:"app-main-form-set-not-main-form",message:`'${u[g]}' is not a Main form of '${c}'`})}),a.push({table:c,allowed:m,catalog:p})}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=cr(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 fe.ValidationError("app",r,o);return a}async function oA(e,t,r){var n,i;let o=g=>({kind:"inconclusive",reason:g}),a=await e.get(If("appmoduleid,appmoduleidunique,componentstate",`appmoduleid eq ${t}`));if(a.status<200||a.status>=300)return o(`reading the app returned HTTP ${a.status}`);let s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s)||s.length===0)return o("reading the app returned no row");let l=s.length===1?s:s.filter(g=>Number(g?.componentstate)===1),u=l.length===1?(i=l[0])===null||i===void 0?void 0:i.appmoduleidunique:"";if(typeof u!="string"||!Df.test(cr(u)))return o(`no single current layer among ${s.length} app row(s)`);let c;try{let g=await(0,Vo.collectPages)(e,`/appmodulecomponents${(0,oe.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${cr(u)} and componenttype eq 60`]])}`,`app Main-form membership ('${t}')`);if(g.some(y=>typeof y.objectid!="string"))return o("a form component carries no object id");c=g.map(y=>cr(String(y.objectid)))}catch(g){return o(`reading its form components failed (${_n(g)})`)}let d=new Map,p=[];for(let g of new Set(c)){let y=r.find(w=>w.catalog.has(g));y?d.set(g,y.table):p.push(g)}if(p.some(g=>!Df.test(g)))return o("a form component carries an object id that is not a GUID");let f=new Set(r.map(g=>g.table)),m=new Set;for(let g=0;g<p.length;g+=Xw){let y=p.slice(g,g+Xw);try{let w=await(0,Vo.collectPages)(e,`/systemforms${(0,oe.odataQuery)([["$select","formid,type,objecttypecode"],["$filter",y.map(C=>`formid eq ${C}`).join(" or ")]])}`,`app Main-form membership ('${t}': classifying components)`);for(let C of w){if(typeof C.formid!="string"||typeof C.type!="number"||C.type===2&&(typeof C.objecttypecode!="string"||C.objecttypecode===""))continue;let S=cr(C.formid);m.add(S);let T=C.type===2?String(C.objecttypecode).toLowerCase():"";f.has(T)&&d.set(S,T)}}catch(w){return o(`classifying its form components failed (${_n(w)})`)}}let h=p.filter(g=>!m.has(g));return h.length>0?o(`form component(s) ${h.join(", ")} could not be classified`):{kind:"read",tables:r.map(g=>{let y=[...d].filter(([,w])=>w===g.table).map(([w])=>w);return{table:g.table,members:y,extras:y.filter(w=>!g.allowed.includes(w)),missing:g.allowed.filter(w=>!y.includes(w))}})}}async function AU(e,t,r){let n=await oA(e,t,r);if(n.kind==="inconclusive")throw new fe.SdkError("APP_MAIN_FORM_SET_UNVERIFIED",`App '${t}': its Main-form allow-list was written but could not be verified \u2014 ${n.reason}.`);let i=n.tables.filter(o=>o.extras.length>0||o.missing.length>0);if(i.length>0)throw new fe.SdkError("APP_MAIN_FORM_SET_NOT_APPLIED",`App '${t}': its Main forms do not match the allow-list after the write \u2014 ${i.map(o=>`'${o.table}': unexpected [${o.extras.join(", ")}], missing [${o.missing.join(", ")}]`).join("; ")}.`)}async function EU(e,t,r){let n;try{n=await oA(e,t,r)}catch(o){n={kind:"inconclusive",reason:_n(o)}}if(n.kind==="inconclusive")return[`Main-form membership of app '${t}' could not be verified (${n.reason}).`];let i=[];for(let o of n.tables)o.extras.length>0&&i.push(`Main-form components outside the allow-list remain for table '${o.table}': [${o.extras.join(", ")}]. This option controls additions only; it does not remove existing components. Runtime form availability has not been verified.`),o.missing.length>0&&i.push(`Allow-listed Main forms are not in app '${t}' after the push for table '${o.table}': [${o.missing.join(", ")}]; re-push to retry.`);return i}async function Zw(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,Ae.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}function CU(e){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,oe.odataQuery)([["$select","appmoduleid,appmoduleidunique"],["$filter",`appmoduleid eq ${e}`],["$top",1]])}async function eA(e,t,r){var n;if(r.length===0)return;let i=CU(t),o=await e.get(i);if(o.status<200||o.status>=300)throw new fe.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 the unpublished-aware read returned HTTP ${o.status}. Re-push to retry.`);let a=qo(o),s=a?.appmoduleidunique;if(typeof s!="string"||!s)throw new fe.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 the app did not return an 'appmoduleidunique' to file components under. Re-push to retry.`);let l=`/appmodulecomponents${(0,oe.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${(0,oe.normalizeGuid)(s,`App '${t}' appmoduleidunique`)} and componenttype eq 1`]])}`,u=await e.get(l);if(u.status<200||u.status>=300)throw new fe.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 reading them back returned HTTP ${u.status}. Re-push to retry.`);let c=(n=u.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(c))throw new fe.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 the read-back returned no readable result set. Re-push to retry.`);let d=new Set(c.map(f=>f.objectid).filter(f=>typeof f=="string").map(f=>f.toLowerCase())),p=r.filter(f=>!d.has(f.metadataId.toLowerCase()));if(p.length>0)throw new fe.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${p.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${p.map(f=>`'${f.logicalName}' (expected objectid ${f.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function SU(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`,o;try{o=await DU(e,r.sitemapId,r.sitemapNameUnique)}catch(l){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${_n(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 (${_n(l.error)})`}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${_n(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 e.delete(n);return s(l.status===404?{kind:"deleted"}:sA(l,e.apiUrl(n)))}return e.supportsAtomicBatch?r.sitemapWriteToken?s(await lA(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 NU(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 DU(e,t,r){var n,i,o;let a=Su(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);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 aA(e,t){var r;let n=(0,oe.normalizeGuid)(t,"id"),i=h=>{throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${h} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry; if the app is newly created, publish it first (an unpublished app is not readable).`)},o=`/appmodules(${n})${fU}`,a;try{a=await e.get(o)}catch(h){return i(`reading the app failed (${h.message}).`)}if(a.status<200||a.status>=300)return i(a.status===404?"reading the app returned HTTP 404, which does NOT prove it is absent \u2014 Dataverse also reports an unpublished app that way, and such an app still owns a sitemap.":`reading the app returned HTTP ${a.status}.`);let 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 l=await rA(e,s);if(!l)return{uniquename:s,appEtag:(0,Ae.readEtag)(a)};let u=(0,oe.normalizeGuid)(l,"sitemapId"),c=await Pf(e,u),d=Su(u,"sitemapid,sitemapnameunique,sitemapxml"),p;try{p=await e.get(d)}catch(h){return i(`reading sitemap '${u}' failed (${h.message}).`)}if(p.status<200||p.status>=300)return i(`reading sitemap '${u}' returned HTTP ${p.status}.`);let f=qo(p);if(!f)return i(`sitemap '${u}' was not returned by the unpublished-aware read.`);if(f.sitemapnameunique!==s)return i(`sitemap '${u}' now carries sitemapnameunique '${String(f.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);if(!Tf(f.sitemapid,u))return i(`sitemap '${u}' was read back as a row carrying sitemapid '${String(f.sitemapid)}'.`);let m=f.sitemapxml;return typeof m!="string"?i(`sitemap '${u}' returned no sitemapxml.`):{sitemapId:u,uniquename:s,sitemapXml:m,appEtag:(0,Ae.readEtag)(a),sitemapEtag:c}}async function _U(e,t,r){let n=(0,oe.normalizeGuid)(t,"id"),i=await aA(e,n);await r?.(i.sitemapXml),await cA(e,n,i)}Yr.deleteAppResolvingOnce=_U;async function IU(e,t){let r=await lA(e,t);if(r.kind!=="deleted")throw r.error}function sA(e,t){try{return(0,Ae.ensureSuccess)(e,t),{kind:"deleted"}}catch(r){return uA(e.status)?{kind:"refused",error:r}:{kind:"unknown",error:r}}}async function lA(e,t){let r=`batch_${(0,Nf.newId)()}`,n=`changeset_${(0,Nf.newId)()}`,i=t.map((p,f)=>[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${f+1}`,"",`DELETE ${e.apiUrl(p.path)} HTTP/1.1`,...p.etag?[`If-Match: ${p.etag}`]:[],""].join(`\r
+`),diagnostics:u}}De.compileGenPage=H4});var Wm=b(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.isFailureAfterPrimaryWrite=Ia.failedAfterPrimaryWrite=void 0;var iE=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function K4(e){return typeof e=="object"&&e!==null&&(e[iE]=!0),e}Ia.failedAfterPrimaryWrite=K4;function J4(e){return typeof e=="object"&&e!==null&&e[iE]===!0}Ia.isFailureAfterPrimaryWrite=J4});var Oc=b(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.appApi=En.deleteAppResolvingOnce=En.mainFormSetShapeIssues=En.unpublishedAppModulesQuery=void 0;var Ta=Mt(),Q4=Ym(),Y4=_m(),oE=Tr(),X4=Ec(),Z4=Wm(),le=we(),he=ae(),jm=lt(),vE=Qs(),be=X(),eV=(0,he.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),Hm="appmoduleid,name,uniquename,description,aiappdescription";function Ic(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,he.odataQuery)([["$select",e],["$filter",t],["$top",r]])}En.unpublishedAppModulesQuery=Ic;function Km(e,t){return Ic(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function Tc(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,he.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function ll(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function tV(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Pc(e,t){if(typeof e!="string")return!1;try{return(0,he.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function wo(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function rV(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function bE(e,t){var r,n;let i=u=>{throw new be.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,he.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,he.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 nV(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,he.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 aE="627090ff-40a3-4053-8790-584edc5be201";function ti(e){return e instanceof Error?e.message:String(e)}async function iV(e,t){var r;try{let n=`/roles${(0,he.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${aE}`]])}`,i=await(0,Ta.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 ${aE}) 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,le.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 (${ti(n)}); it will not be visible or playable until a role is granted access to it.`}}async function oV(e,t,r=!0){let n=[];async function i(l,u,c){try{return(await(0,Ta.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}' (${ti(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([r?i(`/systemforms${(0,he.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,he.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,he.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,he.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,he.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,he.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:n}}var sE=new WeakMap;async function aV(e,t){let r=sE.get(e);r||(r=new Map,sE.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await sV(e,t);return i&&r.set(t,i),i}async function lE(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 sV(e,t){let r=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')${(0,he.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 uE(e,t,r){let n=[],i=wo(t.entities),o=4,a=await lE(i,o,g=>aV(e,g)),s=i.filter((g,v)=>!a[v]);if(s.length>0)throw new be.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 wo(t.components.forms))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of wo(t.components.views))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of wo(t.components.charts))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of wo(t.components.dashboards))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});let u=new Set(t.components.forms),c=new Set(t.components.views),d=new Set(t.components.charts),f=new Map((r??[]).map(g=>[g.table,g])),p=await lE(i,o,g=>oV(e,g,!f.has(g.toLowerCase()))),m=p.flatMap(g=>g.warnings),h=new Set([...wo(t.components.forms),...wo(t.components.dashboards)].map(Ar));return p.forEach((g,v)=>{let w=f.get(i[v].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:m}}function Ar(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var Qm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Jm="/components/mainFormsByTable",cE=50;function wE(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function AE(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:Jm,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=`${Jm}/${wE(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"||!Qm.test(Ar(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):u.has(Ar(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):u.add(Ar(c))})}return r}En.mainFormSetShapeIssues=AE;async function dE(e,t,r){let n=t.components.mainFormsByTable;if(n===void 0)return;let i=AE(n,t.entities);if(i.length>0)throw new be.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,Ta.collectPages)(e,`/systemforms${(0,he.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,he.odataLiteral)(c)}' and type eq 2`]])}`,`app Main-form allow-list ('${c}')`),f=new Set,p=new Set;for(let h of d)typeof h.formid=="string"&&(f.add(Ar(h.formid)),Number(h.formactivationstate)===1&&p.add(Ar(h.formid)));let m=u.map(Ar);m.forEach((h,g)=>{let v=`${Jm}/${wE(l)}/${g}`;f.has(h)?p.has(h)||o.push({pointer:v,rule:"app-main-form-set-inactive",message:`Main form '${u[g]}' of '${c}' is inactive, so no app can offer it`}):o.push({pointer:v,rule:"app-main-form-set-not-main-form",message:`'${u[g]}' is not a Main form of '${c}'`})}),a.push({table:c,allowed:m,catalog:f})}let s=[...t.components.forms.map((l,u)=>({id:l,pointer:`/components/forms/${u}`})),...t.components.dashboards.map((l,u)=>({id:l,pointer:`/components/dashboards/${u}`}))];for(let l of s){let u=Ar(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 be.ValidationError("app",r,o);return a}async function lV(e,t){var r,n;let i=u=>({kind:"inconclusive",reason:u}),o=await e.get(Ic("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"||!Qm.test(Ar(l))?i(`no single current layer among ${a.length} app row(s)`):{kind:"read",unique:Ar(l)}}function Dc(e,t){let r;return()=>r??(r=lV(e,t))}async function CE(e,t,r,n=Dc(e,t)){let i=p=>({kind:"inconclusive",reason:p}),o=await n();if(o.kind==="inconclusive")return o;let a=o.unique,s;try{let p=await(0,Ta.collectPages)(e,`/appmodulecomponents${(0,he.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${Ar(a)} and componenttype eq 60`]])}`,`app Main-form membership ('${t}')`);if(p.some(m=>typeof m.objectid!="string"))return i("a form component carries no object id");s=p.map(m=>Ar(String(m.objectid)))}catch(p){return i(`reading its form components failed (${ti(p)})`)}let l=new Map,u=[];for(let p of new Set(s)){let m=r.find(h=>h.catalog.has(p));m?l.set(p,m.table):u.push(p)}if(u.some(p=>!Qm.test(p)))return i("a form component carries an object id that is not a GUID");let c=new Set(r.map(p=>p.table)),d=new Set;for(let p=0;p<u.length;p+=cE){let m=u.slice(p,p+cE);try{let h=await(0,Ta.collectPages)(e,`/systemforms${(0,he.odataQuery)([["$select","formid,type,objecttypecode"],["$filter",m.map(g=>`formid eq ${g}`).join(" or ")]])}`,`app Main-form membership ('${t}': classifying components)`);for(let g of h){if(typeof g.formid!="string"||typeof g.type!="number"||g.type===2&&(typeof g.objecttypecode!="string"||g.objecttypecode===""))continue;let v=Ar(g.formid);d.add(v);let w=g.type===2?String(g.objecttypecode).toLowerCase():"";c.has(w)&&l.set(v,w)}}catch(h){return i(`classifying its form components failed (${ti(h)})`)}}let f=u.filter(p=>!d.has(p));return f.length>0?i(`form component(s) ${f.join(", ")} could not be classified`):{kind:"read",tables:r.map(p=>{let m=[...l].filter(([,h])=>h===p.table).map(([h])=>h);return{table:p.table,members:m,extras:m.filter(h=>!p.allowed.includes(h)),missing:p.allowed.filter(h=>!m.includes(h))}})}}async function uV(e,t,r,n){let i=await CE(e,t,r,n);if(i.kind==="inconclusive")throw new be.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 be.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 cV(e,t,r,n){let i;try{i=await CE(e,t,r,n)}catch(a){i={kind:"inconclusive",reason:ti(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 fE(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,le.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}async function pE(e,t,r,n=Dc(e,t)){var i;if(r.length===0)return;let o=await n();if(o.kind==="inconclusive")throw new be.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,he.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 be.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 be.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 be.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 dV(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`,o;try{o=await pV(e,r.sitemapId,r.sitemapNameUnique)}catch(l){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${ti(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 (${ti(l.error)})`}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${ti(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,le.resendAppSearchIndexRace)(()=>e.delete(n));return s(l.status===404?{kind:"deleted"}:SE(l,e.apiUrl(n)))}return e.supportsAtomicBatch?r.sitemapWriteToken?s(await NE(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 fV(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 pV(e,t,r){var n,i,o;let a=Tc(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new be.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 be.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 mV(e,t){var r;let n;try{n=await e.get(Ic("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!Pc(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 EE(e,t){var r;let n=(0,he.normalizeGuid)(t,"id"),i=v=>{throw new be.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${v} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`)},o=`/appmodules(${n})${eV}`,a;try{a=await e.get(o)}catch(v){return i(`reading the app failed (${v.message}).`)}let s,l=!1;if(a.status===404){let v=await mV(e,n);if(v.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; ${v.why}.`);s=v.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,le.readEtag)(a)},c=await bE(e,s);if(!c)return{uniquename:s,...u};let d=(0,he.normalizeGuid)(c,"sitemapId"),f=await _c(e,d),p=Tc(d,"sitemapid,sitemapnameunique,sitemapxml"),m;try{m=await e.get(p)}catch(v){return i(`reading sitemap '${d}' failed (${v.message}).`)}if(m.status<200||m.status>=300)return i(`reading sitemap '${d}' returned HTTP ${m.status}.`);let h=ll(m);if(!h)return i(`sitemap '${d}' was not returned by the unpublished-aware read.`);if(h.sitemapnameunique!==s)return i(`sitemap '${d}' now carries sitemapnameunique '${String(h.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);if(!Pc(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 hV(e,t,r){let n=(0,he.normalizeGuid)(t,"id"),i=await EE(e,n);await r?.(i.sitemapXml),await _E(e,n,i)}En.deleteAppResolvingOnce=hV;async function gV(e,t){let r=await NE(e,t);if(r.kind!=="deleted")throw r.error}function SE(e,t){try{return(0,le.ensureSuccess)(e,t),{kind:"deleted"}}catch(r){return DE(e.status)?{kind:"refused",error:r}:{kind:"unknown",error:r}}}function yV(e,t){var r;if(e.status!==400&&(e.status<200||e.status>=300))return!1;let n=(r=(0,vE.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,le.namesAppSearchIndexRace)(i.text))}async function NE(e,t){let r=`batch_${(0,jm.newId)()}`,n=`changeset_${(0,jm.newId)()}`,i=t.map((p,m)=>[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${m+1}`,"",`DELETE ${e.apiUrl(p.path)} HTTP/1.1`,...p.etag?[`If-Match: ${p.etag}`]:[],""].join(`\r
`)),o=[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...i,`--${n}--`,`--${r}--`,""].join(`\r
-`),a=e.apiUrl("/$batch"),s;try{s=await e.postBatch(o,r)}catch(p){return{kind:"unknown",error:p}}let l=sA(s,a);if(l.kind!=="deleted")return l;let u=`app '${t[0].path}'`;if(typeof s.body!="string"||s.body.length===0)return{kind:"unknown",error:new fe.ConnectionError(a,s.status,`atomic delete of ${u} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`)};let c=(0,pU.parseChangeSetStatuses)(s.body,i.map((p,f)=>String(f+1)));if(c===void 0)return{kind:"unknown",error:new fe.ConnectionError(a,s.status,`atomic delete of ${u} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let d=c.find(p=>p<200||p>=300);return d!==void 0?{kind:"refused",error:new fe.ConnectionError(a,d,`atomic delete of ${u} was rolled back: the change set reported HTTP ${d}`)}:c.length!==i.length?{kind:"unknown",error:new fe.ConnectionError(a,s.status,`atomic delete of ${u} cannot be confirmed: the $batch response reported ${c.length} operation result(s), expected exactly ${i.length}`)}:{kind:"deleted"}}async function Pf(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,Ae.readEtag)(r)}catch{return null}}async function TU(e,t){let r=`/appmodules(${t})?$select=appmoduleid`,n=await e.get(r);if(n.status!==404)return(0,Ae.ensureSuccess)(n,e.apiUrl(r)),(0,Ae.readEtag)(n)}async function Cf(e,t,r,n){if(!n)return null;let i=await Pf(e,t);if(!i)return null;try{let o=await e.get(Su(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=qo(o);return!a||!Tf(a.sitemapid,t)||a.sitemapnameunique!==n||a.sitemapxml!==r.sitemapxml||a.sitemapname!==r.sitemapname?null:i}catch{return null}}function uA(e){return e>=400&&e<500&&e!==408&&e!==429}function Sf(e,t,r){if(!e)throw new fe.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 cA(e,t,r){let n=`/appmodules(${t})`;if(!r.sitemapId){await PU(e,n,Sf(r.appEtag,t,"app"));return}if(!e.supportsAtomicBatch)throw new fe.SdkError("APP_DELETE_NOT_ATOMIC",`Refusing to delete app '${t}': it owns a sitemap, and the injected HttpClient cannot send a raw body, so the two rows would have to be deleted as separate requests. A failure between them strands the sitemap and permanently reserves the app's unique name. Implement HttpClient.postRaw so the SDK can delete them atomically.`);await IU(e,[{path:n,etag:Sf(r.appEtag,t,"app")},{path:`/sitemaps(${r.sitemapId})`,etag:Sf(r.sitemapEtag,t,"sitemap")}])}async function PU(e,t,r){(0,Ae.ensureSuccess)(await e.delete(t,{headers:{"If-Match":r}}),e.apiUrl(t))}async function tA(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,lU.collectGenPageIds)(t))]}catch(i){throw new fe.SdkError("SITEMAP_TARGET_UNVERIFIABLE",`Refusing to push the app: its sitemap xml could not be parsed, so the generative pages it navigates to cannot be verified (${_n(i)}).`)}if(r.length===0)return;let n=await(0,uU.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new fe.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 RU(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")}Yr.appApi={async get(e,t){var r;let n=(0,oe.normalizeGuid)(t,"id"),i=await TU(e,n),o=Ef(Af,n),a=(0,Ae.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(r=qo(a))!==null&&r!==void 0?r:{};if(!s.appmoduleid)throw new fe.SdkError("APP_NOT_FOUND",`App '${n}' was not found (checked the unpublished-aware projection, which includes drafts).`);let l=await rA(e,s.uniquename),u=l?(0,oe.normalizeGuid)(l,"sitemapId"):void 0,c=null;if(u){c=await Pf(e,u);let p=Su(u,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),f=(0,Ae.ensureSuccess)(await e.get(p),e.apiUrl(p)),m=qo(f),h=g=>{throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${n}': its sitemap '${u}' was located by unique name, but ${g}, 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(!m)return h("the by-id read returned no row");if(m.sitemapnameunique!==s.uniquename)throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${n}': sitemap '${u}' now carries sitemapnameunique '${String(m.sitemapnameunique)}', not '${String(s.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!Tf(m.sitemapid,u))return h(`the by-id read returned a row carrying sitemapid '${String(m.sitemapid)}'`);if(typeof m.sitemapxml!="string")return h("the by-id read returned no sitemapxml");s.$sitemap=m}let d=i??mU(s);return{raw:s,etag:c,...s.appmoduleid?{siblingEtags:{[(0,oe.normalizeGuid)(s.appmoduleid,"appmoduleid")]:d}}:{}}},async list(e,t){let r=Ef(Af);return(await(0,Vo.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 tA(e,n.sitemapxml);let i=await Yw(e,n,n.appModuleId),o=n.iconWebResourceId?void 0:await gU(e),a=n.iconWebResourceId||o?.id;if(!a)throw new fe.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||hU(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,Ae.ensureSuccess)(await(0,Ae.resendDeadlockVictim)(()=>e.post(c,(0,Ae.withClientMintedId)(u,"appmoduleid",r))),e.apiUrl(c)),p=(0,Ae.resolveCreatedId)(d,"appmoduleid","app module",r),f=null,m=null,h=[];s&&h.push(s);let g={kind:"notRequested"},y=n.sitemapId?(0,oe.normalizeGuid)(n.sitemapId,"sitemapId"):(0,Nf.newId)(),w=!1,C={sitemapxml:n.sitemapxml,sitemapname:n.sitemapname};try{let T="/sitemaps",O=(0,Ae.echoWrite)("sitemapid"),k=await e.post(`${T}${O.query}`,{sitemapid:y,sitemapnameunique:l,...C},O.options);w=uA(k.status);let F=(0,Ae.ensureSuccess)(k,e.apiUrl(T));m=(0,Ae.readEtag)(F),f=m??await Cf(e,y,C,l);let P=await Qw(e,n,i);h.push(...P.warnings);let q=P.components;q.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:y}),await Zw(e,p,q),await eA(e,p,P.tables),i&&await AU(e,p,i);let V=await vU(e,p);V&&h.push(V),n.appSettings&&Object.keys(n.appSettings).length>0&&h.push(...await(0,cU.applyAppSettings)(e,p,n.appSettings)),n.published!==!1&&(await(0,jw.publishAppModule)(e,p),g={kind:"submitted"})}catch(T){let O=await SU(e,p,{sitemapId:y,sitemapNameUnique:l,serverRefusedSitemap:w,sitemapWriteToken:m});throw(0,dU.failedAfterPrimaryWrite)(NU(T,O,{appId:p,sitemapId:y,uniqueName:l}))}let S=null;if(g.kind==="submitted")try{let T=await e.get(`/appmodules(${p})?$select=appmoduleid`);T.status>=200&&T.status<300&&(S=(0,Ae.readEtag)(T))}catch{}return{id:p,etag:f,serverIdentity:{sitemapId:y},siblingEtags:{[p]:S},publish:g,...h.length>0?{warnings:h}:{}}},async update(e,t,r,n,i,o){var a,s,l,u,c,d,p,f,m;let h=r,g=(0,oe.normalizeGuid)(t,"id");if(await tA(e,h.sitemapxml),!h.sitemapId)throw new fe.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 y=(0,oe.normalizeGuid)(h.sitemapId,"sitemapId");if(!n)throw new fe.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${g}': 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 Yw(e,h,g),C=await Qw(e,h,w),S=`/appmodules(${g})`,T=(a=o?.[g])!==null&&a!==void 0?a:null,O=!0,k=!1,F;try{let ot=Ef(Af,g),Kn=await e.get(ot);if(Kn.status>=200&&Kn.status<300){let Br=(s=qo(Kn))!==null&&s!==void 0?s:{};k=!0,F=typeof Br.uniquename=="string"&&Br.uniquename?Br.uniquename:void 0,O=String((l=Br.name)!==null&&l!==void 0?l:"")!==String((u=h.appModuleName)!==null&&u!==void 0?u:"")||String((c=Br.description)!==null&&c!==void 0?c:"")!==String((d=h.appModuleDescription)!==null&&d!==void 0?d:"")||h.appModuleAiDescription!==void 0&&String((p=Br.aiappdescription)!==null&&p!==void 0?p:"")!==String(h.appModuleAiDescription)}}catch{}let P=T;if(O){let ot=k?T:null,Kn=ot?(0,Ae.echoWrite)("appmoduleid",{"If-Match":ot}):{query:"",options:void 0},Br=await e.patch(`${S}${Kn.query}`,{name:h.appModuleName,description:h.appModuleDescription,...h.appModuleAiDescription!==void 0?{aiappdescription:h.appModuleAiDescription}:{}},Kn.options);if(RU(Br))throw new fe.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,Ae.ensureSuccess)(Br,e.apiUrl(S)),P=(0,Ae.readEtag)(Br)}let q={sitemapxml:h.sitemapxml,sitemapname:h.sitemapname},V=F||h.appModuleUniqueName||void 0,Ve=(0,Ae.echoWrite)("sitemapid",{"If-Match":n}),Pt=`/sitemaps(${y})`,Je;try{Je=(0,Ae.ensureSuccess)(await e.patch(`${Pt}${Ve.query}`,{...q},Ve.options),e.apiUrl(Pt))}catch(ot){throw(0,fe.withPartialTokens)(ot,{siblingEtags:{[g]:P}})}let Ge=[...C.warnings];try{await Zw(e,g,C.components),await eA(e,g,C.tables)}catch(ot){Ge.push(`App '${g}': one or more components were not pinned (${ot.message}). Navigation may reference content not included in the app; re-push to retry.`)}w&&Ge.push(...await EU(e,g,w));let Z={kind:"notRequested"},ye=P,hn=(f=(0,Ae.readEtag)(Je))!==null&&f!==void 0?f:await Cf(e,y,q,V);if(h.published===!0){try{await(0,jw.publishAppModule)(e,g),Z={kind:"submitted"}}catch(ot){Z={kind:"failed",error:ot},Ge.push(`App '${g}': saved, but publishing failed (${ot.message}). The app remains unpublished; re-push to retry.`)}if(Z.kind==="submitted"){ye=null;try{let ot=await e.get(`/appmodules(${g})?$select=appmoduleid`);ot.status>=200&&ot.status<300&&(ye=(0,Ae.readEtag)(ot)),hn=(m=await Cf(e,y,q,V))!==null&&m!==void 0?m:hn}catch{}}}return{id:g,etag:hn,siblingEtags:{[g]:ye},publish:Z,...Ge.length>0?{warnings:Ge}:{}}},async delete(e,t){let r=(0,oe.normalizeGuid)(t,"id");await cA(e,r,await aA(e,r))}}});var Rf=b(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});Go.deleteAppCascade=Go.collectGenPageIds=void 0;var OU=Nu(),xU=re(),Of=ae(),LU=iu();function dA(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),i=new LU.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new xU.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,Of.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}Go.collectGenPageIds=dA;async function kU(e,t,r){let n=(0,Of.normalizeGuid)(t,"appModuleId");(0,Of.normalizeGuid)(r,"appModuleIdUnique");let i=[],o=[],a=[];await(0,OU.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&a.push(...dA(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}}Go.deleteAppCascade=kU});var pA={};gn(pA,{Guid:()=>L});var L,ze=R(()=>{"use strict";L=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 M,ht=R(()=>{"use strict";Be();M=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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),r&&(n=n.replace(/"/g,"&quot;").replace(/'/g,"&apos;"))),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(!I.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 I.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 fA={};gn(fA,{ScriptUtilities:()=>I});var I,Be=R(()=>{"use strict";ze();ht();I=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return M.IsNullOrEmpty(t.ToString())?!0:L.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:M.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 Du,_u,Vi,Iu,xf,Tu,Lf=R(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(Du||(Du={}));_u=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},Vi=class extends _u{key;oldValue;newValue;constructor(t,r,n,i){super(Du.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)}},Iu=class extends _u{property;oldValue;newValue;constructor(t,r,n,i){super(Du.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)}},xf=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()})}},Tu=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 xf(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 mA={};gn(mA,{ChartGridMode:()=>dr,ColumnLayoutWidths:()=>UU,ComponentCategory:()=>Ru,ComponentType:()=>kf,ControlLayoutTypes:()=>Vf,DisplayConditionsInfo:()=>BU,ElementNames:()=>A,ElementProperties:()=>v,ElementType:()=>Mf,EntityAttributeProperty:()=>Bf,EventType:()=>ws,FormActivationState:()=>qf,FormCanvasServiceScope:()=>YU,FormDesignerSideBarTab:()=>Ff,FormPresentation:()=>$f,FormState:()=>Pu,FormType:()=>We,HeaderDensityType:()=>ci,LookUpTable:()=>Zr,MORE_TAB_PREFIX:()=>VU,NavBarChildElementType:()=>Uf,PREVIEW_ID_HEADER_FLYOUT:()=>jU,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>KU,PREVIEW_ID_NAVIGATION_AREA:()=>zU,PREVIEW_ID_QUICKCREATE_ROOT:()=>QU,PREVIEW_ID_TAB:()=>JU,PREVIEW_ID_TAB_LIST:()=>HU,PREVIEW_ID_TAB_PANEL:()=>WU,PropertyModelKeys:()=>Wf,PropertyModelSectionKeys:()=>qU,RELATED_TAB_ID:()=>jf,RELATED_TAB_PREFIX:()=>GU,SectionDefaultProperties:()=>$U,SectionLayoutTypes:()=>Te,TabContentType:()=>Gf,TabDefaultProperties:()=>di,TabLayoutTypes:()=>Ie,TelemetryPropertyNames:()=>XU,UnboundControlPropertyKeys:()=>zf,compositeAddressFields:()=>MU,compositeFieldNames:()=>Qt,compositeFields:()=>FU});var We,kf,Ff,A,v,Mf,Qt,FU,MU,Bf,Zr,Pu,ci,$f,BU,Uf,qf,Ie,$U,di,Te,Vf,Gf,UU,zf,Wf,qU,ws,dr,jf,VU,GU,zU,WU,jU,HU,KU,JU,QU,XU,Ru,YU,te=R(()=>{"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"})(We||(We={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(kf||(kf={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(Ff||(Ff={}));(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"})(A||(A={}));v={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"})(Mf||(Mf={}));Qt={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},FU=[Qt.fullname,Qt.yomifullname,Qt.address1_composite,Qt.address2_composite,Qt.address3_composite,Qt.billto,Qt.shipto],MU=[Qt.address1_composite,Qt.address2_composite,Qt.address3_composite,Qt.billto,Qt.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(Bf||(Bf={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(Zr||(Zr={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Pu||(Pu={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(ci||(ci={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})($f||($f={}));BU={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(Uf||(Uf={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(qf||(qf={}));(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"})(Ie||(Ie={}));$U={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},di={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"})(Te||(Te={}));(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"})(Vf||(Vf={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(Gf||(Gf={}));UU={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"})(zf||(zf={}));(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"})(Wf||(Wf={}));qU={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"})(ws||(ws={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(dr||(dr={}));jf="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",VU="more_tab_",GU="related_tab_",zU="preview_id_navigation_area",WU="tab-section",jU="headerFieldsFlyout",HU="tablist",KU="header_overflowButton",JU="tab",QU="quickCreateRoot",XU={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"})(Ru||(Ru={}));YU="CellCanvasServiceScope"});var hA={};gn(hA,{Attribute:()=>Ou,FormElementNode:()=>H});var Ou,H,et=R(()=>{"use strict";Be();ht();Lf();te();ze();Ou=class{key;value;constructor(t,r){this.key=t,this.value=r}},H=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-${L.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(A.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new Ou(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 Vi(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 Vi(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 Vi(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 Iu(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 Vi(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){I.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(I.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:M.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=I.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 A.formCell:let t=this.getAncestor(A.formSection);return t||(t=this.getAncestor(A.formHeader),t)||(t=this.getAncestor(A.formFooter),t)?t:null;case A.formSection:return this.getAncestor(A.formTab);case A.formTab:return this.getAncestor(A.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(A.form);return t?t.changeTracker():null}}});var gA={};gn(gA,{ControlClassId:()=>_,ControlNamePrefixes:()=>xu,getControlDisplayNames:()=>ZU});function ZU(e){return{[_.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[_.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[_.ACIControl]:e("controls.controlNames.aci"),[_.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[_.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[_.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[_.ArticleContentControl]:e("controls.controlNames.articleContent"),[_.BooleanControl]:e("controls.controlNames.twoOption"),[_.ButtonControl]:e("controls.controlNames.button"),[_.CheckboxControl]:e("controls.controlNames.checkbox"),[_.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[_.ConnectionControl]:e("controls.controlNames.connection"),[_.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[_.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[_.DashboardControl]:e("controls.controlNames.dashboard"),[_.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[_.EditFilterControl]:e("controls.controlNames.editFilter"),[_.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[_.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[_.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[_.KBViewerControl]:e("controls.controlNames.kbViewer"),[_.LabelControl]:e("controls.controlNames.label"),[_.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[_.MapLinkControl]:e("controls.controlNames.mapLink"),[_.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[_.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[_.PowerBIControl]:e("controls.controlNames.powerBI"),[_.ProcessControl]:e("controls.controlNames.process"),[_.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[_.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[_.ReportControl]:e("controls.controlNames.report"),[_.StreamsControl]:e("controls.controlNames.streams"),[_.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[_.CurrencyControl]:e("controls.controlNames.currency"),[_.DateTimeControl]:e("controls.controlNames.dateAndTime"),[_.DecimalControl]:e("controls.controlNames.decimal"),[_.DurationControl]:e("controls.controlNames.duration"),[_.EmailAddressControl]:e("controls.controlNames.email"),[_.FileControl]:e("controls.controlNames.file"),[_.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[_.IframeControl]:e("controls.controlNames.iframe"),[_.ImageControl]:e("controls.controlNames.image"),[_.LookupControl]:e("controls.controlNames.lookup"),[_.MapsControl]:e("controls.controlNames.maps"),[_.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[_.ChoiceControl]:e("controls.controlNames.choice"),[_.QuickViewControl]:e("controls.controlNames.quickView"),[_.QuickFormControl]:e("controls.controlNames.quickForm"),[_.CustomControl]:e("controls.controlNames.customControl"),[_.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[_.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[_.SubgridControl]:e("controls.controlNames.subgrid"),[_.TextAreaControl]:e("controls.controlNames.textArea"),[_.TextboxControl]:e("controls.controlNames.textBox"),[_.TickerControl]:e("controls.controlNames.ticker"),[_.UrlControl]:e("controls.controlNames.url"),[_.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[_.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[_.IntegerControl]:e("controls.controlNames.integer"),[_.TimerControl]:e("controls.controlNames.timer"),[_.TimelineControl]:e("controls.controlNames.timeline"),[_.EmailBodyControl]:e("controls.controlNames.emailBody"),[_.PartyListControl]:e("controls.controlNames.partyList"),[_.TimezoneControl]:e("controls.controlNames.timezone"),[_.LanguageControl]:e("controls.controlNames.language"),[_.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[_.ChoicesControl]:e("controls.controlNames.choices"),[_.RegardingControl]:e("controls.controlNames.regarding"),[_.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[_.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[_.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[_.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[_.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[_.KBEditorControl]:e("controls.controlNames.KBEditor"),[_.LinkControl]:e("controls.controlNames.link")}}var _,xu,Gi=R(()=>{"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"})(_||(_={}));xu={[_.WebResourceHTMLControl]:"WebResource",[_.WebResourceImageControl]:"WebResource",[_.IframeControl]:"IFRAME",[_.SearchWidgetControl]:"Search widget",[_.SubgridControl]:"Subgrid",[_.TimelineControl]:"Timeline",[_.QuickViewControl]:"QuickviewControl"}});var zi=b((KX,yA)=>{var As=new Proxy(function(){return As},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:As},apply:function(){return As},construct:function(){return{}}}),vA=function(){return As};Object.setPrototypeOf(vA,As);yA.exports=vA});var Et,In,bA,wA,zo=R(()=>{"use strict";Et="cds-designer-models",In="FormCustomControl",bA="FormCell",wA="Form"});var Wo,Ct,Es=R(()=>{"use strict";Wo=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}},Ct=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 Wi,Hf=R(()=>{"use strict";Es();te();Wi=class e{static lockedFieldCount=new Ct;static dependencyFieldCount=new Ct;static getNecessaryLookUpTable(t){switch(t){case Zr.DependencyFieldTable:return e.dependencyFieldCount;case Zr.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case Zr.DependencyFieldTable:e.dependencyFieldCount=new Ct;case Zr.LockedFieldTable:e.lockedFieldCount=new Ct}}}});var Lu,AA=R(()=>{"use strict";ze();Be();te();et();Lu=class extends H{constructor(t){super(A.controlDescription,t)}get forControl(){let t=this.getProperty(v.ForControl);return I.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new L(t))}set forControl(t){this.setProperty(v.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(A.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!I.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!I.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)I.IsNullOrUndefined(r.id)||t.push(r);return t}async toJSON(t){let r=await this.getCustomControlsJSON(t);return r?{UniqueId:this.forControl.guidString,CustomControls:r,VersionNumber:0,OverallVersionNumber:0}:null}async getCustomControlsJSON(t){if(this.customControls){let r=[];for(let n of this.customControls){let i=await n.toJSON(t);i&&r.push(i)}return r}return null}}});var CA,SA,St,x,EA,pi,ji,jo,Kf,Jf,Ho=R(()=>{"use strict";CA={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"},SA={GroupDefinition:"GroupDefinition"},St={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"})(x||(x={}));(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"})(EA||(EA={}));(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"})(pi||(pi={}));(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"})(ji||(ji={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(jo||(jo={}));Kf=[x.LookupCustomer,x.LookupOwner,x.LookupPartyList,x.LookupRegarding,x.LookupSimple],Jf=[x.WholeNone,x.WholeDuration,x.WholeLanguage,x.WholeTimeZone,x.FP,x.Decimal]});function Tn(){return en||(en=window._makerConfig,en&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(en={...en,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),en?.region==="prod"&&(en={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/"}}},...en}),en||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var en,ku=R(()=>{"use strict";});function NA(e,t,r){if(!e)return Fu.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),Fu.add("")),!1;if(e){if(e=e.toLowerCase(),Fu.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}}),Fu.add(e),!1}return!0}function eq(e){return NA(e,Qf,"Location dictionary")?Qf[e.toLowerCase()]:"us"}function tq(){let e=Tn().location.toLowerCase();return NA(e,Qf,"Current location dictionary")?e:"us"}var Fu,Qf,uY,DA=R(()=>{"use strict";ku();Fu=new Set,Qf={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"};uY=eq(tq())});var z,dY,_A=R(()=>{"use strict";z={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"},dY={[z.USWest]:{geoName:"us",regionShortName:"wus"},[z.USCentral]:{geoName:"us",regionShortName:"cus"},[z.USEast]:{geoName:"us",regionShortName:"eus"},[z.USEast2]:{geoName:"us",regionShortName:"eus2"},[z.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[z.USWest2]:{geoName:"us",regionShortName:"wus2"},[z.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[z.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[z.UKSouth]:{geoName:"uk",regionShortName:"suk"},[z.UKWest]:{geoName:"uk",regionShortName:"wuk"},[z.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[z.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[z.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[z.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[z.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[z.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[z.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[z.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[z.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[z.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[z.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[z.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[z.AsiaEast]:{geoName:"as",regionShortName:"eas"},[z.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[z.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[z.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[z.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[z.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[z.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[z.UAENorth]:{geoName:"ae",regionShortName:"nae"},[z.UAECentral]:{geoName:"ae",regionShortName:"cae"},[z.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[z.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[z.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[z.NorwayEast]:{geoName:"no",regionShortName:"eno"},[z.NorwayWest]:{geoName:"no",regionShortName:"wno"},[z.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[z.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[z.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[z.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[z.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[z.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[z.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[z.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[z.GovernmentUSDodCentral]:{regionShortName:"udc"},[z.GovernmentUSDodEast]:{regionShortName:"ude"},[z.ChinaEast]:{regionShortName:"cne"},[z.ChinaEast2]:{regionShortName:"cne2"},[z.ChinaEast3]:{regionShortName:"cne3"},[z.ChinaNorth]:{regionShortName:"cnn"},[z.ChinaNorth2]:{regionShortName:"cnn2"},[z.ChinaNorth3]:{regionShortName:"cnn3"},[z.UssecEast]:{geoName:"us",regionShortName:"erx"},[z.UssecWest]:{geoName:"us",regionShortName:"wrx"},[z.UsnatEast]:{geoName:"us",regionShortName:"eex"},[z.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var IA=R(()=>{"use strict";ku();});var Cs=R(()=>{"use strict";ku();DA();_A();IA();});function Ss(e,t){return TA?TA.isOverridden(e,t):{overridden:!1}}var TA,Ns=R(()=>{"use strict";});var Xf=R(()=>{"use strict";Cs();Ns();});function rq(e,t){let{region:r}=Tn();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=Ss(e.packageName,t);if(s.overridden)return typeof s.value=="string"?nq(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 nq(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function iq(e){let t=e.packageName;if(Mu.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=>Zf(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=>!$u(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function Ds(e){iq(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:rq(e,r)}}),Mu.set(e.packageName,e),Object.defineProperties({},t)}function Yf(e,t){return Mu.has(e)?!!Mu.get(e).settings[t]:!1}var Mu,Bu=R(()=>{"use strict";Cs();Ns();em();_s();Mu=new Map});function PA(e,t){let{region:r}=Tn();return()=>{let n=Ss(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 oq(e){let t=e.packageName;if(Uu.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=>Yf(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=>!$u(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function tm(e){oq(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:PA(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:PA(e,o.toString())}}),Object.defineProperties(r,i),n.clear()}},Uu.set(e.packageName,e),Object.defineProperties(r,t)}function Zf(e,t){return Uu.has(e)?!!Uu.get(e).features[t]:!1}var Uu,em=R(()=>{"use strict";Cs();_s();Ns();Bu();Uu=new Map});var OA=b((FY,RA)=>{"use strict";RA.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 kA=b(rm=>{"use strict";var aq=Object.prototype.hasOwnProperty,sq;function xA(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function LA(e){try{return encodeURIComponent(e)}catch{return null}}function lq(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=xA(n[1]),o=xA(n[2]);i===null||o===null||i in r||(r[i]=o)}return r}function uq(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(aq.call(e,i)){if(n=e[i],!n&&(n===null||n===sq||isNaN(n))&&(n=""),i=LA(i),n=LA(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}rm.stringify=uq;rm.parse=lq});var om=b((BY,qA)=>{"use strict";var MA=OA(),qu=kA(),BA=/[\n\r\t]/g,cq=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,dq=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,pq=/^[a-zA-Z]:/,fq=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function im(e){return(e||"").toString().replace(fq,"")}var nm=[["#","hash"],["?","query"],function(t,r){return tn(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]],FA={hash:1,query:1};function $A(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 rn(unescape(e.pathname),{});else if(i==="string"){n=new rn(e,{});for(o in FA)delete n[o]}else if(i==="object"){for(o in e)o in FA||(n[o]=e[o]);n.slashes===void 0&&(n.slashes=cq.test(e.href))}return n}function tn(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function UA(e,t){e=im(e),e=e.replace(BA,""),t=t||{};var r=dq.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)):tn(n)?s=r[4]:n?i&&(s=s.slice(2)):a>=2&&tn(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||tn(n),slashesCount:a,rest:s}}function mq(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 rn(e,t,r){if(e=im(e),e=e.replace(BA,""),!(this instanceof rn))return new rn(e,t,r);var n,i,o,a,s,l,u=nm.slice(),c=typeof t,d=this,p=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=qu.parse),t=$A(t),i=UA(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||pq.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!tn(d.protocol)))&&(u[3]=[/(.*)/,"pathname"]);p<u.length;p++){if(a=u[p],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=mq(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&tn(d.protocol)&&(d.pathname="/"+d.pathname),MA(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:"&&tn(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function hq(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||qu.parse)(t)),n[e]=t;break;case"port":n[e]=t,MA(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<nm.length;a++){var s=nm[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:"&&tn(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function gq(e){(!e||typeof e!="function")&&(e=qu.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||tn(r.protocol)?"//":"");return r.username?(o+=r.username,r.password&&(o+=":"+r.password),o+="@"):r.password?(o+=":"+r.password,o+="@"):r.protocol!=="file:"&&tn(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}rn.prototype={set:hq,toString:gq};rn.extractProtocol=UA;rn.location=$A;rn.trimLeft=im;rn.qs=qu;qA.exports=rn});var vq,VA=R(()=>{"use strict";vq=de(om());});function am(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 Vu=R(()=>{"use strict";});var sm,lm,um=R(()=>{"use strict";Vu();sm=class{features=new Map;register(t,r){let n=am(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()}},lm=new sm});var cm=R(()=>{"use strict";});function $u(e){return yq.has(e)}var yq,_s=R(()=>{"use strict";Xf();em();Bu();Ns();Xf();VA();um();Vu();cm();yq=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var bq,GA=R(()=>{"use strict";_s();bq=Ds({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 Gu,$,W,Hi,Ko,zu,zA,WA,dm,Is=R(()=>{"use strict";Es();Gu=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return dm.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={}));Hi=class extends Gu{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},Ko=class e extends Gu{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?zu.Persistent:parseInt(zu[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(zu||(zu={}));(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"})(zA||(zA={}));(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(WA||(WA={}));dm=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new Wo;return t.add($.TwoOptions,"SystemCustomization.type.bit.label"),t.add($.Customer,"SystemCustomization.type.customer.label"),t.add($.CustomerType,"SystemCustomization.type.customer.label"),t.add($.DateTime,"SystemCustomization.type.datetime.label"),t.add($.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add($.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add($.WholeNumber,"SystemCustomization.type.int.label"),t.add($.LookupType,"SystemCustomization.type.lookup.label"),t.add($.Lookup,"SystemCustomization.type.lookup.label"),t.add($.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add($.Currency,"SystemCustomization.type.money.label"),t.add($.Owner,"SystemCustomization.type.owner.label"),t.add($.OwnerType,"SystemCustomization.type.owner.label"),t.add($.PartyList,"SystemCustomization.type.partylist.label"),t.add($.PartyListType,"SystemCustomization.type.partylist.label"),t.add($.OptionSet,"SystemCustomization.type.picklist.label"),t.add($.State,"SystemCustomization.type.state.label"),t.add($.Status,"SystemCustomization.type.status.label"),t.add($.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add($.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add($.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add($.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add($.VirtualType,"SystemCustomization.type.virtual.label"),t.add($.BigInt,"SystemCustomization.type.bigint.label"),t.add($.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add($.EntityNameType,"SystemCustomization.type.entityname.label"),t.add($.Image,"SystemCustomization.type.image.label"),t.add($.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add($.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add($.LookupType,"SystemCustomization.type.lookuptype.label"),t.add($.Subject,"SystemCustomization.type.subject.label"),t.add(W.Email,"SystemCustomization.String.Format.email"),t.add(W.Text,"SystemCustomization.String.Format.text"),t.add(W.TextArea,"SystemCustomization.String.Format.textarea"),t.add(W.Url,"SystemCustomization.String.Format.url"),t.add(W.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(W.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(W.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(W.Phone,"SystemCustomization.String.Format.phone"),t.add(W.None,"SystemCustomization.Integer.Format."),t.add(W.Duration,"SystemCustomization.Integer.Format.duration"),t.add(W.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(W.Language,"SystemCustomization.Integer.Format.language"),t.add(W.Locale,"SystemCustomization.Integer.Format.language"),t.add(W.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(W.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(W.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(Ko.Persistent,"SystemCustomization.String.Source.persistent"),t.add(Ko.Calculated,"SystemCustomization.String.Source.calculated"),t.add(Ko.Rollup,"SystemCustomization.String.Source.rollup"),t.add(Ko.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var JA,fm,Jo,Ki,pm,Wu,Qo,Pn,De,jA,HA,KA,_r=R(()=>{"use strict";JA={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},fm={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"})(Jo||(Jo={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(Ki||(Ki={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(pm||(pm={}));Wu=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"})(Qo||(Qo={}));Pn=class{static StartTag="<"},De={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:Ki.Left,labelPosition:Qo.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"})(jA||(jA={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(HA||(HA={}));(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"})(KA||(KA={}))});var mm,QA=R(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(mm||(mm={}))});var ZA,wq,XA,FZ,MZ,Ts,YA,BZ,$Z,eE=R(()=>{"use strict";ZA=de(zi());Be();zo();GA();Is();_r();Ho();te();wq=de(Ti());QA();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(XA||(XA={}));FZ={Read:ji.Read,Edit:ji.Edit,Both:ji.Both,Container:ji.Container},MZ={input:jo.Input,bound:jo.Bound,output:jo.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(Ts||(Ts={}));(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"})(YA||(YA={}));BZ=new Set([x.Currency,x.Decimal,x.FP,x.Multiple,x.SingleLineEmail,x.SingleLinePhone,x.SingleLineText,x.SingleLineTextArea,x.SingleLineURL,x.SingleLineTickerSymbol,x.WholeNone,x.WholeDuration,x.WholeLanguage,x.WholeTimeZone,x.Enum,x.LookupSimple,x.LookupCustomer,x.LookupOwner,x.LookupPartyList,x.LookupRegarding,x.TwoOptions,x.Boolean,x.PowerBIReport,x.DateAndTimeDateAndTime,x.DateAndTimeDateOnly,x.OptionSet,x.MultiSelectOptionSet,x.CardForm]),$Z={numbers:[x.WholeNone,x.FP,x.Decimal,x.Currency],text:[x.SingleLineText,x.SingleLineTextArea,x.Multiple],lookup:[x.LookupSimple,x.LookupCustomer,x.LookupOwner,x.LookupPartyList,x.LookupRegarding],dates:[x.DateAndTimeDateOnly,x.DateAndTimeDateAndTime],allFields:[x.TwoOptions,x.DateAndTimeDateOnly,x.DateAndTimeDateAndTime,x.FP,x.Decimal,x.WholeNone,x.WholeDuration,x.WholeTimeZone,x.WholeLanguage,x.LookupSimple,x.LookupCustomer,x.LookupOwner,x.LookupPartyList,x.LookupRegarding,x.Multiple,x.OptionSet,x.SingleLineText,x.SingleLineTextArea,x.SingleLineEmail,x.SingleLineURL,x.SingleLineTickerSymbol,x.SingleLinePhone]}});var Ir,ju,tE=R(()=>{"use strict";Ir=de(zi());ze();Be();ht();zo();Ho();eE();Is();te();et();_r();ju=class extends H{constructor(t){super(A.customControl,t)}customControlId;get id(){let t=this.getProperty(v.id);return I.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new L(t.substr(1,t.length-2)):new L(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(St.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===St.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===St.name)?.value,o={Name:i,Type:x.Grid,Columns:[]},l=this.getParameters().get(St.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===v.static&&o.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(v.Name)}get formFactor(){return this.getProperty(v.formFactor)}set formFactor(t){this.setProperty(v.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(Pn.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),p=await this.parameterJSON(a,u,d,t);r.push({Name:c,Value:p})}else if(this.isGroups(s))r.push({Name:a,Value:{Type:SA.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===Ts.dataset?o.get(St.dataset)?.some(f=>this.getDatasetName(f)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:x.Grid}}):c.propertyType===Ts.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,Ir.trackInfoTrace)(Et,{eventName:`${In}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,Ir.trackErrorTrace)(Et,{eventName:`${In}/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,Ir.trackErrorTrace)(Et,{eventName:`${In}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,Ir.trackErrorTrace)(Et,{eventName:`${In}/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===St.name)?.value;if(o)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${a}`);(0,Ir.trackErrorTrace)(Et,{eventName:`${In}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let o=n,a=r&&r.find(l=>l.key===v.Type),s=o&&!o.ofTypeGroup.every(l=>!Kf.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===pi.FormComponent){let d=this.getFormComponentValueByParameterName(v.bindAttribute),p=await i.formModelService.loadLookupModel(d),f=p.lookupColumn,m=this.getLookupDataTypeFromAttributeMetadata(f);return{Name:t,Type:m,Usage:l,Static:u,Primary:c,EntityName:p.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(CA.DefaultViewId),TargetEntityType:f.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(v.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(v.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(v.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(v.DependentAttributeType),AllowFilterOff:M.IsStrictTrue(this.getFormComponentValueByParameterName(v.AllowFilterOff)),DisableQuickFind:M.IsStrictTrue(this.getFormComponentValueByParameterName(v.DisableQuickFind)),EnableViewPicker:!M.IsStrictTrue(this.getFormComponentValueByParameterName(v.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,Ir.trackErrorTrace)(Et,{eventName:`${In}/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 f=a.value;return{Type:f,Static:u,Usage:l,Value:this.isNumberTypeProperty(o,f)&&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 p=new Error(`No property type info for ${t}`);(0,Ir.trackErrorTrace)(Et,{eventName:`${In}/parameterJSON`,eventData:{message:"Missing property type info"}},p)}else{let l=new Error(`No property manifest info for ${t}`);(0,Ir.trackWarningTrace)(Et,{eventName:`${In}/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 x.LookupCustomer;case $.Owner:return x.LookupOwner;case $.PartyList:return x.LookupPartyList;default:return n===W.Regarding?x.LookupRegarding:x.LookupSimple}}isLookupType(t){return Kf.includes(t)}isNumberTypeProperty(t,r){return Jf.includes(r)||t.ofTypeGroup.some(n=>Jf.includes(n))}isDataSet(t){return St.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var j,hm=R(()=>{"use strict";j=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 U,Xo,je,Hu=R(()=>{"use strict";ze();Es();Be();ht();Is();Gi();hm();_r();U=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"}},Xo=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},je=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new Ct;static initializeFieldControls(){let t=new Ct,r=e.getControlName($.SingleLineofText,W.Phone);t.add(r,new L(U.PhoneNumberControl));let n=e.getControlName($.SingleLineofText,W.TextArea);t.add(n,new L(U.TextAreaControl));let i=e.getControlName($.SingleLineofText,W.Text);t.add(i,new L(U.TextBoxControl));let o=e.getControlName($.SingleLineofText,W.Email);t.add(o,new L(U.EmailAddressControl));let a=e.getControlName($.SingleLineofText,W.Url);t.add(a,new L(U.UrlControl));let s=e.getControlName($.SingleLineofText,W.TickerSymbol);t.add(s,new L(U.TickerControl));let l=e.getControlName($.SingleLineofText,W.PhoneticGuide);t.add(l,new L(U.TextBoxControl));let u=e.getControlName($.WholeNumber,W.Duration);t.add(u,new L(U.DurationControl));let c=e.getControlName($.WholeNumber,W.Language);t.add(c,new L(U.LanguagePickerControl));let d=e.getControlName($.WholeNumber,W.TimeZone);t.add(d,new L(U.TimeZonePicklistControl));let p=e.getControlName($.WholeNumber,W.None);t.add(p,new L(U.IntegerControl));let f=e.getControlName($.DateTime,W.DateOnly);t.add(f,new L(U.DateTimeControl));let m=e.getControlName($.DateTime,W.DateAndTime);t.add(m,new L(U.DateTimeControl));let h=e.getControlName($.LookupType,W.None);t.add(h,new L(U.LookupControl));let g=e.getControlName($.CustomerType,W.None);t.add(g,new L(U.LookupControl));let y=e.getControlName($.FloatingPointNumber,W.None);t.add(y,new L(U.FloatControl));let w=e.getControlName($.DecimalNumber,W.None);t.add(w,new L(U.DecimalControl));let C=e.getControlName($.Currency,W.None);t.add(C,new L(U.MoneyControl));let S=e.getControlName($.MultipleLineofText,W.None);t.add(S,new L(U.TextAreaControl));let T=e.getControlName($.MultipleLineofText,W.Text);t.add(T,new L(U.TextAreaControl));let O=e.getControlName($.MultipleLineofText,W.TextArea);t.add(O,new L(U.TextAreaControl));let k=e.getControlName($.MultipleLineofText,W.Email);t.add(k,new L(U.EmailBodyControl));let F=e.getControlName($.OptionSet,W.None);t.add(F,new L(U.PicklistControl));let P=e.getControlName($.TwoOptions,W.None);t.add(P,new L(U.RadioControl));let q=e.getControlName($.Image,W.None);t.add(q,new L(U.WebResourceImageControl));let V=e.getControlName($.Image,W.None);t.add(V,new L(U.WebResourceHtmlControl));let Ve=e.getControlName($.TwoOptions,"Radio");t.add(Ve,new L(U.RadioControl));let Pt=e.getControlName($.TwoOptions,"CheckBox");t.add(Pt,new L(U.CheckBoxControl));let Je=e.getControlName($.TwoOptions,"List");t.add(Je,new L(U.PicklistControl));let Ge=e.getControlName($.State,W.None);t.add(Ge,new L(U.PicklistControl));let Z=e.getControlName($.Status,W.None);t.add(Z,new L(U.PicklistStatusControl));let ye=e.getControlName($.OwnerType,W.None);t.add(ye,new L(U.LookupControl));let hn=e.getControlName($.PartyListType,W.None);t.add(hn,new L(U.PartyListControl));let ot=e.getControlName($.LookupType,W.Regarding);t.add(ot,new L(U.RegardingControl));let Kn=e.getControlName($.MultiSelectOptionSet,W.None);return t.add(Kn,new L(U.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(!I.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=I.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return I.IsNullOrUndefined(t.control)||I.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===U.CustomControl}static initializeUnboundControls(){let t=new Ct;return t.add(U.ACIControl,j.ACIControl),t.add(U.IframeControl,j.IframeControl),t.add(U.SearchWidgetControl,j.SearchWidgetControl),t.add(U.MapsControl,j.MapsControl),t.add(U.QuickFormCollectionControl,j.QuickFormCollectionControl),t.add(U.GridControl,j.SubGridControl),t.add(U.WebResourceImageControl,j.WebResourceImageControl),t.add(U.WebResourceHtmlControl,j.WebResourceHtmlControl),t.add(U.ReferencePanelSearchWidget,j.SearchWidgetControl),t.add(U.ReferencePanelQuickFormCollectionControl,j.QuickFormCollectionControl),t.add(U.ReferencePanelSubgridControl,j.SubGridControl),t.add(U.TimerControl,j.TimerControl),t.add(U.TimeLineControl,j.NotesControl),t.add(U.TimeLineControlUC,j.NotesControl),t.add(U.SocialInsightControl,j.SocialInsightControl),t.add(Xo.RelationshipAssistant,j.CustomControl),t}static initializeReferencePanelControls(){let t=new Ct;return t.add(U.IframeControl,j.IframeControl),t.add(U.ReferencePanelSearchWidget,j.SearchWidgetControl),t.add(U.ReferencePanelQuickFormCollectionControl,j.QuickFormCollectionControl),t.add(U.ReferencePanelSubgridControl,j.SubGridControl),t.add(U.WebResourceHtmlControl,j.WebResourceHtmlControl),t.add(U.WebResourceImageControl,j.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new Wo;return t.add(Jo.IFRAME,!0),t.add(Jo.SPACER,!0),t.add(Jo.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(I.IsNullOrUndefined(t)||I.IsNullOrUndefined(t.control)||I.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!I.IsNullOrUndefined(t)&&!I.IsNullOrUndefined(t.Name)&&t.Name.indexOf(De.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return I.IsNullOrUndefined(t)||I.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=M.EmptyString;if(I.IsNullOrUndefined(t)||I.IsNullOrUndefined(t.control)||I.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return I.IsNullOrUndefined(t)||I.IsNullOrUndefined(t.guidString)?M.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===U.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===U.CustomControl&&!I.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case j.IframeControl:case j.ACIControl:case j.SocialInsightControl:return 6;case j.SubGridControl:case j.CustomControl:return 4;case j.WebResourceImageControl:return 15;case j.WebResourceHtmlControl:return 15;case j.MapsControl:return 8;case j.SearchWidgetControl:return 10;case j.NotesControl:case j.TimeLineControl:return 15;case j.TimerControl:return 2;default:}}static isLookUpControl(t){return!I.IsNullOrUndefined(t)&&t.ClassId.guidString===U.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!I.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!I.IsNullOrUndefined(t)&&(t.guidString===Xo.RelationshipAssistant||t.guidString===Xo.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!I.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!I.IsNullOrUndefined(t)&&t.guidString===Xo.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(I.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===U.CustomControl&&!I.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var Ku,rE=R(()=>{"use strict";Ku=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 Ji,Yo,nE,iE,fi,oE,aE,gm=R(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(Ji||(Ji={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(Yo||(Yo={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(nE||(nE={}));(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"})(iE||(iE={}));(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"})(fi||(fi={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(oE||(oE={}));(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"})(aE||(aE={}))});var Zo,sE=R(()=>{"use strict";_s();Zo=tm({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 lE(e){return{...e,extractConfig:t=>Aq(t,Object.keys(e.fallback))}}function Aq(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var vm=R(()=>{"use strict";});var ym=b((fee,cE)=>{var Ps=new Proxy(function(){return Ps},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ps},apply:function(){return Ps},construct:function(){return{}}}),uE=function(){return Ps};Object.setPrototypeOf(uE,Ps);cE.exports=uE});var fE=b((mee,pE)=>{var Rs=new Proxy(function(){return Rs},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Rs},apply:function(){return Rs},construct:function(){return{}}}),dE=function(){return Rs};Object.setPrototypeOf(dE,Rs);pE.exports=dE});var bm=b((hee,hE)=>{var Os=new Proxy(function(){return Os},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Os},apply:function(){return Os},construct:function(){return{}}}),mE=function(){return Os};Object.setPrototypeOf(mE,Os);hE.exports=mE});var vE=b((gee,gE)=>{function Eq(){this.__data__=[],this.size=0}gE.exports=Eq});var ea=b((vee,yE)=>{function Cq(e,t){return e===t||e!==e&&t!==t}yE.exports=Cq});var xs=b((yee,bE)=>{var Sq=ea();function Nq(e,t){for(var r=e.length;r--;)if(Sq(e[r][0],t))return r;return-1}bE.exports=Nq});var AE=b((bee,wE)=>{var Dq=xs(),_q=Array.prototype,Iq=_q.splice;function Tq(e){var t=this.__data__,r=Dq(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():Iq.call(t,r,1),--this.size,!0}wE.exports=Tq});var CE=b((wee,EE)=>{var Pq=xs();function Rq(e){var t=this.__data__,r=Pq(t,e);return r<0?void 0:t[r][1]}EE.exports=Rq});var NE=b((Aee,SE)=>{var Oq=xs();function xq(e){return Oq(this.__data__,e)>-1}SE.exports=xq});var _E=b((Eee,DE)=>{var Lq=xs();function kq(e,t){var r=this.__data__,n=Lq(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}DE.exports=kq});var Ls=b((Cee,IE)=>{var Fq=vE(),Mq=AE(),Bq=CE(),$q=NE(),Uq=_E();function ta(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])}}ta.prototype.clear=Fq;ta.prototype.delete=Mq;ta.prototype.get=Bq;ta.prototype.has=$q;ta.prototype.set=Uq;IE.exports=ta});var PE=b((See,TE)=>{var qq=Ls();function Vq(){this.__data__=new qq,this.size=0}TE.exports=Vq});var OE=b((Nee,RE)=>{function Gq(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}RE.exports=Gq});var LE=b((Dee,xE)=>{function zq(e){return this.__data__.get(e)}xE.exports=zq});var FE=b((_ee,kE)=>{function Wq(e){return this.__data__.has(e)}kE.exports=Wq});var wm=b((Iee,ME)=>{var jq=typeof global=="object"&&global&&global.Object===Object&&global;ME.exports=jq});var Tr=b((Tee,BE)=>{var Hq=wm(),Kq=typeof self=="object"&&self&&self.Object===Object&&self,Jq=Hq||Kq||Function("return this")();BE.exports=Jq});var ks=b((Pee,$E)=>{var Qq=Tr(),Xq=Qq.Symbol;$E.exports=Xq});var GE=b((Ree,VE)=>{var UE=ks(),qE=Object.prototype,Yq=qE.hasOwnProperty,Zq=qE.toString,Fs=UE?UE.toStringTag:void 0;function e3(e){var t=Yq.call(e,Fs),r=e[Fs];try{e[Fs]=void 0;var n=!0}catch{}var i=Zq.call(e);return n&&(t?e[Fs]=r:delete e[Fs]),i}VE.exports=e3});var WE=b((Oee,zE)=>{var t3=Object.prototype,r3=t3.toString;function n3(e){return r3.call(e)}zE.exports=n3});var Qi=b((xee,KE)=>{var jE=ks(),i3=GE(),o3=WE(),a3="[object Null]",s3="[object Undefined]",HE=jE?jE.toStringTag:void 0;function l3(e){return e==null?e===void 0?s3:a3:HE&&HE in Object(e)?i3(e):o3(e)}KE.exports=l3});var Rn=b((Lee,JE)=>{function u3(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}JE.exports=u3});var Ju=b((kee,QE)=>{var c3=Qi(),d3=Rn(),p3="[object AsyncFunction]",f3="[object Function]",m3="[object GeneratorFunction]",h3="[object Proxy]";function g3(e){if(!d3(e))return!1;var t=c3(e);return t==f3||t==m3||t==p3||t==h3}QE.exports=g3});var YE=b((Fee,XE)=>{var v3=Tr(),y3=v3["__core-js_shared__"];XE.exports=y3});var tC=b((Mee,eC)=>{var Am=YE(),ZE=(function(){var e=/[^.]+$/.exec(Am&&Am.keys&&Am.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function b3(e){return!!ZE&&ZE in e}eC.exports=b3});var Em=b((Bee,rC)=>{var w3=Function.prototype,A3=w3.toString;function E3(e){if(e!=null){try{return A3.call(e)}catch{}try{return e+""}catch{}}return""}rC.exports=E3});var iC=b(($ee,nC)=>{var C3=Ju(),S3=tC(),N3=Rn(),D3=Em(),_3=/[\\^$.*+?()[\]{}|]/g,I3=/^\[object .+?Constructor\]$/,T3=Function.prototype,P3=Object.prototype,R3=T3.toString,O3=P3.hasOwnProperty,x3=RegExp("^"+R3.call(O3).replace(_3,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function L3(e){if(!N3(e)||S3(e))return!1;var t=C3(e)?x3:I3;return t.test(D3(e))}nC.exports=L3});var aC=b((Uee,oC)=>{function k3(e,t){return e?.[t]}oC.exports=k3});var mi=b((qee,sC)=>{var F3=iC(),M3=aC();function B3(e,t){var r=M3(e,t);return F3(r)?r:void 0}sC.exports=B3});var Qu=b((Vee,lC)=>{var $3=mi(),U3=Tr(),q3=$3(U3,"Map");lC.exports=q3});var Ms=b((Gee,uC)=>{var V3=mi(),G3=V3(Object,"create");uC.exports=G3});var pC=b((zee,dC)=>{var cC=Ms();function z3(){this.__data__=cC?cC(null):{},this.size=0}dC.exports=z3});var mC=b((Wee,fC)=>{function W3(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}fC.exports=W3});var gC=b((jee,hC)=>{var j3=Ms(),H3="__lodash_hash_undefined__",K3=Object.prototype,J3=K3.hasOwnProperty;function Q3(e){var t=this.__data__;if(j3){var r=t[e];return r===H3?void 0:r}return J3.call(t,e)?t[e]:void 0}hC.exports=Q3});var yC=b((Hee,vC)=>{var X3=Ms(),Y3=Object.prototype,Z3=Y3.hasOwnProperty;function e4(e){var t=this.__data__;return X3?t[e]!==void 0:Z3.call(t,e)}vC.exports=e4});var wC=b((Kee,bC)=>{var t4=Ms(),r4="__lodash_hash_undefined__";function n4(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=t4&&t===void 0?r4:t,this}bC.exports=n4});var EC=b((Jee,AC)=>{var i4=pC(),o4=mC(),a4=gC(),s4=yC(),l4=wC();function ra(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])}}ra.prototype.clear=i4;ra.prototype.delete=o4;ra.prototype.get=a4;ra.prototype.has=s4;ra.prototype.set=l4;AC.exports=ra});var NC=b((Qee,SC)=>{var CC=EC(),u4=Ls(),c4=Qu();function d4(){this.size=0,this.__data__={hash:new CC,map:new(c4||u4),string:new CC}}SC.exports=d4});var _C=b((Xee,DC)=>{function p4(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}DC.exports=p4});var Bs=b((Yee,IC)=>{var f4=_C();function m4(e,t){var r=e.__data__;return f4(t)?r[typeof t=="string"?"string":"hash"]:r.map}IC.exports=m4});var PC=b((Zee,TC)=>{var h4=Bs();function g4(e){var t=h4(this,e).delete(e);return this.size-=t?1:0,t}TC.exports=g4});var OC=b((ete,RC)=>{var v4=Bs();function y4(e){return v4(this,e).get(e)}RC.exports=y4});var LC=b((tte,xC)=>{var b4=Bs();function w4(e){return b4(this,e).has(e)}xC.exports=w4});var FC=b((rte,kC)=>{var A4=Bs();function E4(e,t){var r=A4(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}kC.exports=E4});var Xu=b((nte,MC)=>{var C4=NC(),S4=PC(),N4=OC(),D4=LC(),_4=FC();function na(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])}}na.prototype.clear=C4;na.prototype.delete=S4;na.prototype.get=N4;na.prototype.has=D4;na.prototype.set=_4;MC.exports=na});var $C=b((ite,BC)=>{var I4=Ls(),T4=Qu(),P4=Xu(),R4=200;function O4(e,t){var r=this.__data__;if(r instanceof I4){var n=r.__data__;if(!T4||n.length<R4-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new P4(n)}return r.set(e,t),this.size=r.size,this}BC.exports=O4});var Cm=b((ote,UC)=>{var x4=Ls(),L4=PE(),k4=OE(),F4=LE(),M4=FE(),B4=$C();function ia(e){var t=this.__data__=new x4(e);this.size=t.size}ia.prototype.clear=L4;ia.prototype.delete=k4;ia.prototype.get=F4;ia.prototype.has=M4;ia.prototype.set=B4;UC.exports=ia});var VC=b((ate,qC)=>{var $4="__lodash_hash_undefined__";function U4(e){return this.__data__.set(e,$4),this}qC.exports=U4});var zC=b((ste,GC)=>{function q4(e){return this.__data__.has(e)}GC.exports=q4});var jC=b((lte,WC)=>{var V4=Xu(),G4=VC(),z4=zC();function Yu(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new V4;++t<r;)this.add(e[t])}Yu.prototype.add=Yu.prototype.push=G4;Yu.prototype.has=z4;WC.exports=Yu});var KC=b((ute,HC)=>{function W4(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}HC.exports=W4});var QC=b((cte,JC)=>{function j4(e,t){return e.has(t)}JC.exports=j4});var Sm=b((dte,XC)=>{var H4=jC(),K4=KC(),J4=QC(),Q4=1,X4=2;function Y4(e,t,r,n,i,o){var a=r&Q4,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,p=!0,f=r&X4?new H4:void 0;for(o.set(e,t),o.set(t,e);++d<s;){var m=e[d],h=t[d];if(n)var g=a?n(h,m,d,t,e,o):n(m,h,d,e,t,o);if(g!==void 0){if(g)continue;p=!1;break}if(f){if(!K4(t,function(y,w){if(!J4(f,w)&&(m===y||i(m,y,r,n,o)))return f.push(w)})){p=!1;break}}else if(!(m===h||i(m,h,r,n,o))){p=!1;break}}return o.delete(e),o.delete(t),p}XC.exports=Y4});var Nm=b((pte,YC)=>{var Z4=Tr(),eV=Z4.Uint8Array;YC.exports=eV});var eS=b((fte,ZC)=>{function tV(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}ZC.exports=tV});var rS=b((mte,tS)=>{function rV(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}tS.exports=rV});var sS=b((hte,aS)=>{var nS=ks(),iS=Nm(),nV=ea(),iV=Sm(),oV=eS(),aV=rS(),sV=1,lV=2,uV="[object Boolean]",cV="[object Date]",dV="[object Error]",pV="[object Map]",fV="[object Number]",mV="[object RegExp]",hV="[object Set]",gV="[object String]",vV="[object Symbol]",yV="[object ArrayBuffer]",bV="[object DataView]",oS=nS?nS.prototype:void 0,Dm=oS?oS.valueOf:void 0;function wV(e,t,r,n,i,o,a){switch(r){case bV:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case yV:return!(e.byteLength!=t.byteLength||!o(new iS(e),new iS(t)));case uV:case cV:case fV:return nV(+e,+t);case dV:return e.name==t.name&&e.message==t.message;case mV:case gV:return e==t+"";case pV:var s=oV;case hV:var l=n&sV;if(s||(s=aV),e.size!=t.size&&!l)return!1;var u=a.get(e);if(u)return u==t;n|=lV,a.set(e,t);var c=iV(s(e),s(t),n,i,o,a);return a.delete(e),c;case vV:if(Dm)return Dm.call(e)==Dm.call(t)}return!1}aS.exports=wV});var uS=b((gte,lS)=>{function AV(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}lS.exports=AV});var hi=b((vte,cS)=>{var EV=Array.isArray;cS.exports=EV});var pS=b((yte,dS)=>{var CV=uS(),SV=hi();function NV(e,t,r){var n=t(e);return SV(e)?n:CV(n,r(e))}dS.exports=NV});var mS=b((bte,fS)=>{function DV(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}fS.exports=DV});var gS=b((wte,hS)=>{function _V(){return[]}hS.exports=_V});var bS=b((Ate,yS)=>{var IV=mS(),TV=gS(),PV=Object.prototype,RV=PV.propertyIsEnumerable,vS=Object.getOwnPropertySymbols,OV=vS?function(e){return e==null?[]:(e=Object(e),IV(vS(e),function(t){return RV.call(e,t)}))}:TV;yS.exports=OV});var AS=b((Ete,wS)=>{function xV(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}wS.exports=xV});var gi=b((Cte,ES)=>{function LV(e){return e!=null&&typeof e=="object"}ES.exports=LV});var SS=b((Ste,CS)=>{var kV=Qi(),FV=gi(),MV="[object Arguments]";function BV(e){return FV(e)&&kV(e)==MV}CS.exports=BV});var _m=b((Nte,_S)=>{var NS=SS(),$V=gi(),DS=Object.prototype,UV=DS.hasOwnProperty,qV=DS.propertyIsEnumerable,VV=NS((function(){return arguments})())?NS:function(e){return $V(e)&&UV.call(e,"callee")&&!qV.call(e,"callee")};_S.exports=VV});var TS=b((Dte,IS)=>{function GV(){return!1}IS.exports=GV});var Zu=b(($s,oa)=>{var zV=Tr(),WV=TS(),OS=typeof $s=="object"&&$s&&!$s.nodeType&&$s,PS=OS&&typeof oa=="object"&&oa&&!oa.nodeType&&oa,jV=PS&&PS.exports===OS,RS=jV?zV.Buffer:void 0,HV=RS?RS.isBuffer:void 0,KV=HV||WV;oa.exports=KV});var ec=b((_te,xS)=>{var JV=9007199254740991,QV=/^(?:0|[1-9]\d*)$/;function XV(e,t){var r=typeof e;return t=t??JV,!!t&&(r=="number"||r!="symbol"&&QV.test(e))&&e>-1&&e%1==0&&e<t}xS.exports=XV});var Im=b((Ite,LS)=>{var YV=9007199254740991;function ZV(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=YV}LS.exports=ZV});var FS=b((Tte,kS)=>{var eG=Qi(),tG=Im(),rG=gi(),nG="[object Arguments]",iG="[object Array]",oG="[object Boolean]",aG="[object Date]",sG="[object Error]",lG="[object Function]",uG="[object Map]",cG="[object Number]",dG="[object Object]",pG="[object RegExp]",fG="[object Set]",mG="[object String]",hG="[object WeakMap]",gG="[object ArrayBuffer]",vG="[object DataView]",yG="[object Float32Array]",bG="[object Float64Array]",wG="[object Int8Array]",AG="[object Int16Array]",EG="[object Int32Array]",CG="[object Uint8Array]",SG="[object Uint8ClampedArray]",NG="[object Uint16Array]",DG="[object Uint32Array]",Ce={};Ce[yG]=Ce[bG]=Ce[wG]=Ce[AG]=Ce[EG]=Ce[CG]=Ce[SG]=Ce[NG]=Ce[DG]=!0;Ce[nG]=Ce[iG]=Ce[gG]=Ce[oG]=Ce[vG]=Ce[aG]=Ce[sG]=Ce[lG]=Ce[uG]=Ce[cG]=Ce[dG]=Ce[pG]=Ce[fG]=Ce[mG]=Ce[hG]=!1;function _G(e){return rG(e)&&tG(e.length)&&!!Ce[eG(e)]}kS.exports=_G});var BS=b((Pte,MS)=>{function IG(e){return function(t){return e(t)}}MS.exports=IG});var US=b((Us,aa)=>{var TG=wm(),$S=typeof Us=="object"&&Us&&!Us.nodeType&&Us,qs=$S&&typeof aa=="object"&&aa&&!aa.nodeType&&aa,PG=qs&&qs.exports===$S,Tm=PG&&TG.process,RG=(function(){try{var e=qs&&qs.require&&qs.require("util").types;return e||Tm&&Tm.binding&&Tm.binding("util")}catch{}})();aa.exports=RG});var tc=b((Rte,GS)=>{var OG=FS(),xG=BS(),qS=US(),VS=qS&&qS.isTypedArray,LG=VS?xG(VS):OG;GS.exports=LG});var Pm=b((Ote,zS)=>{var kG=AS(),FG=_m(),MG=hi(),BG=Zu(),$G=ec(),UG=tc(),qG=Object.prototype,VG=qG.hasOwnProperty;function GG(e,t){var r=MG(e),n=!r&&FG(e),i=!r&&!n&&BG(e),o=!r&&!n&&!i&&UG(e),a=r||n||i||o,s=a?kG(e.length,String):[],l=s.length;for(var u in e)(t||VG.call(e,u))&&!(a&&(u=="length"||i&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||$G(u,l)))&&s.push(u);return s}zS.exports=GG});var rc=b((xte,WS)=>{var zG=Object.prototype;function WG(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||zG;return e===r}WS.exports=WG});var Rm=b((Lte,jS)=>{function jG(e,t){return function(r){return e(t(r))}}jS.exports=jG});var KS=b((kte,HS)=>{var HG=Rm(),KG=HG(Object.keys,Object);HS.exports=KG});var QS=b((Fte,JS)=>{var JG=rc(),QG=KS(),XG=Object.prototype,YG=XG.hasOwnProperty;function ZG(e){if(!JG(e))return QG(e);var t=[];for(var r in Object(e))YG.call(e,r)&&r!="constructor"&&t.push(r);return t}JS.exports=ZG});var Vs=b((Mte,XS)=>{var e9=Ju(),t9=Im();function r9(e){return e!=null&&t9(e.length)&&!e9(e)}XS.exports=r9});var ZS=b((Bte,YS)=>{var n9=Pm(),i9=QS(),o9=Vs();function a9(e){return o9(e)?n9(e):i9(e)}YS.exports=a9});var tN=b(($te,eN)=>{var s9=pS(),l9=bS(),u9=ZS();function c9(e){return s9(e,u9,l9)}eN.exports=c9});var iN=b((Ute,nN)=>{var rN=tN(),d9=1,p9=Object.prototype,f9=p9.hasOwnProperty;function m9(e,t,r,n,i,o){var a=r&d9,s=rN(e),l=s.length,u=rN(t),c=u.length;if(l!=c&&!a)return!1;for(var d=l;d--;){var p=s[d];if(!(a?p in t:f9.call(t,p)))return!1}var f=o.get(e),m=o.get(t);if(f&&m)return f==t&&m==e;var h=!0;o.set(e,t),o.set(t,e);for(var g=a;++d<l;){p=s[d];var y=e[p],w=t[p];if(n)var C=a?n(w,y,p,t,e,o):n(y,w,p,e,t,o);if(!(C===void 0?y===w||i(y,w,r,n,o):C)){h=!1;break}g||(g=p=="constructor")}if(h&&!g){var S=e.constructor,T=t.constructor;S!=T&&"constructor"in e&&"constructor"in t&&!(typeof S=="function"&&S instanceof S&&typeof T=="function"&&T instanceof T)&&(h=!1)}return o.delete(e),o.delete(t),h}nN.exports=m9});var aN=b((qte,oN)=>{var h9=mi(),g9=Tr(),v9=h9(g9,"DataView");oN.exports=v9});var lN=b((Vte,sN)=>{var y9=mi(),b9=Tr(),w9=y9(b9,"Promise");sN.exports=w9});var cN=b((Gte,uN)=>{var A9=mi(),E9=Tr(),C9=A9(E9,"Set");uN.exports=C9});var pN=b((zte,dN)=>{var S9=mi(),N9=Tr(),D9=S9(N9,"WeakMap");dN.exports=D9});var wN=b((Wte,bN)=>{var Om=aN(),xm=Qu(),Lm=lN(),km=cN(),Fm=pN(),yN=Qi(),sa=Em(),fN="[object Map]",_9="[object Object]",mN="[object Promise]",hN="[object Set]",gN="[object WeakMap]",vN="[object DataView]",I9=sa(Om),T9=sa(xm),P9=sa(Lm),R9=sa(km),O9=sa(Fm),Xi=yN;(Om&&Xi(new Om(new ArrayBuffer(1)))!=vN||xm&&Xi(new xm)!=fN||Lm&&Xi(Lm.resolve())!=mN||km&&Xi(new km)!=hN||Fm&&Xi(new Fm)!=gN)&&(Xi=function(e){var t=yN(e),r=t==_9?e.constructor:void 0,n=r?sa(r):"";if(n)switch(n){case I9:return vN;case T9:return fN;case P9:return mN;case R9:return hN;case O9:return gN}return t});bN.exports=Xi});var IN=b((jte,_N)=>{var Mm=Cm(),x9=Sm(),L9=sS(),k9=iN(),AN=wN(),EN=hi(),CN=Zu(),F9=tc(),M9=1,SN="[object Arguments]",NN="[object Array]",nc="[object Object]",B9=Object.prototype,DN=B9.hasOwnProperty;function $9(e,t,r,n,i,o){var a=EN(e),s=EN(t),l=a?NN:AN(e),u=s?NN:AN(t);l=l==SN?nc:l,u=u==SN?nc:u;var c=l==nc,d=u==nc,p=l==u;if(p&&CN(e)){if(!CN(t))return!1;a=!0,c=!1}if(p&&!c)return o||(o=new Mm),a||F9(e)?x9(e,t,r,n,i,o):L9(e,t,l,r,n,i,o);if(!(r&M9)){var f=c&&DN.call(e,"__wrapped__"),m=d&&DN.call(t,"__wrapped__");if(f||m){var h=f?e.value():e,g=m?t.value():t;return o||(o=new Mm),i(h,g,r,n,o)}}return p?(o||(o=new Mm),k9(e,t,r,n,i,o)):!1}_N.exports=$9});var ON=b((Hte,RN)=>{var U9=IN(),TN=gi();function PN(e,t,r,n,i){return e===t?!0:e==null||t==null||!TN(e)&&!TN(t)?e!==e&&t!==t:U9(e,t,r,n,PN,i)}RN.exports=PN});var LN=b((Kte,xN)=>{var q9=ON();function V9(e,t){return q9(e,t)}xN.exports=V9});var Bm=b((Jte,kN)=>{var G9=mi(),z9=(function(){try{var e=G9(Object,"defineProperty");return e({},"",{}),e}catch{}})();kN.exports=z9});var ic=b((Qte,MN)=>{var FN=Bm();function W9(e,t,r){t=="__proto__"&&FN?FN(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}MN.exports=W9});var $m=b((Xte,BN)=>{var j9=ic(),H9=ea();function K9(e,t,r){(r!==void 0&&!H9(e[t],r)||r===void 0&&!(t in e))&&j9(e,t,r)}BN.exports=K9});var UN=b((Yte,$N)=>{function J9(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}}$N.exports=J9});var VN=b((Zte,qN)=>{var Q9=UN(),X9=Q9();qN.exports=X9});var HN=b((Gs,la)=>{var Y9=Tr(),jN=typeof Gs=="object"&&Gs&&!Gs.nodeType&&Gs,GN=jN&&typeof la=="object"&&la&&!la.nodeType&&la,Z9=GN&&GN.exports===jN,zN=Z9?Y9.Buffer:void 0,WN=zN?zN.allocUnsafe:void 0;function e5(e,t){if(t)return e.slice();var r=e.length,n=WN?WN(r):new e.constructor(r);return e.copy(n),n}la.exports=e5});var QN=b((ere,JN)=>{var KN=Nm();function t5(e){var t=new e.constructor(e.byteLength);return new KN(t).set(new KN(e)),t}JN.exports=t5});var YN=b((tre,XN)=>{var r5=QN();function n5(e,t){var r=t?r5(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}XN.exports=n5});var eD=b((rre,ZN)=>{function i5(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}ZN.exports=i5});var nD=b((nre,rD)=>{var o5=Rn(),tD=Object.create,a5=(function(){function e(){}return function(t){if(!o5(t))return{};if(tD)return tD(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();rD.exports=a5});var Um=b((ire,iD)=>{var s5=Rm(),l5=s5(Object.getPrototypeOf,Object);iD.exports=l5});var aD=b((ore,oD)=>{var u5=nD(),c5=Um(),d5=rc();function p5(e){return typeof e.constructor=="function"&&!d5(e)?u5(c5(e)):{}}oD.exports=p5});var lD=b((are,sD)=>{var f5=Vs(),m5=gi();function h5(e){return m5(e)&&f5(e)}sD.exports=h5});var dD=b((sre,cD)=>{var g5=Qi(),v5=Um(),y5=gi(),b5="[object Object]",w5=Function.prototype,A5=Object.prototype,uD=w5.toString,E5=A5.hasOwnProperty,C5=uD.call(Object);function S5(e){if(!y5(e)||g5(e)!=b5)return!1;var t=v5(e);if(t===null)return!0;var r=E5.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&uD.call(r)==C5}cD.exports=S5});var qm=b((lre,pD)=>{function N5(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}pD.exports=N5});var Vm=b((ure,fD)=>{var D5=ic(),_5=ea(),I5=Object.prototype,T5=I5.hasOwnProperty;function P5(e,t,r){var n=e[t];(!(T5.call(e,t)&&_5(n,r))||r===void 0&&!(t in e))&&D5(e,t,r)}fD.exports=P5});var hD=b((cre,mD)=>{var R5=Vm(),O5=ic();function x5(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?O5(r,s,l):R5(r,s,l)}return r}mD.exports=x5});var vD=b((dre,gD)=>{function L5(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}gD.exports=L5});var bD=b((pre,yD)=>{var k5=Rn(),F5=rc(),M5=vD(),B5=Object.prototype,$5=B5.hasOwnProperty;function U5(e){if(!k5(e))return M5(e);var t=F5(e),r=[];for(var n in e)n=="constructor"&&(t||!$5.call(e,n))||r.push(n);return r}yD.exports=U5});var Gm=b((fre,wD)=>{var q5=Pm(),V5=bD(),G5=Vs();function z5(e){return G5(e)?q5(e,!0):V5(e)}wD.exports=z5});var ED=b((mre,AD)=>{var W5=hD(),j5=Gm();function H5(e){return W5(e,j5(e))}AD.exports=H5});var ID=b((hre,_D)=>{var CD=$m(),K5=HN(),J5=YN(),Q5=eD(),X5=aD(),SD=_m(),ND=hi(),Y5=lD(),Z5=Zu(),e8=Ju(),t8=Rn(),r8=dD(),n8=tc(),DD=qm(),i8=ED();function o8(e,t,r,n,i,o,a){var s=DD(e,r),l=DD(t,r),u=a.get(l);if(u){CD(e,r,u);return}var c=o?o(s,l,r+"",e,t,a):void 0,d=c===void 0;if(d){var p=ND(l),f=!p&&Z5(l),m=!p&&!f&&n8(l);c=l,p||f||m?ND(s)?c=s:Y5(s)?c=Q5(s):f?(d=!1,c=K5(l,!0)):m?(d=!1,c=J5(l,!0)):c=[]:r8(l)||SD(l)?(c=s,SD(s)?c=i8(s):(!t8(s)||e8(s))&&(c=X5(l))):d=!1}d&&(a.set(l,c),i(c,l,n,o,a),a.delete(l)),CD(e,r,c)}_D.exports=o8});var zm=b((gre,PD)=>{var a8=Cm(),s8=$m(),l8=VN(),u8=ID(),c8=Rn(),d8=Gm(),p8=qm();function TD(e,t,r,n,i){e!==t&&l8(t,function(o,a){if(i||(i=new a8),c8(o))u8(e,t,a,r,TD,n,i);else{var s=n?n(p8(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),s8(e,a,s)}},d8)}PD.exports=TD});var Wm=b((vre,RD)=>{function f8(e){return e}RD.exports=f8});var xD=b((yre,OD)=>{function m8(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)}OD.exports=m8});var FD=b((bre,kD)=>{var h8=xD(),LD=Math.max;function g8(e,t,r){return t=LD(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,o=LD(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),h8(e,this,s)}}kD.exports=g8});var BD=b((wre,MD)=>{function v8(e){return function(){return e}}MD.exports=v8});var qD=b((Are,UD)=>{var y8=BD(),$D=Bm(),b8=Wm(),w8=$D?function(e,t){return $D(e,"toString",{configurable:!0,enumerable:!1,value:y8(t),writable:!0})}:b8;UD.exports=w8});var GD=b((Ere,VD)=>{var A8=800,E8=16,C8=Date.now;function S8(e){var t=0,r=0;return function(){var n=C8(),i=E8-(n-r);if(r=n,i>0){if(++t>=A8)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}VD.exports=S8});var WD=b((Cre,zD)=>{var N8=qD(),D8=GD(),_8=D8(N8);zD.exports=_8});var HD=b((Sre,jD)=>{var I8=Wm(),T8=FD(),P8=WD();function R8(e,t){return P8(T8(e,t,I8),e+"")}jD.exports=R8});var JD=b((Nre,KD)=>{var O8=ea(),x8=Vs(),L8=ec(),k8=Rn();function F8(e,t,r){if(!k8(r))return!1;var n=typeof t;return(n=="number"?x8(r)&&L8(t,r.length):n=="string"&&t in r)?O8(r[t],e):!1}KD.exports=F8});var jm=b((Dre,QD)=>{var M8=HD(),B8=JD();function $8(e){return M8(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&&B8(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})}QD.exports=$8});var YD=b((_re,XD)=>{var U8=zm(),q8=jm(),V8=q8(function(e,t,r,n){U8(e,t,r,n)});XD.exports=V8});var pr,zs=R(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(pr||(pr={}))});function e_(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${ZD.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 ZD,G8,t_=R(()=>{"use strict";ZD=de(bm()),G8=de(ym());});var Hm,r_=R(()=>{"use strict";Bu();Hm=Ds({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 i_,o_,a_,s_,Km,z8,oc,n_,Jm=R(()=>{"use strict";i_=de(ym()),o_=de(fE()),a_=de(bm()),s_=de(LN()),Km=de(YD());zs();t_();r_();z8=60*1e3,oc=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=pr.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"?Hm.prodEcsEndpoint:Hm.integrationEcsEndpoint}client=new o_.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=i_.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:[a_.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:e_(this.clientName,n,this.endpointType),...o}),this.client.requestUpdate(),this._status===pr.NotLoaded&&(this._status=pr.Initialized)}catch(s){this._status=pr.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*z8)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,Km.default)({},t.fallback,n,t.override,n_)};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,s_.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,Km.default)({},this.client.getConfig()?.config,this.clientConfigOverride,n_);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=pr.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})}},n_=(e,t)=>{if(Array.isArray(t))return t}});var u_=b((Fre,l_)=>{"use strict";var W8=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};l_.exports=W8});var Qm=b((Mre,d_)=>{var Ws=new Proxy(function(){return Ws},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ws},apply:function(){return Ws},construct:function(){return{}}}),c_=function(){return Ws};Object.setPrototypeOf(c_,Ws);d_.exports=c_});var m_=b((Bre,f_)=>{var js=new Proxy(function(){return js},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:js},apply:function(){return js},construct:function(){return{}}}),p_=function(){return js};Object.setPrototypeOf(p_,js);f_.exports=p_});var A_=b(($re,w_)=>{"use strict";var Xm=m_(),j8={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},H8={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},K8={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},y_={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},Ym={};Ym[Xm.ForwardRef]=K8;Ym[Xm.Memo]=y_;function h_(e){return Xm.isMemo(e)?y_:Ym[e.$$typeof]||j8}var J8=Object.defineProperty,Q8=Object.getOwnPropertyNames,g_=Object.getOwnPropertySymbols,X8=Object.getOwnPropertyDescriptor,Y8=Object.getPrototypeOf,v_=Object.prototype;function b_(e,t,r){if(typeof t!="string"){if(v_){var n=Y8(t);n&&n!==v_&&b_(e,n,r)}var i=Q8(t);g_&&(i=i.concat(g_(t)));for(var o=h_(e),a=h_(t),s=0;s<i.length;++s){var l=i[s];if(!H8[l]&&!(r&&r[l])&&!(a&&a[l])&&!(o&&o[l])){var u=X8(t,l);try{J8(e,l,u)}catch{}}}}return e}w_.exports=b_});function C_(e,t,r){let[n,i]=(0,ua.useState)(e.getConfig(t));return(0,ua.useEffect)(()=>{if(!r?.subscribe&&e.status===pr.ConfigsLoaded)return;let o=e.subscribe(t,a=>{i(a),r?.subscribe||o.unsubscribe()});return o?.unsubscribe},[]),n}function S_(e){return function(t,r){return C_(e,t,r)}}function N_(e,t,r,n){let i=o=>{let a=C_(e,t,n),s={...o,...a};return ua.default.createElement(r,{...s})};return(0,E_.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function D_(e,t,r,n){return t.reduce((i,o)=>N_(e,o,i,n),r)}function __(e){return function(t,r,n){return N_(e,t,r,n)}}var E_,ua,Zm=R(()=>{"use strict";E_=de(A_()),ua=de(Qm());zs();});var T_=b((Vre,I_)=>{var Z8=zm(),e6=jm(),t6=e6(function(e,t,r){Z8(e,t,r)});I_.exports=t6});var ac=b((Gre,P_)=>{var r6=Qi(),n6=gi(),i6="[object Symbol]";function o6(e){return typeof e=="symbol"||n6(e)&&r6(e)==i6}P_.exports=o6});var O_=b((zre,R_)=>{var a6=hi(),s6=ac(),l6=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,u6=/^\w*$/;function c6(e,t){if(a6(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||s6(e)?!0:u6.test(e)||!l6.test(e)||t!=null&&e in Object(t)}R_.exports=c6});var k_=b((Wre,L_)=>{var x_=Xu(),d6="Expected a function";function eh(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(d6);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(eh.Cache||x_),r}eh.Cache=x_;L_.exports=eh});var M_=b((jre,F_)=>{var p6=k_(),f6=500;function m6(e){var t=p6(e,function(n){return r.size===f6&&r.clear(),n}),r=t.cache;return t}F_.exports=m6});var $_=b((Hre,B_)=>{var h6=M_(),g6=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,v6=/\\(\\)?/g,y6=h6(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(g6,function(r,n,i,o){t.push(i?o.replace(v6,"$1"):n||r)}),t});B_.exports=y6});var q_=b((Kre,U_)=>{function b6(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}U_.exports=b6});var H_=b((Jre,j_)=>{var V_=ks(),w6=q_(),A6=hi(),E6=ac(),C6=1/0,G_=V_?V_.prototype:void 0,z_=G_?G_.toString:void 0;function W_(e){if(typeof e=="string")return e;if(A6(e))return w6(e,W_)+"";if(E6(e))return z_?z_.call(e):"";var t=e+"";return t=="0"&&1/e==-C6?"-0":t}j_.exports=W_});var J_=b((Qre,K_)=>{var S6=H_();function N6(e){return e==null?"":S6(e)}K_.exports=N6});var X_=b((Xre,Q_)=>{var D6=hi(),_6=O_(),I6=$_(),T6=J_();function P6(e,t){return D6(e)?e:_6(e,t)?[e]:I6(T6(e))}Q_.exports=P6});var Z_=b((Yre,Y_)=>{var R6=ac(),O6=1/0;function x6(e){if(typeof e=="string"||R6(e))return e;var t=e+"";return t=="0"&&1/e==-O6?"-0":t}Y_.exports=x6});var rI=b((Zre,tI)=>{var L6=Vm(),k6=X_(),F6=ec(),eI=Rn(),M6=Z_();function B6(e,t,r,n){if(!eI(e))return e;t=k6(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var l=M6(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=eI(c)?c:F6(t[i+1])?[]:{})}L6(s,l,u),s=s[l]}return e}tI.exports=B6});var iI=b((ene,nI)=>{var $6=rI();function U6(e,t,r){return e==null?e:$6(e,t,r)}nI.exports=U6});function lI(e){let{query:t}=(0,sI.default)(window.location.href,!0);return V6(e,t),e}function V6(e,t){let r=q6+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+uI,u={};if(o===r)u=s;else if(o.startsWith(l)){let c=o.substring(l.length);(0,aI.default)(u,c,s)}(0,oI.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var oI,aI,sI,uI,q6,cI=R(()=>{"use strict";oI=de(T_()),aI=de(iI()),sI=de(om());uI=".",q6="ecs"+uI});function lc(e,t,r){let n=lI(new oc(e,t,r));function i(o){(0,sc.useEffect)(()=>{n.init(o)},[])}return{featuresClient:n,createFeature:z6(n),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>D_(n,o,a,s)}}function z6(e){let t=S_(e),r=__(e);return function(i){let o=lE(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===pr.ConfigsLoaded,lm.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>r(o,a,s),feature:o}}}var G6,sc,th=R(()=>{"use strict";G6=de(u_()),sc=de(Qm());vm();Jm();zs();Zm();cI();um();});var dI=R(()=>{"use strict";vm();Jm();th();zs();Zm();Vu();cm();});function uc(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,ca.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,ca.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,ca.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var ca,rh=R(()=>{"use strict";ca=de(zi());});var wne,Ane,Ene,pI=R(()=>{"use strict";dI();rh();({featuresClient:wne,createFeature:Ane,useFeaturesClientInitParams:Ene}=lc("PowerApps-Shell-Test",uc("shell-features")))});var hI=b((Sne,mI)=>{var Hs=new Proxy(function(){return Hs},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Hs},apply:function(){return Hs},construct:function(){return{}}}),fI=function(){return Hs};Object.setPrototypeOf(fI,Hs);mI.exports=fI});var W6,j6,gI=R(()=>{"use strict";Cs();W6=de(hI()),j6=de(zi());});var vI=R(()=>{"use strict";pI();rh();gI();});var xne,da,Lne,yI=R(()=>{"use strict";vI();th();({featuresClient:xne,createFeature:da,useFeaturesClientInitParams:Lne}=lc("PowerApps-MakerPortal",uc("powerapps-features")))});var bI,wI,Bne,$ne,Une,qne,nh=R(()=>{"use strict";sE();yI();({feature:bI}=da({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:Zo.enableAutoInsertionOfCellInRow}})),{feature:wI}=da({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:Zo.enableOneGridEvents}}),{feature:Bne}=da({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:Zo.disablePBIComponents}}),{feature:$ne}=da({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:Zo.enableAgentResponse}}),{feature:Une,useFeature:qne}=da({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:Zo.enableDelayedLocalizationForCustomControls}})});var CI=b((Gne,EI)=>{var Ks=new Proxy(function(){return Ks},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ks},apply:function(){return Ks},construct:function(){return{}}}),AI=function(){return Ks};Object.setPrototypeOf(AI,Ks);EI.exports=AI});var gt,vi=R(()=>{"use strict";ze();Be();ht();Hu();te();et();gt=class extends H{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(v.colspan);return I.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){I.IsNullOrUndefined(t)||this.setProperty(v.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(v.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new L(t.substr(1,t.length-2)):new L(t)}set id(t){this.setProperty(v.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(v.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(v.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new L(t.substr(1,t.length-2)):new L(t)}get Name(){return this.getProperty(v.Name)}set Name(t){this.setProperty(v.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(v.languagecode)===r){i.setProperty(v.description,t);return}let n=new H(A.formLabel,null);n.setProperty(v.description,t),n.setProperty(v.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(v.languagecode)===t)return r.getProperty(v.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(v.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(v.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(v.availableforphone)}set availableforphone(t){I.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(v.availableforphone,String(t))}get visible(){return this.getProcessedValue(v.visible)}set visible(t){I.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(v.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(v.showlabel)}set showlabel(t){I.IsNullOrUndefined(t)||this.setProperty(v.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return I.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(A.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(A.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(A.formControl);if(t)return t.getParam(v.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(v.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(A.formControl);if(t)return t.getParam(v.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(v.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(A.formControl);return t?t.getParam(v.DefaultViewId):M.EmptyString}set defaultviewid(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(v.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(A.formControl);return t?t.getParam(v.DependentAttributeName):M.EmptyString}set dependentattributename(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(v.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(A.formControl);return t?t.getParam(v.DependentAttributeType):M.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(v.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(A.formControl);if(t)return t.getParam(v.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(v.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(A.formControl);if(t)return t.getParam(v.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(v.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(A.formControl);return t?t.getParam(v.FilterRelationshipName):M.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(v.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(A.formControl);return t?t.getParam(v.AvailableViewIds):M.EmptyString}set availableviewids(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(v.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(A.formControl);if(t&&t.ClassId){let r=je.getUniqueIdentifierForControl(t);return!I.IsNullOrUndefined(r)&&je.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(A.formControl);if(t){let n=je.getUniqueIdentifierForControl(t).guidString,i=n===U.GridControl||n===U.TimeLineControl||n===U.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===A.formSection||this.NodeName===A.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(A.formControl);if(t){let n=je.getUniqueIdentifierForControl(t).guidString,i=n===U.MapsControl||n===U.WebResourceHtmlControl||n===U.WebResourceImageControl||n===U.IframeControl||n===U.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(A.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(A.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var pa,ih=R(()=>{"use strict";ht();te();et();pa=class extends H{constructor(t,r){super(A.dependency,t),M.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(v.id,t)}get id(){return this.getProperty(v.id)}setDefaultProperties(t){this.id=t}}});var SI,fa,oh=R(()=>{"use strict";Be();ih();te();et();vi();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(SI||(SI={}));fa=class extends gt{constructor(t,r){super(A.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(v.Name,t)}get eventName(){return this.getProperty(v.Name)}set application(t){this.setProperty(v.application,t)}get application(){return this.getProperty(v.application)}set attribute(t){this.setProperty(v.EventAttribute,t)}get attribute(){return this.getProperty(v.EventAttribute)}set relationship(t){this.setProperty(v.Relationship,t)}get relationship(){return this.getProperty(v.Relationship)}set control(t){this.setProperty(v.Control,t)}get control(){return this.getProperty(v.Control)}set active(t){this.setProperty(v.EventActive,t)}get active(){return this.getProperty(v.EventActive)}getAllHandlers(){let t=this.getChildren(A.EventHandlers);return t&&t.length?t[0].getChildren(A.handler):[]}getAllDependencies(){let t=this.getChildren(A.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(A.formDependencies);if(I.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new H(A.formDependencies,this)),r=this.getFirstChild(A.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new pa(r,n.toString()))}}}});var Pr,Js=R(()=>{"use strict";ze();Es();Be();Gi();te();et();_r();Pr=class extends H{previewVersion;constructor(t){super(A.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(v.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new L(t)}set ClassId(t){this.setProperty(v.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(v.datafieldname)}set dataFieldName(t){this.setProperty(v.datafieldname,t)}set id(t){this.setProperty(v.id,t)}get id(){return this.getProperty(v.id)}get UniqueId(){let t=this.getProperty(v.uniqueid);return I.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new L(t))}set UniqueId(t){this.setProperty(v.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(v.isRequired)==="true"}set isRequired(t){I.IsNullOrUndefined(t)||this.setProperty(v.isRequired,String(t))}get disableMru(){return this.getParam(v.DisableMru)==="true"}set disableMru(t){I.IsNullOrUndefined(t)||this.setParameter(v.DisableMru,t)}get useMFDForCreate(){return this.getParam(v.UseMFDForCreate)==="true"}set useMFDForCreate(t){I.IsNullOrUndefined(t)||this.setParameter(v.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(v.UseMFDForEdit)==="true"}set useMFDForEdit(t){I.IsNullOrUndefined(t)||this.setParameter(v.UseMFDForEdit,t)}get disabled(){return this.getProperty(v.disabled)==="true"}set disabled(t){I.IsNullOrUndefined(t)||this.setProperty(v.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(v.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(v.indicationOfSubgrid,String(t))}getAllParameters(){let t=new Ct,r=this.getFirstChild(v.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=(Pn.StartTag+r).toString(),o=this.parametersNode;if(o){let a=o.findFirst(s=>s&&s.getNodeName()===t);if(a)if(n){this.deleteFirstGrandChildOfName(A.controlParameters,a);return}else{let s=a.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):a.addChild(new H(i,a))}else n||(a=new H(t,o),a.addChild(new H(i,a)),o.addChild(a))}else if(!n){o=new H("parameters",this);let a=new H(t,o);a.addChild(new H(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)===Pn.StartTag?o.substring(1):o}}}return null}get parametersNode(){let t=this.getChildren(v.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new Ct;switch(this.ClassId.guidString.toUpperCase()){case _.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(v.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case _.BooleanControl:case _.CheckboxControl:return 0;case _.DateTimeControl:return 2;case _.DecimalControl:return 3;case _.FloatingNumberControl:return 4;case _.IntegerControl:case _.DurationControl:case _.LanguageControl:case _.TimezoneControl:return 5;case _.LookupControl:return 6;case _.CurrencyControl:return 8;case _.PartyListControl:return 10;case _.ChoiceControl:case _.RelationshipRoleChoiceControl:return 11;case _.ChoiceStatusControl:return 13;case _.TextAreaControl:case _.TextboxControl:case _.LabelControl:case _.EmailAddressControl:case _.UrlControl:case _.TickerControl:case _.ButtonControl:case _.PhoneNumberControl:return 14;case _.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===We.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 ma,ah=R(()=>{"use strict";ht();Ho();Js();te();et();ma=class extends Pr{constructor(t){super(t)}get targetEntityType(){return this.getParam(v.targetEntityType)||M.EmptyString}set targetEntityType(t){this.setParameter(v.targetEntityType,t)}get viewId(){return M.StripBraces(this.getParam(v.viewId))||M.EmptyString}set viewId(t){this.setParameter(v.viewId,M.AddBraces(t))}get viewIds(){return this.getParam(v.viewIds)||M.EmptyString}set viewIds(t){this.setParameter(v.viewIds,t)}get relationshipName(){return this.getParam(v.RelationshipName)||M.EmptyString}set relationshipName(t){this.setParameter(v.RelationshipName,t)}get isUserView(){return M.IsStrictTrue(this.getParam(v.isUserView))}set isUserView(t){this.setParameter(v.isUserView,t.toString())}get enableViewPicker(){return M.IsStrictTrue(this.getParam(v.enableViewPicker))}set enableViewPicker(t){this.setParameter(v.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(v.autoExpand)===v.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(v.autoExpand,t?v.Auto:v.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(v.recordsPerPage)?Number(this.getParam(v.recordsPerPage)):Number(v.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(v.recordsPerPage,String(t))}get enableQuickFind(){return M.IsStrictTrue(this.getParam(v.enableQuickFind))}set enableQuickFind(t){this.setParameter(v.enableQuickFind,t)}get teamTemplateId(){return M.StripBraces(this.getParam(v.teamTemplateId))||M.EmptyString}set teamTemplateId(t){this.setParameter(v.teamTemplateId,M.AddBraces(t))}get chartId(){return this.getParam(v.visualizationId)||M.EmptyString}set chartId(t){this.setParameter(v.visualizationId,t)}get enableChartPicker(){return M.IsStrictTrue(this.getParam(v.enableChartPicker))}set enableChartPicker(t){this.setParameter(v.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(v.chartGridMode)){case dr.Chart:return dr.Chart;case dr.Grid:return dr.Grid;default:return dr.All}}set chartGridMode(t){this.setParameter(v.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=dr.Chart:this.chartGridMode=this.enableChartPicker?dr.All:dr.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case v.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case v.viewId:n.getAllChildren()[0].setNodeName("<"+M.AddBraces(r.viewId));break;case v.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case v.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case v.RelationshipName:let i=n.getAllChildren(),o="<"+r.relationshipName;i.length?n.getAllChildren()[0].setNodeName(o):n.addChild(new H(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(St.dataset)?n[i].getParameters().get(St.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 ha,sh=R(()=>{"use strict";ht();Ho();Js();te();ha=class extends Pr{constructor(t){super(t)}get defaultViewId(){return M.StripBraces(this.getParam(v.DefaultViewId))||M.EmptyString}set defaultViewId(t){this.setParameter(v.DefaultViewId,M.AddBraces(t))}get autoResolve(){return M.IsStrictTrue(this.getParam(v.AutoResolve))}set autoResolve(t){this.setParameter(v.AutoResolve,t)}get disableQuickFind(){return M.IsStrictTrue(this.getParam(v.DisableQuickFind))}set disableQuickFind(t){this.setParameter(v.DisableQuickFind,t)}get disableViewPicker(){return M.IsStrictTrue(this.getParam(v.DisableViewPicker))}set disableViewPicker(t){this.setParameter(v.DisableViewPicker,t)}get allowFilterOff(){return M.IsStrictTrue(this.getParam(v.AllowFilterOff))}set allowFilterOff(t){this.setParameter(v.AllowFilterOff,t)}get disableMru(){return M.IsStrictTrue(this.getParam(v.DisableMru))}set disableMru(t){this.setParameter(v.DisableMru,t)}get dependentAttributeName(){return this.getParam(v.DependentAttributeName)||M.EmptyString}set dependentAttributeName(t){this.setParameter(v.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(v.DependentAttributeType)||M.EmptyString}set dependentAttributeType(t){this.setParameter(v.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(v.FilterRelationshipName)||M.EmptyString}set filterRelationshipName(t){this.setParameter(v.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(v.AvailableViewIds)||M.EmptyString}set availableViewIds(t){this.setParameter(v.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case v.datafieldname:case v.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case v.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+M.AddBraces(r.defaultViewId));break;case v.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case v.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case v.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case v.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case v.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case v.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case v.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case v.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case v.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(St.value)?n[i].getParameters().get(St.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 NI,lh,qt,Qs=R(()=>{"use strict";NI=de(CI());vi();te();Be();ze();oh();Js();Hu();hm();Hf();_r();Gi();zo();ah();sh();uh();Is();lh="_",qt=class e extends gt{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(A.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,I.IsNullOrUndefined(this.getProperty(v.id))&&(this.id=new L(L.NewGuid()))}addControl(t,r,n,i,o,a,s){n instanceof Pr?this.addChild(n):n instanceof L&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,o,a,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!I.IsNullOrUndefined(this.control))return I.IsNullOrUndefined(this.control.dataFieldName)?I.IsNullOrUndefined(this.control.id)?!0:!Wi.dependencyFieldCount.containsKey(this.control.id):!Wi.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new fa(this,ws.onLoad))}get dependencies(){let t=this.getChildren(A.formEvents);for(let r of t){let n=r.getChildren(A.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let o;if(i&&xu[i])o=xu[i].replace(/ /g,lh)+lh;else{o="Control_";let u=new Error("Control class id does not exist or is undefined");(0,NI.trackErrorTrace)(Et,{eventName:`${bA}/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,v.isUnbound,"true"),e.prototype.setProperty.call(t,v.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,o,a,s){let l;o===fr.Grid?(l=new ma(this),l.indicationOfSubgrid=!0):o===fr.Lookup?l=new ha(this):l=new Pr(this);let u=n.guidString,c=a||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,v.id,c),l.ClassId=n,!I.IsNullOrUndefined(s)&&(l.UniqueId=s),!a&&r)this.getUnboundControlProperties(l);else{let d=je.getUniqueIdentifierForControl(l);I.IsNullOrUndefined(d)||(je.getControlDataTypeByControlOrUniqueId(d)===j.QuickFormCollectionControl||!je.isUnboundFormControlByIdentifier(d)?o!==fr.Grid&&a&&u!==_.IframeControl&&u!==_.SubgridControl&&u!==_.ReferencePanelSubgridControl&&(l.dataFieldName=a,e.prototype.setProperty.call(l,v.disabled,"false")):(this.rowspan=je.GetRowSpan(l),(je.getControlDataTypeByControlOrUniqueId(d)===j.NotesControl||je.getControlDataTypeByControlOrUniqueId(d)===j.TimeLineControl)&&(e.prototype.setProperty.call(l,v.disabled,"false"),l.id=j.NotesControl)),(je.getUnboundControlNameFromIdentifier(n)===j.SubGridControl||je.getUnboundControlNameFromIdentifier(n)===j.NotesControl||je.getUnboundControlNameFromIdentifier(n)===j.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(I.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(v.id);a.getNodeName()===A.dependency&&s?r.push(s):this.buildDependencyList(a,r)}}}get control(){return this.getFirstChild(A.formControl)}set rowspan(t){this.setProperty(v.rowspan,String(t))}get rowspan(){let t=this.getProperty(v.rowspan);return I.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(v.auto,String(t))}get autoexpand(){return this.getProperty(v.auto)==="true"}set colspan(t){let r=Number(fm.ONE_COLUMN),n=Number(fm.FOUR_COLUMN);I.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(v.colspan,String(t))}get colspan(){let t=this.getProperty(v.colspan);return I.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(A.formRow)}getParentSection(){return this.getAncestor(A.formSection)}getParentTab(){return this.getAncestor(A.formTab)}getParentForm(){return this.getAncestor(A.form)}isInHeader(){let t=this.getAncestor(A.formHeader);return!I.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(A.formFooter);return!I.IsNullOrUndefined(t)}isEmpty(){return I.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(A.formHeader):this.isInFooter()?this.getAncestor(A.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(v.userspacer);return I.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(v.userspacer,"true")}ClearUserSpacer(){this.setProperty(v.userspacer,"false")}get columns(){let t=this.getProperty(v.columnName);return I.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case Te.TWO_COLUMN:r="11";break;case Te.THREE_COLUMN:r="111";break;case Te.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(!I.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();I.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===Hi.ApplicationRequired||a===Hi.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?Hi.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??Hi.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()===A.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()===A.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)===lh&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var ga,ch=R(()=>{"use strict";ht();te();et();ga=class extends H{isInternal;constructor(t,r,n,i){super(A.library,t),this.isInternal=!!i,M.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(v.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(v.libraryUniqueId,t)}get name(){return this.getProperty(v.libraryName)}set name(t){this.setProperty(v.libraryName,t)}get displayName(){return this.getProperty(v.displayName)}set displayName(t){this.setProperty(v.displayName,t)}get description(){return this.getProperty(v.description)}set description(t){this.setProperty(v.description,t)}}});var Yi,dh=R(()=>{"use strict";Be();Qs();te();et();Yi=class extends H{isRowAddedOnDragOver;constructor(t){super(A.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 I.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return I.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(A.formSection)}insertPaddingCellAtIndex(t){let r=new qt(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(A.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 H6(e){switch(e){case Ki.Left:return Ji.Left;case Ki.Right:return Ji.Right;case Ki.Center:return Ji.Center;default:return Ji.Left}}function K6(e){switch(e){case Qo.Left:return Yo.Left;case Qo.Top:return Yo.Top;default:return Yo.Left}}function DI(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var J6,nn,Xs=R(()=>{"use strict";gm();ze();Be();ht();nh();Qs();te();_r();vi();dh();J6=115,nn=class e extends gt{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=Te.ONE_COLUMN;break;case 11:t=Te.TWO_COLUMN;break;case 111:t=Te.THREE_COLUMN;break;case 1111:t=Te.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=De.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+De.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(v.Name,r)}initializeDefaultProperties(t,r,n){if(n===Te.REFERENCE_PANEL){this.addProperty(v.rowheight,"25");let i=`${De.referencePanelNamePrefix}${L.NewGuid()}${De.namePrefix}`;this.addProperty(v.Name,i)}else this.setUniqueName();if(this.addProperty(v.id,new L(L.NewGuid()).guidString),this.addProperty(v.IsUserDefined,De.IsUserDefined),this.addProperty(v.locklevel,De.LockLevel),this.addProperty(v.showlabel,De.ShowLabel),this.addProperty(v.showbar,De.ShowBar),this.addProperty(v.layout,De.Layout),this.addProperty(v.Fieldlabelalignment,De.labelAlignment),this.addProperty(v.Fieldlabelposition,De.labelPosition),I.IsNullOrUndefined(n))this.addProperty(v.columnName,De.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(v.columnName,i)}this.addProperty(v.LabelWidth,De.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case Te.TWO_COLUMN:r="11";break;case Te.THREE_COLUMN:r="111";break;case Te.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 I.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(M.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new Yi(null);if(this.addGrandChild(A.formRows,r),bI.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new qt(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===Te.REFERENCE_PANEL&&(n=Te.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(A.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(A.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(A.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(A.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(A.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(A.formRows);return t.length===0?[]:t[0].getChildren(A.formRow)}get columns(){let t=this.getProperty(v.columnName),r=I.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 DI(n)}return r}set columns(t){I.IsNullOrUndefined(t)||this.setProperty(v.columnName,String(t))}get rowHeight(){let t=this.getProperty(v.rowheight);return I.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(v.rowheight,String(t))}set autoexpand(t){this.setProperty(v.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(v.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(v.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(v.IsUserDefined,"1"):this.setProperty(v.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(A.formColumn)}getParentTab(){return this.getAncestor(A.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(v.showlabel)==="true"}set showlabel(t){I.IsNullOrUndefined(t)||this.setProperty(v.showlabel,String(t))}get fieldLabelAlignment(){let t=De.labelAlignment,r=this.getProperty(v.Fieldlabelalignment);return I.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){I.IsNullOrUndefined(t)||this.setProperty(v.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(v.Fieldlabelposition);return I.IsNullOrUndefined(t)?De.labelPosition:t}set fieldLabelPosition(t){I.IsNullOrUndefined(t)||this.setProperty(v.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(v.showbar)==="true"}set showbar(t){I.IsNullOrUndefined(t)||this.setProperty(v.showbar,String(t))}get labelwidth(){let t=+this.getProperty(v.LabelWidth);return t===0?J6:t}set labelwidth(t){I.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(v.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:H6(this.fieldLabelAlignment),Position:K6(this.fieldLabelPosition)},Columns:DI(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()===A.formSection){let i=n;i.Name&&!M.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!I.IsNullOrUndefined(this)&&!I.IsNullOrUndefined(this.Name)&&this.Name.indexOf(De.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===A.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===A.formFooter||this.NodeName===A.formHeader}}});var yi,cc=R(()=>{"use strict";te();et();Xs();yi=class e extends H{constructor(t){super(A.formColumn,t)}initializeDefaultProperties(t){this.addProperty(v.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(A.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new nn(A.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(A.formSections,t,r)}initialize(t,r,n,i=Te.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(A.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(A.formSection)}get width(){return this.getProperty(v.width)}set width(t){this.setProperty(v.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(A.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(v.Name),Id:this.getProperty(v.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(v.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var dc,_I=R(()=>{"use strict";ze();te();_r();Xs();dc=class extends nn{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(v.Name,n),this.addProperty(v.id,new L(L.NewGuid()).guidString),this.addProperty(v.columnName,De.columns),this.setDisplayName(r,t)}}});var pc,II=R(()=>{"use strict";cc();te();_I();pc=class extends yi{addAndIntializeNavBarSection(t,r,n,i){let o=new dc(A.formSection,null);return o.initializeNavArea(t,r,i),this.addGrandChildAtIndex(A.formSections,o,n),o}}});var On,fc=R(()=>{"use strict";ze();Be();ht();cc();te();et();vi();On=class extends gt{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(A.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(A.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=Ie.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=Ie.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=Ie.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=Ie.TWO_COLUMN_WIDER_RIGHT;break}t=Ie.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=Ie.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=Ie.THREE_COLUMN_WIDER_MID;break}t=Ie.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(v.Name,di.namePrefix+t.toString()),this.addProperty(v.id,new L(L.NewGuid()).guidString),this.addProperty(v.IsUserDefined,di.IsUserDefined),this.addProperty(v.locklevel,di.LockLevel),this.addProperty(v.showlabel,di.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=Te.ONE_COLUMN,o=!0,a){let s=this.getChildren(A.formColumns)[0],l=[];switch(t){case Ie.ONE_COLUMN:l.push(100);break;case Ie.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case Ie.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case Ie.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case Ie.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case Ie.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new yi(s);c.initialize(u,r,n,i),this.addGrandChild(A.formColumns,c)}}initialize(t,r,n,i,o,a=Te.ONE_COLUMN,s=!0,l){this.addChild(new H(A.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,o,a,s,l)}get columns(){let t=this.getChildren(A.formColumns);return t.length!==1?[]:t[0].getChildren(A.formColumn)}get expanded(){return this.getProcessedValue(v.expanded)}set expanded(t){I.IsNullOrUndefined(t)||this.setProperty(v.expanded,String(t))}get groupName(){return this.getProperty(v.groupName)}get contentType(){return this.getProperty(v.contentType)}set contentType(t){this.setProperty(v.contentType,t)}insertNewColumnAtIndex(t,r,n,i,o){t.initialize(n,i,o),this.addGrandChildAtIndex(A.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(A.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(A.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()===A.formTab){let i=n;i.Name&&!M.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var Zi,ph=R(()=>{"use strict";ze();te();et();_r();II();fc();Zi=class extends On{constructor(t,r,n){super(t,Ie.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new L(L.NewGuid())}initializeDefaultProps(){this.addChild(new H(A.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(A.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<Wu.FIVE_COLUMN;t++){let r=new pc(this.getChildren(A.formColumns)[0]);r.initializeDefaultProperties(JA.FiveEqColumn),this.addGrandChild(A.formColumns,r)}}}});function X6(e){switch(e){case We.Main:return fi.Main;case We.QuickCreate:return fi.QuickCreate;case We.QuickViewForm:return fi.Quick;case We.Dialog:return fi.Dialog;default:return fi.None}}function Y6(e,t){if(t===We.Main){if(e)switch(e.toLowerCase()){case"low":return ci.Low;case"highreadonlyvalues":return ci.HighReadOnlyValues;default:return ci.HighWithControls}return ci.Low}}var hc,Q6,mc,TI=R(()=>{"use strict";rE();hc=de(zi());gm();Be();ht();zo();nh();te();Ho();Lf();Gi();Qs();te();vi();ch();ph();fc();Q6="1920";mc=class e extends gt{_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(A.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 Tu,this._metadataChangeEvent=new Ku}get FormLibraries(){let t=this.getFirstChild(A.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 qt).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 qt){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()===A.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let o=i.GetPropertyByParameter(n).replace("$webresource:",""),a=new ga(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,hc.trackErrorTrace)(wA,{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 M.IsNullOrEmpty(this.getProperty(v.ShowImage))?!0:this.getProperty(v.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(v.ShowImage,String(t)):this.setProperty(v.ShowImage,"false")}get ShowNavigation(){return M.IsNullOrEmpty(this.getProperty(v.ShowNavigationbar))?!0:this.getProperty(v.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(v.ShowNavigationbar,String(t)):this.setProperty(v.ShowNavigationbar,"false")}get MaxWidth(){return M.IsNullOrEmpty(this.getProperty(v.MaxWidth))?Q6:this.getProperty(v.MaxWidth)}set MaxWidth(t){this.setProperty(v.MaxWidth,t)}get headerDensityType(){return this.getProperty(v.HeaderDensityType)}set headerDensityType(t){t&&this.formType===We.Main?this.setProperty(v.HeaderDensityType,t):this.formType!==We.Main&&this.headerDensityType&&this.removeProperty(v.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===We.Main||this.formType===We.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(A.formHeader);return t.length!==1?null:t[0]}set header(t){I.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(A.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(A.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return I.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(A.formFooter);return t.length!==1?null:t[0]}set footer(t){I.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new On(null,t),o=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,o,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(A.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,o){let a=new On(null,Ie.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);a.initialize(Ie.ONE_COLUMN,s,this.LanguageCode,r,n,o,!1),this.addGrandChildAtIndex(A.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===di.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(A.formTabs);return t.length!==1?[]:t[0].getChildren(A.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof Zi)return t}return null}get NavigationNode(){let t=this.getChildren(A.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(A.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(A.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(A.formTabs);if(!I.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(A.formFooter).length>0}get displayCondition(){let t=this.getChildren(A.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(A.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(A.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(A.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);I.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(A.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 qt))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 qt&&i.control&&t.control&&o&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==_.CustomControl?!1:this.cellHasCustomControlWithName(t,pi.EditableGridControl)||wI.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,pi.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===_.CustomControl&&this.cellHasCustomControlWithName(t,pi.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()===A.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 Zi)){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,hc.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===We.Main?{HeaderDensity:Y6(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:X6(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 gc,fh,PI=R(()=>{"use strict";ze();Be();te();et();vi();gc=class extends gt{constructor(t){super(A.formDisplayConditions,t)}get Order(){let t=this.getProperty(v.Order);return I.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(v.Order,t.toString())}get FallbackForm(){return this.getProperty(v.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(v.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(A.formEveryOne)&&this.getChildren(A.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new fh(this))}},fh=class extends H{constructor(t){super(A.formEveryOne,t)}}});var vc,RI=R(()=>{"use strict";te();et();vc=class extends H{constructor(t,r){super(A.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(v.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(v.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(v.functionName)}set FunctionName(t){this.setProperty(v.functionName,t)}get LibraryName(){return this.getProperty(v.libraryNameEventHandler)}set LibraryName(t){this.setProperty(v.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(v.enabledForField)}set Enabled(t){this.setProperty(v.enabledForField,t)}get PassExecutionContext(){return this.getProperty(v.passExecutionContext)}set PassExecutionContext(t){this.setProperty(v.passExecutionContext,t)}get Parameters(){return this.getProperty(v.parameters)}set Parameters(t){this.setProperty(v.parameters,t)}}});var va,mh=R(()=>{"use strict";te();Xs();va=class extends nn{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(A.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 Ys,OI=R(()=>{"use strict";te();mh();Ys=class extends va{_customFooter;constructor(t,r){super(A.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 Zs,xI=R(()=>{"use strict";te();mh();Zs=class extends va{_customHeader;constructor(t,r){super(A.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(v.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(v.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(v.showBody)}set showBody(t){t!=null&&this.setProperty(v.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(v.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(v.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 Vt,eo=R(()=>{"use strict";ze();ht();te();vi();Vt=class e extends gt{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(v.LCID)===t)return r.getProperty(v.text);return null}getAllTitles(){let t=this.getChildren(A.Titles);return t.length===0?[]:t[0].getChildren(A.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(v.LCID)===r){i.setProperty(v.text,t);return}let n=new e(A.Title,null);n.setProperty(v.text,t),n.setProperty(v.LCID,String(r)),this.addGrandChild(A.Titles,n)}get Sequence(){return+this.getProperty(v.Sequence)}set Sequence(t){this.setProperty(v.Sequence,t.toString())}get Area(){return this.getProperty(v.Area)}set Area(t){this.setProperty(v.Area,t)}set Id(t){this.setProperty(v.Id,t)}get Id(){return this.getProperty(v.Id)}get id(){return new L(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(v.icon)}set Icon(t){t=t||M.EmptyString,this.setProperty(v.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var el,LI=R(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(el||(el={}))});var yc,kI=R(()=>{"use strict";Be();te();eo();LI();yc=class extends Vt{constructor(t){super(A.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 I.IsNullOrUndefined(r)?el.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):el.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 Se,Z6,FI,Oae,ya,hh=R(()=>{"use strict";ze();te();eo();(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"})(Se||(Se={}));Z6=new Map([[Se.Info,"Info"],[Se.Sales,"Sales"],[Se.Service,"Service"],[Se.Marketing,"Marketing"],[Se.ProcessCenter,"ProcessCenter"]]),FI=new Map([["Info",Se.Info],["Sales",Se.Sales],["Service",Se.Service],["Marketing",Se.Marketing],["ProcessCenter",Se.ProcessCenter]]),Oae=new Map([[Se.Info,9e3],[Se.Sales,9200],[Se.Service,9400],[Se.Marketing,9600],[Se.ProcessCenter,9800],[Se.InternetMarketing,1e4],[Se.Async,10200]]),ya=class extends Vt{constructor(t,r){super(A.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=Z6.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(A.formNavigation)}get AreaId(){return this.getProperty(v.Id)}set AreaId(t){this.setProperty(v.Id,t)}get id(){return new L(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 ba,gh=R(()=>{"use strict";te();eo();ba=class extends Vt{constructor(t,r){super(A.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(A.formNavBarArea)}get ParentNavigation(){return this.getAncestor(A.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var bc,MI=R(()=>{"use strict";Be();te();eo();bc=class extends Vt{RelationshipNameUCIRuntime;constructor(t){super(A.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(v.RelationshipName)}set RelationshipName(t){this.setProperty(v.RelationshipName,t)}set Show(t){this.setProperty(v.Show,String(t))}get Show(){let t=this.getProperty(v.Show);return I.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(v.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 wc,BI=R(()=>{"use strict";te();eo();wc=class extends Vt{constructor(t){super(A.formNavBarItem,t)}get Url(){return this.getProperty(v.url)}set Url(t){this.setProperty(v.url,t)}}});var Ac,$I=R(()=>{"use strict";ze();te();hh();gh();eo();Ac=class extends Vt{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(A.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[Se.Info,Se.Sales,Se.Service,Se.Marketing,Se.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let o=new Set(i.map(a=>FI.get(a.AreaId)));n=n.filter(a=>!o.has(a))}}else{let i=new ba(A.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let o=new ya(A.formNavBarArea,this.navBarAreas);o.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(o)}),!0):!1}get navBar(){return this.getFirstChild(A.formNavBar)}get id(){return new L(jf,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(A.formNavBarAreas,r),this.addGrandChildAtIndex(A.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 UI={};gn(UI,{ControlType:()=>fr,DeserializationService:()=>bh,DeserializationServiceScope:()=>yh,DeserializedFormElementNode:()=>Gt});var vh,Gt,yh,fr,bh,uh=R(()=>{"use strict";vh=de(zi());ze();Be();ht();zo();Hf();Gi();AA();tE();Hu();TI();Qs();cc();Js();ih();te();te();PI();et();_r();oh();RI();OI();ah();sh();xI();ch();dh();Xs();fc();kI();hh();gh();MI();BI();$I();Gt=class extends H{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},yh="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(fr||(fr={}));bh=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 f="";throw d.length===0?f="FormXml has no form node.":f="FormXml has multiple form nodes.",(0,vh.trackErrorTrace)(Et,{eventName:yh,eventData:{error:f}}),new Error(f)}let p=this.createFormModel(d.item(0),r,n,i,o,a,s,l,u,c);return I.IsNullOrUndefined(p.displayCondition)&&s!==We.Dialog&&this.appendDefaultDisplayCondition(p),p}upsertFieldCount(t,r){let n=Wi.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(!I.IsNullOrUndefined(t)){let n=I.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,o,a,s,l,u,c){let d=new mc(r,n,i,o,a,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===We.Main&&(this.insertHeaderFooterElementProperties(A.formHeader,d,d.header),this.insertHeaderFooterElementProperties(A.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(I.IsNullOrUndefined(n)){let i=t===A.formHeader?new Zs(r,!0):new Ys(r,!0);Gt.prototype.insertProperty.call(i,v.id,"{"+L.NewGuid()+"}"),Gt.prototype.insertProperty.call(i,v.Fieldlabelposition,"Top"),Gt.prototype.insertProperty.call(i,v.columnName,De.MarginalControlColumns),Gt.prototype.insertProperty.call(i,v.LabelWidth,De.LabelWidth),Gt.prototype.insertProperty.call(i,v.Fieldlabelalignment,"Left");let o=null,a=new Yi(o);for(let s=0;s<i.maxColumns;s++){let l=new qt(a);Gt.prototype.insertProperty.call(l,v.id,"{"+L.NewGuid()+"}"),l.setDisplayName(M.EmptyString,this.lcid),Gt.prototype.insertProperty.call(l,v.showlabel,"false"),a.addCell(l)}i.appendRow(a),t===A.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 Gt(`<${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,vh.trackErrorTrace)(Et,{eventName:yh,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(Gt.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===A.formCell&&i.name===v.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&&Gt.prototype.insertChild.call(t,o)}}createModelNode(t,r){switch(t.nodeName){case A.form:throw new Error("Form node shouldn't be created using this method");case A.formTab:return new On(r);case A.formColumn:return new yi(r);case A.formHeader:return new Zs(r,!1);case A.formFooter:return new Ys(r,!1);case A.formSection:return new nn(A.formSection,r);case A.formRow:return new Yi(r);case A.formCell:return new qt(r);case A.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===v.indicationOfSubgrid&&l.value==="true"||l.name===v.classid&&(l.value?.toLocaleUpperCase()===`{${_.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${_.ReferencePanelSubgridControl}}`))o=fr.Grid;else if(l.name===v.classid&&l.value?.toLocaleUpperCase()===`{${_.LookupControl}}`)o=fr.Lookup;else if(l.name===v.classid&&l.value?.toLocaleUpperCase()===`{${_.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===v.DefaultViewId&&(o=fr.Lookup)}return o===fr.Grid?new ma(r):o===fr.Lookup?new ha(r):new Pr(r);case A.formEvent:return new fa(r,M.EmptyString);case A.dependency:return this.populateDependencyTable(t),new pa(r,M.EmptyString);case A.Handler:let a=[];return new vc(a,r);case A.formNavigation:return new Ac(t.nodeName,r);case A.formNavBarArea:return new ya(t.nodeName,r);case A.formNavBarAreas:return new ba(t.nodeName,r);case A.formNavBar:return new yc(r);case A.formNavBarByRelationshipItem:return new bc(r);case A.formNavBarItem:return new wc(r);case A.formDisplayConditions:return new gc(r);case A.library:return new ga(r,M.EmptyString,M.EmptyString);case A.controlDescription:return new Lu(r);case A.customControl:return this.populateCustomControlConfigurationId(t),new ju(r);default:return new Gt(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===v.id&&this.upsertFieldCount(i.value,Zr.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===v.id){let o=new L(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===v.ForControl){let l=s.value.substr(1,i.value.length-2);je.CustomControlIdMap.upsert(l,o);break}}break}}}}});var qI={};gn(qI,{SerializationService:()=>wh,SerializationServiceScope:()=>ez,SerializedFormElementNode:()=>wa});var ez,wa,wh,VI=R(()=>{"use strict";ht();et();_r();ph();ez="SerializationService",wa=class extends H{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},wh=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=wa.prototype.fetchNodeName.call(t);if(r.charAt(0)===Pn.StartTag)return M.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return M.EmptyString;let n=wa.prototype.enumerateProperties.call(t),i=wa.prototype.enumerateChildren.call(t);if(!(t instanceof Zi)){let o=`<${r}`;if(n.length!==0&&(o+=` ${this.getPropertiesString(n)}`),i.length===0)o+=" />";else{let a=M.EmptyString;for(let s of i)a+=this.serializeFormXmlNode(s);o+=`>${a}</${r}>`}return o}return M.EmptyString}getPropertiesString(t){let r=M.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${M.EscapeXml(n.value,!0)}"`}),r}}});var Sh=b(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.completeRecordAsStored=Aa.completeLabelsAsStored=void 0;var Ah=oi(),tz="E7A81278-8635-4D9E-8D4D-59480B391C5B",rz=new Set(["tab","section","cell"]);function Rr(e){let t=[];for(let r=e.firstChild;r;r=r.nextSibling)r.nodeType===1&&t.push(r);return t}function bi(e,t){return Rr(e).find(r=>r.tagName===t)}function zI(e,t){return e.length===t.length&&e.every((r,n)=>r.tagName===t[n].tagName)}function Eh(e){let t=bi(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===tz:!1}function Ch(e,t){var r,n;let i=((r=bi(e,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"";return i!==""&&i===(((n=bi(t,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"")}function nz(e,t){if(bi(e,"labels"))return;let r=Rr(e),n=Rr(t),i=n[0];if(!i||i.tagName!=="labels"||n.length!==r.length+1||!zI(r,n.slice(1)))return;let o=Rr(i);if(!(o.length===0||o.some(s=>s.tagName!=="label"||!s.hasAttribute("description")||!s.hasAttribute("languagecode"))||!(e.tagName==="cell"&&Eh(e)&&Ch(e,t))&&o.some(s=>s.getAttribute("description")!=="")))return i}function iz(e,t){let r=oz(e.ownerDocument,t),n=Rr(e)[0];n?e.insertBefore(r,n):e.appendChild(r)}function oz(e,t){let r=e.createElement("labels");for(let n of Rr(t))r.appendChild(WI(e,n));return r}function WI(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 GI(e,t){let r=bi(e,"labels");return r?Rr(r).find(n=>n.tagName==="label"&&n.getAttribute("languagecode")===String(t)):void 0}function az(e,t,r){if(e.tagName!=="cell"||!Eh(e)||!Ch(e,t))return!1;let n=GI(e,r),i=GI(t,r),o=i?.getAttribute("description")||"";return!n||!n.hasAttribute("description")||(n.getAttribute("description")||"")!==""||o===""?!1:(n.setAttribute("description",o),!0)}function sz(e,t){if(e.tagName!=="cell"||!Eh(e)||!Ch(e,t))return;let r=bi(e,"labels"),n=bi(t,"labels");if(!r||!n)return;let i=Rr(r),o=Rr(n),a=p=>p.tagName==="label"&&p.hasAttribute("description")&&p.hasAttribute("languagecode");if(o.length<=i.length||!i.every(a)||!o.every(a))return;let s=new Map(i.map(p=>[p.getAttribute("languagecode")||"",p]));if(s.size!==i.length)return;let l=new Set,u=0,c=[],d=[];for(let p of o){let f=p.getAttribute("languagecode")||"";if(l.has(f))return;l.add(f);let m=s.get(f);if(!m){d.push(p);continue}if((m.getAttribute("description")||"")!==(p.getAttribute("description")||""))return;u+=1,c.push(...d.map(h=>({label:h,before:m}))),d=[]}return c.push(...d.map(p=>({label:p}))),u===i.length?c:void 0}function jI(e,t,r,n){if(e.tagName!==t.tagName)return;if(rz.has(e.tagName)){let a=nz(e,t);a&&(iz(e,a),n.changed=!0),az(e,t,r)&&(n.changed=!0);let s=sz(e,t),l=bi(e,"labels");if(s&&l){for(let{label:u,before:c}of s){let d=WI(e.ownerDocument,u);c?l.insertBefore(d,c):l.appendChild(d)}n.changed=!0}}let i=Rr(e),o=Rr(t);zI(i,o)&&i.forEach((a,s)=>jI(a,o[s],r,n))}function HI(e,t,r){let n,i;try{n=(0,Ah.parseXmlRoot)(e,""),i=(0,Ah.parseXmlRoot)(t,"")}catch{return e}let o={changed:!1};return jI(n,i,r,o),o.changed?(0,Ah.serializeNode)(n):e}Aa.completeLabelsAsStored=HI;function lz(e,t,r){let n=e?.formxml,i=t?.formxml;if(typeof n!="string"||typeof i!="string")return e;let o=HI(n,i,r);return o===n?e:{...e,formxml:o}}Aa.completeRecordAsStored=lz});var cT=b(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.classIdForAttributeType=Wt.QUICK_VIEW_CLASS_ID=Wt.NOTES_CLASS_ID=Wt.SUBGRID_CLASS_ID=Wt.formRegistration=Wt.FormAdapter=void 0;var xn=(ze(),$r(pA)),uz=(Be(),$r(fA)),cz=(et(),$r(hA)),tt=(te(),$r(mA)),$e=(Gi(),$r(gA)),dz=(uh(),$r(UI)),pz=(VI(),$r(qI)),He=ri(),KI=nr(),zt=Nr(),fz=mf(),Ea=lt(),mz=Sh(),vt=af(),JI=re(),Ih=ae(),Th=ii(),rT=Li(),hz={[tt.FormType.Main]:"Main",[tt.FormType.QuickCreate]:"QuickCreate",[tt.FormType.QuickViewForm]:"QuickView",[tt.FormType.Card]:"Card"},Ec={Main:tt.FormType.Main,QuickCreate:tt.FormType.QuickCreate,QuickView:tt.FormType.QuickViewForm,Card:tt.FormType.Card},gz=new Map(Object.entries($e.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function nT(e){var t;return e&&(t=gz.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function tl(e){return e.getAllProperties().map(t=>[t.key,t.value])}function to(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function iT(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function Ph(e,t){var r,n;let i=iT(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(r=o.find(s=>to(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return a&&(n=to(a).get("description"))!==null&&n!==void 0?n:""}function vz(e){let t=iT(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 oT(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function Nh(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function rl(e){return String(e??"").replace(/[{}]/g,"")}function Dh(e){return`{${rl(e)}}`}function QI(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function Sc(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,He.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:tl(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,He.rawFromNode)(u)})}),{modeled:s,bag:{a:tl(e),c:o,w:{n:a.getNodeName(),a:tl(a),c:l}}}}function aT(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,He.rawFromNode)(o)})}),{modeled:n,bag:{a:tl(e),c:i}}}function XI(e,t){let{modeled:r,bag:n}=Sc(e,"tabs","tab");return{tabs:r.map(i=>yz(i,t)),bag:n}}function yz(e,t){var r,n;let i=to(e),{modeled:o,bag:a}=Sc(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:Ph(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:o.map(s=>bz(s,t)),bag:a}}function bz(e,t){let r=to(e),{modeled:n,bag:i}=Sc(e,"sections","section");return{width:r.get("width"),sections:n.map(o=>wz(o,t)),bag:i}}function wz(e,t){var r,n,i;let o=to(e),{modeled:a,bag:s}=Sc(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:Ph(e,t),visible:o.has("visible")?o.get("visible")==="true":!0,showLabel:o.get("showlabel")==="true",columns:oT((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(l=>Az(l,t)),bag:s}}function Az(e,t){let{modeled:r,bag:n}=aT(e,"cell",!1);return{cells:r.map(i=>Ez(i,t)),bag:n}}function Ez(e,t){var r;let n=to(e),{modeled:i,bag:o}=aT(e,"control",!0),a=Ph(e,t),s=n.get("showlabel")==="true",l=i[0]?Cz(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:QI(n.get("colspan"),1),rowspan:QI(n.get("rowspan"),1),control:l,bag:o}}function Cz(e,t,r){var n,i;let o=to(e),a=rl((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:nT(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:r,parameters:vz(e),bag:{a:tl(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,He.rawFromNode)(l)}))}}}function Ei(e){return e.a.length===0&&e.c.length===0&&!e.w}function sT(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function ro(e,t){var r;let n=new Set(e.a.map(a=>a[0])),i=Ei(e),o=[];for(let a of t)if(n.has(a.key)){let s=(r=sT(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,He.mergeAttrs)(e.a,o)}var wi=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),Ai=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),YI=(e,t,r=1)=>({key:e,matches:n=>Number(n)===t,render:()=>String(t),absentDefault:String(r)});function Rh(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function _h(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>({n:(0,Ih.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${e[t]}`,a:[],c:[]}]}))}}function Sz(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 Nz(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 Oh(e,t,r){let n=e.c.findIndex(o=>o.node.n==="labels");if(n<0){if(!t||Ei(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:Rh(t,r)},...a]}}if(Sz(e.c[n].node,r)===t)return e;let i=Nz(e.c[n].node,t,r);return{...e,c:e.c.map((o,a)=>a===n?{...o,node:i}:o)}}function Dz(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 _z(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function Iz(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function Tz(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||Ei(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:_h(t)}]}}if(_z(Dz(e.c[r].node),t))return e;let n=_h(t);return{...e,c:e.c.map((i,o)=>o===r?{...i,node:n}:i)}}function Nc(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,He.spliceChildren)(e.w.c,r)};return(0,He.spliceChildren)(e.c,[a])}let i=n(),o={n:t,a:[],c:r};return e.c.length===0?[...i,o]:(0,He.spliceChildren)(e.c,[...i,o])}function Pz(e,t){let r=e.tabs.map(n=>Rz(n,t));return{n:"form",a:ro(e.bag,[]),c:e.tabs.length===0&&Ei(e.bag)?[]:Nc(e.bag,"tabs",r,()=>[])}}function lT(e,t,r){return t&&!e.c.some(n=>n.node.n==="labels")?[Rh(t,r)]:[]}function Rz(e,t){let r=[wi("id",e.id),wi("name",e.name),Ai("expanded",e.expanded),Ai("visible",e.visible,!0)],n=e.columns.map(o=>Oz(o,t)),i=Oh(e.bag,e.label,t);return{n:"tab",a:ro(i,r),c:Nc(i,"columns",n,()=>lT(i,e.label,t))}}function Oz(e,t){let r=e.width!==void 0?[wi("width",e.width)]:[],n=e.sections.map(i=>xz(i,t));return{n:"column",a:ro(e.bag,r),c:Nc(e.bag,"sections",n,()=>[])}}function xz(e,t){let r=[wi("id",e.id),wi("name",e.name),Ai("showlabel",e.showLabel),Ai("visible",e.visible,!0),{key:"columns",matches:o=>oT(o)===e.columns,render:()=>Nh(e.columns),absentDefault:Nh(1)}],n=e.rows.map(o=>Lz(o,t)),i=Oh(e.bag,e.label,t);return{n:"section",a:ro(i,r),c:Nc(i,"rows",n,()=>lT(i,e.label,t))}}function Lz(e,t){let r=e.cells.map(n=>kz(n,t));return{n:"row",a:ro(e.bag,[]),c:Ei(e.bag)?r:(0,He.assembleChildren)(e.bag,r)}}function kz(e,t){let r=e.control?e.control.showLabel:sT(e.bag,"showlabel")==="true",n=[wi("id",e.id),Ai("showlabel",r),Ai("visible",e.visible,!0),YI("colspan",e.colspan),YI("rowspan",e.rowspan)],i=e.control?[Fz(e.control)]:[],o;if(Ei(e.bag))o=[...e.control&&e.control.label?[Rh(e.control.label,t)]:[],...i];else{let a=e.control?Oh(e.bag,e.control.label,t):e.bag;o=(0,He.assembleChildren)(a,i)}return{n:"cell",a:ro(e.bag,n),c:o}}function Fz(e){let t=[wi("id",e.id),{key:"classid",matches:i=>rl(i)===e.classId,render:()=>Dh(e.classId),absentDefault:""}];e.fieldName!==null&&t.push(wi("datafieldname",e.fieldName)),t.push(Ai("disabled",e.isReadOnly)),t.push(Ai("isrequired",e.isRequired));let r=e.fieldName===null?Iz(e.bag,"datafieldname"):e.bag,n;return Ei(r)?n=Object.keys(e.parameters).length>0?[_h(e.parameters)]:[]:n=(0,He.assembleChildren)(Tz(r,e.parameters),[]),{n:"control",a:ro(r,t),c:n}}var Mz={make:(e,t)=>new cz.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function ZI(e,t,r,n){(0,Th.installDomShim)();let i=$z(e,r);(0,vt.reconcileEmbedDescriptions)(i,n);let o=(0,He.rebuildRaw)(Pz(i,t),Mz,null);return new pz.SerializationService(t).serializeFormXmlNode(o)}function Bz(e){return JSON.parse(JSON.stringify(e))}function $z(e,t){var r;let n=Bz(e);n.bag||(n.bag=(0,He.emptyBag)()),Hz(n.bag),t&&Uz(n,t);for(let i of(r=n.tabs)!==null&&r!==void 0?r:[])qz(i);return n}function Uz(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";xh(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=uT(s.attributeType)))})}function eT(e){let t=[];return xh(e,r=>t.push(r)),t}function xh(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 qz(e){e.id||(e.id=xn.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)Vz(t);e.bag||(e.bag=(0,He.emptyBag)())}function Vz(e){e.sections||(e.sections=[]);for(let t of e.sections)Gz(t);e.bag||(e.bag=(0,He.emptyBag)()),e.width===void 0&&Ei(e.bag)&&(e.width="100%")}function Gz(e){e.id||(e.id=xn.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)zz(t);e.bag||(e.bag=(0,He.emptyBag)())}function zz(e){e.cells||(e.cells=[]);for(let t of e.cells)Wz(t);e.bag||(e.bag=(0,He.emptyBag)())}function Wz(e){(0,vt.hasGenPage)(e.control)&&(0,vt.applyEmbedCellDefaults)(e),e.id||(e.id=xn.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&&jz(e.control),e.bag||(e.bag=(0,He.emptyBag)())}function jz(e){var t;(0,vt.hasGenPage)(e)&&(0,vt.applyEmbedControlDefaults)(e),e.id||(e.id=xn.Guid.NewGuid()),e.classId===void 0&&(e.classId=String($e.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":nT(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,Ih.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,He.emptyBag)())}function Hz(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"&&!tT(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",Dh(xn.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!tT(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",Dh(xn.Guid.NewGuid())])}}var Cc=class{constructor(t=rT.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,o;let{tabs:a,bag:s}=XI(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=hz[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:a,bag:s};return(0,vt.projectGenPageEmbeds)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:ZI(t,this.lcid),formid:t.id||(0,Ea.newId)(),objecttypecode:t.entityLogicalName,type:Ec[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:tt.FormPresentation.AirForm,formactivationstate:t.status==="Active"?tt.FormActivationState.Active:tt.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=this.deserialize({formxml:c,formid:(n=u.formid)!==null&&n!==void 0?n:(0,Ea.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});return Jz(this.toArtifact(d,(l=u.description)!==null&&l!==void 0?l:void 0),c)}toApiPayload(t,r,n){let i=(0,vt.genPageEmbedIssues)(t);if(i.length>0)throw new JI.ValidationError("form",t.id,i);return{formxml:ZI(t,this.lcid,n,r),name:t.name,type:Ec[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 xh(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()]}createDefault(t){var r,n,i,o,a,s,l,u,c,d,p;let f=(0,vt.genPageEmbedIssues)(t);if(f.length>0)throw new JI.ValidationError("form",t.id||"(new)",f);let m=t.tabs&&t.tabs.length>0?void 0:oW(this.lcid),h=m!==void 0?m:t.tabs.map(w=>Qz(w,this.lcid)).join(""),g=this.deserialize({formxml:`<form><tabs>${h}</tabs></form>`,formid:t.id||(0,Ea.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:Ec[(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:tt.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?tt.FormActivationState.Active:tt.FormActivationState.InActive}),y=this.toArtifact(g,t.description);if(t.tabs&&t.tabs.length>0){let w=eT(t);eT(y).forEach((C,S)=>{w[S]&&w[S].label===void 0&&delete C.label,w[S]&&w[S].genPage!==void 0&&(C.genPage=JSON.parse(JSON.stringify(w[S].genPage)))})}return{id:(l=t.id)!==null&&l!==void 0?l:y.id,name:(u=t.name)!==null&&u!==void 0?u:"New Form",entityLogicalName:(c=t.entityLogicalName)!==null&&c!==void 0?c:"",formType:(d=t.formType)!==null&&d!==void 0?d:"Main",status:(p=t.status)!==null&&p!==void 0?p:"Active",...t.description!==void 0?{description:t.description}:{},tabs:y.tabs,bag:y.bag}}assignMissingIds(t){return(0,Ea.assignMissingIds)(t)}completeAsStored(t,r){return(0,mz.completeRecordAsStored)(t,r,this.lcid)}normalize(t){return(0,vt.mintEmbedIdentity)(t)}committed(t,r){var n,i,o,a,s,l;let u=r?.formxml;if(typeof u!="string"||!(0,vt.mayCommitEmbedState)(t))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,Ea.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:Ec[(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:tt.FormPresentation.AirForm,formactivationstate:tt.FormActivationState.Active}),{bag:d}=XI(c,this.lcid),p=(0,vt.commitEmbedState)(t,(l=(0,vt.descriptionsRegion)(d))===null||l===void 0?void 0:l.node);return{artifact:p,baseline:p}}validate(t){return mW(t)}deserialize(t){(0,Th.installDomShim)();let r=uz.ScriptUtilities.ParseXml(t.formxml),n=new dz.DeserializationService(this.lcid).deSerializeFormXml(r,new xn.Guid(t.formid),t.objecttypecode,tt.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===tt.FormActivationState.InActive?"Inactive":"Active"}};Wt.FormAdapter=Cc;function Kz(e){var t;(0,Th.installDomShim)();let r=new DOMParser().parseFromString(e,"text/xml").getElementsByTagName("form")[0],n=new Set;for(let i=(t=r?.firstChild)!==null&&t!==void 0?t:null;i;i=i.nextSibling)i.nodeType===1&&(i.nodeName==="header"||i.nodeName==="footer")&&n.add(i.nodeName);return n}function Jz(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=Kz(t),i=["header","footer"].filter(a=>!n.has(a)),o=e.bag.c.filter(a=>{var s;return i.includes((s=a?.node)===null||s===void 0?void 0:s.n)}).map(a=>a.i);return o.length>0&&(e.bag.c=e.bag.c.filter(a=>{var s;return!i.includes((s=a?.node)===null||s===void 0?void 0:s.n)}).map(a=>({...a,i:a.i-o.filter(s=>s<a.i).length}))),e}function Or(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Lh(e,t){return e?`<labels><label description="${Or(e)}" languagecode="${t}" /></labels>`:""}function kh(e){return e&&e.length>0?rl(e):(0,Ea.newId)()}function Qz(e,t){var r,n,i,o;let a=(r=e.columns)!==null&&r!==void 0?r:[],s=(a.length>0?a:[iW()]).map(l=>Xz(l,t)).join("");return`<tab id="{${Or(kh(e.id))}}" name="${Or((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}">${Lh(e.label,t)}<columns>${s}</columns></tab>`}function Xz(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(o=>Yz(o,t)).join("");return`<column width="${Or((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function Yz(e,t){var r,n,i,o,a;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>Zz(l,t)).join("");return`<section id="{${Or(kh(e.id))}}" name="${Or((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="${Nh((a=e.columns)!==null&&a!==void 0?a:1)}">${Lh(e.label,t)}<rows>${s}</rows></section>`}function Zz(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>eW(n,t)).join("")}</row>`}function eW(e,t){var r,n,i,o,a;let s=tW(e),l=s.control,u=l?Lh((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?rW(l):"";return`<cell id="{${Or(kh(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 tW(e){if(!(0,vt.hasGenPage)(e.control))return e;let t={...e.control};(0,vt.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,vt.applyEmbedCellDefaults)(r),r}function rW(e){var t,r,n;let i=e.fieldName?` datafieldname="${Or(e.fieldName)}"`:"",o=nW(e.parameters),a=e.classId?rl(e.classId):String($e.ControlClassId.TextboxControl);return`<control id="${Or((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Or(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 nW(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,Ih.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Or(e[n])}</${n}>`).join("")}</parameters>`)}function iW(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function oW(e){return`<tab id="{${xn.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${xn.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 aW(e=rT.DEFAULT_LCID){return{adapter:new Cc(e),api:fz.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,KI.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,KI.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}Wt.formRegistration=aW;var sW=new Set(["id","name","label","expanded","visible","columns","bag"]),lW=new Set(["id","width","sections","bag"]),uW=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),cW=new Set(["id","cells","bag"]),dW=new Set(["id","visible","colspan","rowspan","control","bag"]),pW=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","bag"]),fW={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 mW(e){let t=[];return(0,zt.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let o=`/tabs/${i}`;(0,zt.rejectUnknownKeys)(n,sW,o,"tab",t),(0,zt.childObjects)(n,"columns",o,"column",t).forEach(({node:s,index:l})=>{let u=`${o}/columns/${l}`;(0,zt.rejectUnknownKeys)(s,lW,u,"column",t),(0,zt.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:p})=>{let f=`${u}/sections/${p}`;(0,zt.rejectUnknownKeys)(d,uW,f,"section",t),(0,zt.childObjects)(d,"rows",f,"row",t).forEach(({node:h,index:g})=>{let y=`${f}/rows/${g}`;(0,zt.rejectUnknownKeys)(h,cW,y,"row",t),(0,zt.childObjects)(h,"cells",y,"cell",t).forEach(({node:C,index:S})=>{let T=`${y}/cells/${S}`;(0,zt.rejectUnknownKeys)(C,dW,T,"cell",t,fW);let O=C.control;O!=null&&!(0,zt.isJsonObject)(O)?t.push((0,zt.issue)(`${T}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof O}`)):(0,zt.isJsonObject)(O)&&(0,zt.rejectUnknownKeys)(O,pW,`${T}/control`,"control",t)})})})})}),t.push(...(0,vt.genPageEmbedIssues)(e)),t}Wt.SUBGRID_CLASS_ID=$e.ControlClassId.SubgridControl;Wt.NOTES_CLASS_ID=$e.ControlClassId.TimelineControl;Wt.QUICK_VIEW_CLASS_ID=$e.ControlClassId.QuickViewControl;var hW={Lookup:String($e.ControlClassId.LookupControl),Customer:String($e.ControlClassId.LookupControl),Owner:String($e.ControlClassId.LookupControl),PartyList:String($e.ControlClassId.PartyListControl),Boolean:String($e.ControlClassId.BooleanControl),DateTime:String($e.ControlClassId.DateTimeControl),Decimal:String($e.ControlClassId.DecimalControl),Double:String($e.ControlClassId.FloatingNumberControl),Money:String($e.ControlClassId.CurrencyControl),Integer:String($e.ControlClassId.IntegerControl),BigInt:String($e.ControlClassId.IntegerControl),Memo:String($e.ControlClassId.TextAreaControl),String:String($e.ControlClassId.TextboxControl)},gW="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function uT(e){return e==="Picklist"||e==="State"||e==="Status"?gW:e&&hW[e]||String($e.ControlClassId.TextboxControl)}Wt.classIdForAttributeType=uT;function tT(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var Fh=b(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.viewApi=Ca.findDefaultViews=void 0;var fT=Rt(),Xt=be(),on=ae(),vW="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",yW="savedqueryid,name,returnedtypecode,querytype,isdefault",bW=60*1e3;function dT(e,t){var r,n,i;if(((r=e.canbedeleted)===null||r===void 0?void 0:r.Value)!==!1)return!1;let o=String((n=e.fetchxml)!==null&&n!==void 0?n:"");if(/<link-entity\b/i.test(o))return!1;let a=(i=o.match(/<condition\b[^>]*>/gi))!==null&&i!==void 0?i:[];return a.length===1&&/\battribute=["']statecode["']/i.test(a[0])&&/\boperator=["']eq["']/i.test(a[0])&&(t===1?/\bvalue=["']1["']/i:/\bvalue=["']0["']/i).test(a[0])}function wW(e,t){let r=String(e??"").trim().toLowerCase().split(/\s+/),n=String(t??"").trim().toLowerCase().split(/\s+/);return r.length===n.length&&r.filter((i,o)=>i!==n[o]).length===1}function AW(e){var t,r;let n=e.filter(l=>dT(l,0)),i=e.filter(l=>dT(l,1));if(n.length!==1||i.length!==1)return;let[o]=n,[a]=i;return Math.abs(Date.parse(String((t=a.createdon)!==null&&t!==void 0?t:""))-Date.parse(String((r=o.createdon)!==null&&r!==void 0?r:"")))<=bW&&wW(o.name,a.name)?a:void 0}async function EW(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,on.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,on.odataQuery)([["$select","savedqueryid,name,isdefault,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,fT.collectPages)(e,a,`findDefaultViews('${t}')`),l=c=>{var d;return/^(Active|Inactive)\b/i.test((d=c.name)!==null&&d!==void 0?d:"")},u=new Set(s.filter(c=>c.isdefault||l(c)));if(!s.some(l)){let c=AW(s);c&&u.add(c)}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:"")}})}Ca.findDefaultViews=EW;async function CW(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,on.odataPathLiteral)(t)}')${(0,on.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 pT(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await CW(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}Ca.viewApi={async get(e,t){let r=(0,on.normalizeGuid)(t,"id"),n=await(0,Xt.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,on.odataQuery)([["$select",vW]]);return{raw:(0,Xt.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},readToken(e,t){return(0,Xt.readRowEtag)(e,"savedqueries","savedqueryid",(0,on.normalizeGuid)(t,"id"))},async list(e,t){let r=`/savedqueries${(0,on.odataQuery)([["$select",yW],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,on.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,fT.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,Xt.echoWrite)("savedqueryid"),o=`/savedqueries${i.query}`,a=await pT(e,n.layoutxml,n.returnedtypecode),s=(0,Xt.ensureSuccess)(await e.post(o,(0,Xt.withClientMintedId)({name:n.name,description:n.description,fetchxml:n.fetchxml,layoutxml:a,returnedtypecode:n.returnedtypecode,querytype:n.querytype,isdefault:n.isdefault},"savedqueryid",r),i.options),e.apiUrl(o));return{id:(0,Xt.resolveCreatedId)(s,"savedqueryid","view",r),etag:(0,Xt.readEtag)(s)}},async update(e,t,r,n){let i=r,o=(0,on.normalizeGuid)(t,"id"),a=(0,Xt.echoWrite)("savedqueryid",{"If-Match":(0,Xt.requireEtag)(n,"view",o)}),s=`/savedqueries(${o})${a.query}`,l=await pT(e,i.layoutxml,i.returnedtypecode),u=(0,Xt.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,Xt.readEtag)(u)}},delete(e,t){return(0,Xt.deleteRecord)(e,"savedqueries",t)}}});var IT=b(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.viewRegistration=Sa.ViewAdapter=void 0;var wT=re(),Yt=Nr(),Mh=ri(),no=oi(),mT=nr(),SW=Fh(),Bh=ii(),NW=lt(),AT=100,_c=class{toArtifact(t){var r,n,i,o,a,s,l,u;(0,Bh.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",p=(0,no.parseXmlRoot)(c,"<fetch/>"),f=(0,no.parseXmlRoot)(d,"<grid/>"),m=CT(p);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:_W(p),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:ET(f,p),filters:NT(p),sort:ST(p),...m.length>0?{linkEntities:m}:{},fetchBag:c?(0,no.projectElementBag)(p):void 0,layoutBag:d?(0,no.projectElementBag)(f):void 0}}fromArtifact(t){(0,Bh.installDomShim)();let{fetchxml:r,layoutxml:n}=hT(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,Bh.installDomShim)();let{fetchxml:s,layoutxml:l}=hT(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,NW.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,Yt.childObjects)(n,"columns","","column",r),(0,Yt.childObjects)(n,"sort","","sort",r),(0,Yt.childObjects)(n,"linkEntities","","linkEntity",r),DW(n.linkEntities,r);let i=n.filters;return i!=null&&((0,Yt.isJsonObject)(i)?$h(i,"/filters",r):r.push((0,Yt.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};Sa.ViewAdapter=_c;function DW(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,Yt.isJsonObject)(r))return;for(let o of["name","from","to"]){let a=r[o];(typeof a!="string"||a.trim()==="")&&t.push((0,Yt.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,Yt.isJsonObject)(i)?$h(i,`/linkEntities/${n}/filters`,t):t.push((0,Yt.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function $h(e,t,r){(0,Yt.childObjects)(e,"conditions",t,"condition",r),(0,Yt.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:o})=>$h(i,`${t}/groups/${o}`,r))}function _W(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function ET(e,t){var r;let n=Uh(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)?AT:c,order:a},p=n.get(u);p&&(d.relatedEntity=p.linkKey,p.attributeName&&p.attributeName!==u&&(d.sourceAttribute=p.attributeName)),a+=1,o.push(d)}return o}function Uh(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 CT(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of yt(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=yt(n,"filter").find(c=>!Ic(c));r.push({name:i,from:o,to:a,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:qh(u)}:{}})}return r}function ST(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 NT(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=yt(t,"filter").filter(i=>!Ic(i)).map(qh);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function Ic(e){if(e.getAttribute("isquickfindfields")==="1")return!0;if(yt(e,"filter").length>0)return!1;let t=yt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||yt(r,"value").length>0||TW(r))}var IW=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function TW(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&&!IW.has(i))return!0}return!1}function qh(e){var t,r;let n=((t=e.getAttribute("type"))!==null&&t!==void 0?t:"and").toLowerCase()==="or"?"or":"and",i=[],o=[],a=e.childNodes;for(let s=0;s<a.length;s+=1){let l=a[s];if(l.nodeType===1)if(l.tagName==="condition"){if(l.getAttribute("isquickfindfields")==="1")continue;let u=l.getAttribute("attribute");if(!u)continue;let c={attribute:u,operator:(r=l.getAttribute("operator"))!==null&&r!==void 0?r:""},d=l.getAttribute("value");d!==null&&(c.value=d);let p=l.getAttribute("entityname")||"";p&&(c.entityname=p),i.push(c)}else l.tagName==="filter"&&o.push(qh(l))}return{type:n,conditions:i,groups:o}}function yt(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 Vh=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function PW(e,t){let r=Uh(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=r.get(i.name);if(o){let a=Vh(i),s=n.get(a);s?s.push(o.link):n.set(a,[o.link])}}return n}function RW(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(Vh(s));return!!l&&l.some(u=>!i.has(u))});if(a.length!==0)throw new wT.ValidationError("view",e.id,a.map(s=>(0,Yt.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 hT(e){let t=OW(e.columns);if(!gT(e.fetchBag)||!gT(e.layoutBag))return{fetchxml:zW({...e,columns:t}),layoutxml:WW({...e,columns:t},`${e.entityLogicalName}id`)};let r=new DOMParser().parseFromString("<root/>","text/xml"),n=vT(e.fetchBag,"fetch",r),i=vT(e.layoutBag,"grid",r),o=ET(i,n),a=!Dc(t,o),s=!Dc(e.sort,ST(n)),l=!Dc(e.filters,NT(n)),u=e.linkEntities,c=u!==void 0&&!Dc(u,CT(n)),d=c?PW(n,o):void 0;return c&&qW(r,n,u),c&&(GW(e,n,t,d),RW(e,n,t,d)),a?(yT(r,n,t,o),FW(r,i,t)):c&&yT(r,n,t,o),s&&$W(r,n,e.sort),l&&UW(r,n,e.filters),{fetchxml:(0,no.serializeNode)(n),layoutxml:(0,no.serializeNode)(i)}}function OW(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:AT,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function gT(e){return!!e&&(e.c.length>0||e.a.length>0)}function vT(e,t,r){let n={n:t,a:(0,Mh.mergeAttrs)(e.a,[]),c:(0,Mh.spliceChildren)(e.c,[])};return(0,Mh.rebuildRaw)(n,(0,no.domEngine)(r),null)}function yT(e,t,r,n){var i,o;let a=t.getElementsByTagName("entity")[0];if(!a)return;let s=d=>{var p,f;return`${(p=d.relatedEntity)!==null&&p!==void 0?p:""}:${d.name}:${(f=d.sourceAttribute)!==null&&f!==void 0?f:d.name}`},l=new Set(r.map(s));for(let d of n)l.has(s(d))||xW(a,d);let u=Uh(t),c=new Set(yt(a,"attribute").map(d=>d.getAttribute("name")).filter(d=>!!d));for(let d of[...r].sort((p,f)=>p.order-f.order))if(d.relatedEntity){let p=u.get(d.name);if(p&&p.attributeName===((i=d.sourceAttribute)!==null&&i!==void 0?i:d.name)&&(p.linkKey===d.relatedEntity||p.linkName===d.relatedEntity||!_T(a,d.relatedEntity)))continue;let f=LW(e,a,d.relatedEntity),m=e.createElement("attribute");DT(m,d),f.appendChild(m),u.set(d.name,{linkKey:d.relatedEntity,linkName:f.getAttribute("name")||d.relatedEntity,attributeName:(o=d.sourceAttribute)!==null&&o!==void 0?o:d.name,link:f})}else{if(c.has(d.name))continue;let p=e.createElement("attribute");p.setAttribute("name",d.name),kW(a,p),c.add(d.name)}}function DT(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 xW(e,t){if(t.relatedEntity){for(let r of yt(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of yt(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of yt(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function _T(e,t,r=!1){let n=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of yt(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 LW(e,t,r){let n=_T(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function kW(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 FW(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),o=MW(n);if(BW(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 MW(e){return yt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function BW(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 $W(e,t,r){let n=t.getElementsByTagName("entity")[0];if(!n)return;let i=(p,f)=>`${p.toLowerCase()}\0${f.toLowerCase()}`,o=new Map,a=new Map,s=(p,f,m)=>{let h=p.get(f);h?h.push(m):p.set(f,[m])};for(let p of yt(n,"order")){let f=p.getAttribute("attribute")||"";f&&(s(o,i(p.getAttribute("entityname")||"",f),p),s(a,f.toLowerCase(),p)),n.removeChild(p)}let l=new Set,u=(p,f)=>{let m=p.get(f);for(;m&&m.length>0;){let h=m.shift();if(!l.has(h))return l.add(h),h}},c=p=>{var f;let m=a.get(p.toLowerCase());if(!m)return;let h=m.filter(y=>!l.has(y)),g=(f=h.find(y=>!y.getAttribute("entityname")))!==null&&f!==void 0?f:h[0];return g&&l.add(g),g},d=r.map(p=>{let f=String(p.attribute);return p.entityname===void 0?{expression:p,element:void 0}:{expression:p,element:u(o,i(p.entityname,f))}});for(let p of d)p.expression.entityname===void 0&&(p.element=c(String(p.expression.attribute)));for(let{expression:p,element:f}of d){let m=f??e.createElement("order");m.setAttribute("attribute",p.attribute),m.setAttribute("descending",String(p.descending)),p.entityname?m.setAttribute("entityname",p.entityname):p.entityname===""&&m.removeAttribute("entityname"),n.appendChild(m)}}function UW(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of yt(n,"filter"))Ic(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(nl(e,r))}}function Dc(e,t){return JSON.stringify(e)===JSON.stringify(t)}function qW(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=yt(i,"link-entity").filter(m=>m.getAttribute("name")&&m.getAttribute("from")&&m.getAttribute("to")),a=(m,h)=>m.getAttribute(h)||"",s=new Array(r.length),l=new Set,u=m=>{r.forEach((h,g)=>{if(s[g])return;let y=o.filter(S=>!l.has(S)&&m(S,h));if(y.length!==1)return;let w=y[0];r.some((S,T)=>T!==g&&!s[T]&&m(w,S))||(s[g]=w,l.add(w))})};u((m,h)=>!!h.alias&&a(m,"name")===h.name&&a(m,"alias")===h.alias),u((m,h)=>a(m,"name")===h.name&&a(m,"from")===h.from&&a(m,"to")===h.to),u((m,h)=>a(m,"name")===h.name&&a(m,"from")===h.from),u((m,h)=>a(m,"name")===h.name&&a(m,"to")===h.to),u((m,h)=>a(m,"name")===h.name);let c=r.map((m,h)=>h).filter(m=>!s[m]),d=o.filter(m=>!l.has(m)),p=new Map;for(let m of d){let h=p.get(a(m,"name"));h?h.push(m):p.set(a(m,"name"),[m])}let f=new Map;for(let m of c){let h=f.get(r[m].name);h?h.push(m):f.set(r[m].name,[m])}for(let[m,h]of f){let g=(n=p.get(m))!==null&&n!==void 0?n:[];g.length===h.length&&h.forEach((y,w)=>{s[y]=g[w],l.add(g[w])})}r.forEach((m,h)=>{let g=s[h];if(g){bT(e,g,m);return}let y=e.createElement("link-entity");bT(e,y,m),i.appendChild(y)});for(let m of o)l.has(m)||i.removeChild(m)}var VW=new Set(["inner","outer"]);function GW(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],p=d.getAttribute("name"),f=d.getAttribute("alias");p&&o.add(p),f&&o.add(f)}let s=new Set;for(let c=0;c<a.length;c+=1)s.add(a[c]);let l=c=>{let d=n?.get(Vh(c));return!!d&&d.every(p=>s.has(p))},u=r.filter(c=>c.relatedEntity&&!o.has(c.relatedEntity)&&!l(c));if(u.length!==0)throw new wT.ValidationError("view",e.id,u.map(c=>{var d;let p=((d=e.linkEntities)!==null&&d!==void 0?d:[]).some(f=>f.name===c.relatedEntity||f.alias===c.relatedEntity);return(0,Yt.issue)(`/columns/${r.indexOf(c)}`,"view-column-dangling-link",`column '${c.name}' has relatedEntity '${c.relatedEntity}', but no matching join remains in linkEntities. `+(p?"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 bT(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):VW.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=yt(t,"filter").find(o=>!Ic(o)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?nl(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function zW(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(nl(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){DT(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(nl(r,e.filters)),new XMLSerializer().serializeToString(r)}function nl(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(nl(e,n));return r}function WW(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 jW(){return{adapter:new _c,api:SW.viewApi,publish:(e,t,r)=>(0,mT.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,mT.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}Sa.viewRegistration=jW});function Tc(e,t){return e==="SetFieldValue"&&t!==void 0&&HW.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var HW,Gh=R(()=>{"use strict";HW=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function TT(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function zh(e){return e==="AllForms"||TT(e)?1:2}function Wh(e){return TT(e)?e:null}function PT(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:Na.WorkflowCategory.BusinessRule,type:Na.WorkflowTypeCode.Definition,mode:1,scope:Na.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:zh(e.scope),processtriggerformid:Wh(e.scope)}}var Na,RT=R(()=>{"use strict";Na=de(Ti());});function OT(e,t=0){return(ct[e[t+0]]+ct[e[t+1]]+ct[e[t+2]]+ct[e[t+3]]+"-"+ct[e[t+4]]+ct[e[t+5]]+"-"+ct[e[t+6]]+ct[e[t+7]]+"-"+ct[e[t+8]]+ct[e[t+9]]+"-"+ct[e[t+10]]+ct[e[t+11]]+ct[e[t+12]]+ct[e[t+13]]+ct[e[t+14]]+ct[e[t+15]]).toLowerCase()}var ct,xT=R(()=>{ct=[];for(let e=0;e<256;++e)ct.push((e+256).toString(16).slice(1))});function jh(){return Pc>Rc.length-16&&((0,LT.randomFillSync)(Rc),Pc=0),Rc.slice(Pc,Pc+=16)}var LT,Rc,Pc,kT=R(()=>{LT=require("crypto"),Rc=new Uint8Array(256),Pc=Rc.length});var FT,Hh,MT=R(()=>{FT=require("crypto"),Hh={randomUUID:FT.randomUUID}});function KW(e,t,r){if(Hh.randomUUID&&!t&&!e)return Hh.randomUUID();e=e||{};let n=e.random??e.rng?.()??jh();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 OT(n)}var Nt,BT=R(()=>{MT();kT();xT();Nt=KW});var Kh=R(()=>{BT()});var $T=R(()=>{"use strict";});var Jh=b(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.WorkflowConditionOperator=mr.WorkflowAttributeType=mr.SystemStep=mr.FieldRequiredLevelTypes=mr.AttributeDateTimeBehavior=void 0;mr.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};mr.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};mr.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};mr.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"};mr.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 GT(e){switch(e){case"Boolean":return Ne.WorkflowAttributeType.Boolean;case"Customer":return Ne.WorkflowAttributeType.Customer;case"DateTime":return Ne.WorkflowAttributeType.DateTime;case"Decimal":return Ne.WorkflowAttributeType.Decimal;case"Double":return Ne.WorkflowAttributeType.Float;case"Integer":return Ne.WorkflowAttributeType.Integer;case"Lookup":return Ne.WorkflowAttributeType.Lookup;case"Money":return Ne.WorkflowAttributeType.Money;case"Owner":return Ne.WorkflowAttributeType.Owner;case"Picklist":return Ne.WorkflowAttributeType.Picklist;case"State":return Ne.WorkflowAttributeType.State;case"Status":return Ne.WorkflowAttributeType.Status;case"Uniqueidentifier":case"UniqueIdentifier":return Ne.WorkflowAttributeType.UniqueIdentifier;case"BigInt":return Ne.WorkflowAttributeType.BigType;default:return Ne.WorkflowAttributeType.String}}function QT(e){return e&&e!==Ne.WorkflowAttributeType.String?e:void 0}function XW(e){return{__class:JT,parameterName:"primaryEntity",entityName:e}}function UT(e){return{__class:Xh,type:Qh,typeSet:!1,behavior:Ne.AttributeDateTimeBehavior.None,method:zT,parameters:[e]}}function qT(e,t,r=Ne.WorkflowAttributeType.String){return{__class:jT,type:r,behavior:Ne.AttributeDateTimeBehavior.None,typeSet:!1,entity:XW(t),attributeName:e}}function YW(e,t=Ne.WorkflowAttributeType.String){return{__class:HT,type:t,behavior:Ne.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function ZW(e){return{__class:KT,type:Qh,typeSet:!1,behavior:Ne.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function XT(e,t){let r=JW[e.operator],n=UT(qT(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=ZW(e.right.value??"0"):e.right.kind==="field"?i=qT(e.right.field??"",t,e.right.workflowType):i=YW(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=UT(i);return{__class:Xh,type:Qh,typeSet:!1,behavior:Ne.AttributeDateTimeBehavior.None,method:WT,parameters:[r,n,o]}}function YT(e){return typeof e=="object"&&e.__class===Xh}function e7(e){return typeof e=="object"&&e.__class===KT}function Oc(e){return YT(e)&&e.method===zT&&e.parameters.length>0?Oc(e.parameters[0]):e}function VT(e){if(typeof e!="object"||e.__class!==jT)return null;let t=e.entity;if(t&&t.__class&&t.__class!==JT)return null;let r=e.attributeName;return r?{field:r,workflowType:QT(e.type)}:null}function ZT(e){if(!e)return null;let t=Oc(e);if(!YT(t)||t.method!==WT||t.parameters.length!==3)return null;let r=t.parameters[0],n=QW[String(r)];if(!n)return null;let i=VT(Oc(t.parameters[1]));if(!i)return null;let o=Oc(t.parameters[2]);if(e7(o))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=VT(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===HT){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:QT(o.type)}}}return null}function Zh(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=Yh&&r<=Da}function io(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&&!Zh(t)?"invalidDayCount":null}function _a(e){return io(e)===null}var Ne,zT,WT,Qh,jT,HT,Xh,KT,JT,JW,QW,Yh,Da,il=R(()=>{"use strict";Ne=de(Jh());zT="0",WT="3",Qh="0",jT="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",HT="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",Xh="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",KT="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",JT="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";JW={"+":0,"-":1,"*":2,"/":3},QW={0:"+",1:"-",2:"*",3:"/"};Yh=0,Da=2147483647});var e2=R(()=>{"use strict";});function Ln(e){return!t7.has(e)}function eg(e){return e==="Equals"||e==="DoesNotEqual"}function i2(e){return c7.has(e)}function xc(e){return r2.has(e)?r7:s7.has(e)?n7:n2.has(e)?i7:u7.has(e)?a7:o7}function o2(e){return xc(e)[0]}function a2(e,t){return xc(t).includes(e)}function t2(e){return r2.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":n2.has(e)?"date":l7.has(e)?"boolean":"other"}function Lc(e,t){let r=t2(e),n=t2(t);return r==="other"||n==="other"?e===t:r===n}var t7,r7,n7,i7,o7,a7,r2,s7,n2,l7,u7,c7,kc=R(()=>{"use strict";e2();t7=new Set(["ContainsData","DoesNotContainData"]);r7=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],n7=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],i7=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],o7=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],a7=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],r2=new Set(["String","Memo","EntityName"]),s7=new Set(["Integer","BigInt","Money","Decimal","Double"]),n2=new Set(["DateTime"]),l7=new Set(["Boolean"]),u7=new Set(["Lookup","Owner","Customer"]);c7=new Set(["Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith"])});function p7(e){return e.startsWith("__")&&!d7.has(e)}function f7(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{p7(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function b2(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function oo(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Fc(e){return b2(e)||oo(e)}function m7(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function ol(){return{list:[]}}function tg(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:Nt(),languageCode:r,description:t}]}}function og(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function Uc(e,t,r){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,entity:og(t),attributeName:e}}function Ta(e,t){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function v7(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?E2:A2:w2}function C2(e){return e.bpfField==="StageCategory"?G.WorkflowAttributeType.BpfStageCategory:G.WorkflowAttributeType.BpfProcess}function y7(e,t){let r=C2(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${l2}_${s2}`,entityName:s2,relatedAttributeName:l2},attributeName:g7}:Uc(h7,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,method:lg,parameters:[v7(e),n]}}function S2(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==lg)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===A2?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===E2?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===w2?{bpfField:"ProcessName"}:null}function Mc(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===lg){let r=(t.parameters??[])[0];if(typeof r=="string"&&b7.has(r.replace(/^"+|"+$/g,"")))return!0}return oo(e)?Mc(e.operand):b2(e)?Mc(e.left)||(e.right??[]).some(Mc):!1}function N2(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 w7(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 u2(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return N2(e);case"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions":return e.primitiveValue!=null;case"LookupExpression:#Microsoft.Crm.Workflow.Expressions":case"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions":return!0;default:return!1}}function A7(e){let t=sg[e.conditionOperatoroperator];if(!t)return!1;let r=t==="ContainsData"||t==="DoesNotContainData";if(oo(e))return r&&c2(e.operand,!0);let n=e.right??[];return n.length!==(r?0:1)?!1:c2(e.left,r,n[0])}function c2(e,t,r){return S2(e)||N2(e)?t||u2(r):!1}function ag(e){if(!e||!Fc(e))return!1;let t=e.conditionOperatoroperator;if(!oo(e)&&(t===G.WorkflowConditionOperator.LogicalAnd||t===G.WorkflowConditionOperator.LogicalOr)){let r=e.right??[];return r.length>0&&ag(e.left)&&r.every(ag)}return A7(e)}function d2(e){return!e||w7(e)?!1:Mc(e)||!ag(e)}function D2(e){return{__class:"LookupExpression:#Microsoft.Crm.Workflow.Expressions",type:e.workflowType??G.WorkflowAttributeType.Lookup,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,entityType:e.entityType,label:e.label??"",staticValue:Ta(e.id.replace(/[{}]/g,""),G.WorkflowAttributeType.UniqueIdentifier)}}function p2(e){return e==="ContainsData"||e==="DoesNotContainData"}function rg(e){return E7.has(e)}function f2(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:G.WorkflowAttributeType.Boolean,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function m2(e,t){let r=e.valueType==="Lookup"?e.lookupValue?.workflowType??G.WorkflowAttributeType.Lookup:e.valueWorkflowType??G.WorkflowAttributeType.String,n=e.leftWorkflowType??r,i=rg(n)&&i2(e.operator),o=ig[e.operator]??G.WorkflowConditionOperator.Equal;if(e.source==="BusinessProcess"){let l=y7(e,t);if(p2(e.operator))return f2(l,o);let u=C2(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:G.WorkflowAttributeType.Boolean,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o,left:l,right:[Ta(e.value??"",u)]}}let a=Uc(e.field,t,n);if(p2(e.operator))return f2(a,o);let s;if(e.valueType==="Field"&&e.valueField){let l=rg(n)&&rg(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:n;s=[Uc(e.valueField,t,i?G.WorkflowAttributeType.String:l)]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[D2(e.lookupValue)]}else e.valueType==="Clear"?s=[Ta(null,r)]:e.valueType==="Expression"?s=[$c(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)]:s=[Ta(e.value??"",r)];return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:G.WorkflowAttributeType.Boolean,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o,left:a,right:s}}function C7(e,t,r){if(e.length===0)return null;let n=m2(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:G.WorkflowAttributeType.Boolean,behavior:G.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?G.WorkflowConditionOperator.LogicalAnd:G.WorkflowConditionOperator.LogicalOr,left:n,right:[m2(e[i],r)]}}return n}function Bc(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")return e.primitiveValue==null?{valueType:"Clear",valueWorkflowType:e.type}:{valueType:"Value",value:e.primitiveValue!=null?String(e.primitiveValue):"",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!==G.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=ZT(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function S7(e){let t=sg[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=oo(e)?e.operand:e.left,i=oo(e)?[]:e.right??[],o=S2(n);if(o){let d=i[0];return{id:Nt(),field:"",fieldDisplayName:"",source:"BusinessProcess",bpfField:o.bpfField,...o.stageType?{stageType:o.stageType}:{},operator:t,valueType:"Value",value:d?.primitiveValue!=null&&!r?String(d.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"}:Bc(i[0]),c=u.valueWorkflowType??l;return{id:Nt(),field:s,fieldDisplayName:s,operator:t,...u,...c?{valueWorkflowType:c}:{},...l?{leftWorkflowType:l}:{}}}function h2(e){if(!e||!Fc(e))return{clauses:[],logic:"AND"};let t=[],r=(o,a)=>{let s=o.conditionOperatoroperator;if(oo(o)||s!==G.WorkflowConditionOperator.LogicalAnd&&s!==G.WorkflowConditionOperator.LogicalOr){t.push({...S7(o),...a?{connector:a}:{}});return}let l=s===G.WorkflowConditionOperator.LogicalAnd?"AND":"OR";Fc(o.left)&&r(o.left,a),(o.right??[]).filter(Fc).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 $c(e,t,r,n,i,o,a,s){if(e==="Field"&&r)return Uc(r,n,G.WorkflowAttributeType.String);if(e==="Expression"){if(i)return XT(i,n);if(o!=null)return o}return e==="Lookup"&&a?D2(a):e==="Clear"?Ta(null,s??G.WorkflowAttributeType.String):Ta(t??"",G.WorkflowAttributeType.String)}function ng(e,t){return{propertyName:e,propertyValueExpr:t}}function Ia(e){return`Step_${e.value++}`}function hr(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 g2(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):hr(t,r)}function N7(e){return e===y2.StateCode.Activated?"Active":"Draft"}function D7(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function _2(e,t=1033){return new Pa({languageCode:t}).serialize(e)}function I2(e){return new Pa().deserialize(e)}var y2,G,d7,ig,sg,lg,w2,A2,E2,h7,g7,s2,l2,b7,E7,ug,Pa,cg=R(()=>{"use strict";Kh();y2=de(Ti());$T();il();kc();G=de(Jh());d7=new Set(["__class"]);ig={Equals:G.WorkflowConditionOperator.Equal,DoesNotEqual:G.WorkflowConditionOperator.NotEqual,IsGreaterThan:G.WorkflowConditionOperator.GreaterThan,IsLessThan:G.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:G.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:G.WorkflowConditionOperator.LessThanOrEqual,Contains:G.WorkflowConditionOperator.Contains,DoesNotContain:G.WorkflowConditionOperator.DoesNotContain,BeginsWith:G.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:G.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:G.WorkflowConditionOperator.EndsWith,DoesNotEndWith:G.WorkflowConditionOperator.DoesNotEndWith,On:G.WorkflowConditionOperator.On,NotOn:G.WorkflowConditionOperator.NotOn,ContainsData:G.WorkflowConditionOperator.NotNull,DoesNotContainData:G.WorkflowConditionOperator.IsNull},sg={};for(let e of Object.keys(ig))sg[ig[e]]=e;lg="23",w2="BpfProcess",A2="ActiveStageCategory",E2="SelectedStageCategory",h7="processid",g7="stagecategory",s2="processstage",l2="stageid";b7=new Set(["ActiveStage","SelectedStage","Stage"]);E7=new Set([G.WorkflowAttributeType.Lookup,G.WorkflowAttributeType.Owner,G.WorkflowAttributeType.Customer]);ug={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"};Pa=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>ug[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??Nt(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:ol(),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:hr("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??Ia(this.stepCounter),stepLabels:{list:[]},specification:ng(t.field,$c(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:og(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),o=t??"",a=n?.stepLabels,s=tg(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:g2(n?.id,"ActionStep",this.idCounter),name:n?.name??Ia(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??Nt(),uniqueName:n?.uniqueName??`id_${Nt().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=og(this.entityName),n=t.stepName??Ia(this.stepCounter),i=t.stepLabels??ol(),o={name:n,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:hr("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:ng(t.field,$c(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:hr("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:ng(t.field,$c(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:hr("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...o,id:hr("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?G.FieldRequiredLevelTypes.Required:G.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...o,id:hr("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=tg(t.stepLabels,s,this.languageCode);return{...o,id:hr("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=tg(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:hr("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??Ia(this.stepCounter),n=hr("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??C7(o.clauses,o.logic,this.entityName),l=a?o.branchName??Ia(this.stepCounter):Ia(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?g2(o.branchId,"ConditionBranchStep",this.idCounter):hr("ConditionBranchStep",this.idCounter),name:l,description:o.displayName,stepLabels:ol(),conditionExpression:s??void 0,steps:{list:o.trueBranch.map(p=>this.serializeBranchItem(p))}};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:ol(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:hr("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:ol(),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??Nt():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:f7(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:D7(r,i?.formId),status:N7(t.statecode),rootCondition:n,wfomRoot:i}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(m7);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...o]=t,{clauses:a,logic:s}=h2(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)??Nt(),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,...d2(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=h2(n.conditionExpression);return i.length===0&&!d2(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||Nt(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...Bc(u?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Bc(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=Bc(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!==G.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}}}});function mg(e){return _7.has(e.type)}function dg(e,t,r,n,i,o,a){let s=i.get(r);!s||!R2.has(s.attributeType)||n!=="Value"||a?.operator&&!eg(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 I7(e,t){let r=t.get(e.field);return!!r&&R2.has(r.attributeType)&&eg(e.operator)}function pg(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function fg(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${Da}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:Da}}}function T2(e,t,r,n,i,o,a,s){if(i!=="Clear")return;let l=o.get(n);Tc(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 Vc(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(mg(t))return!0}else if(Vc(t))return!0;return!1}function hg(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=hg(r,t);if(n)return n}}return null}function Ra(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=Ra(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=Ra(n,t);if(i)return i}}return null}function gg(e,t){return{...e,trueBranch:P2(e.trueBranch,t),falseBranch:P2(e.falseBranch,t)}}function P2(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?gg(r,t):r)}function Ci(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?Ci(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?Ci(n,t,r):n)}}function qc(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?qc(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?qc(n,t,r):n)}}function O2(e,t,r,n){return Ci(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function vg(e){return e.length===1&&e[0].kind==="condition"}function P7(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(vg(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function R7(e){return!!e&&P7(e)<T7}function O7(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let o=[];if(vg(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 x2(e,t,r){let n=O7(e,t);return!n||!R7(n)?e:Ci(e,t,i=>L2(i,r))}function L2(e,t){if(vg(e.falseBranch))return{...e,falseBranch:[L2(e.falseBranch[0],t)]};let r=yg(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function k2(e,t){let r=Ra(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 Ci(e,r.node.id,o=>({...o,falseBranch:i}))}function F2(e,t,r){let n=Ra(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 Ci(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 yg(e){return{kind:"condition",id:Nt(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function M2(e,t){let r={kind:"action",id:Nt(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:Nt(),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 B2(e){if(!e)return[];let t=[];return $2(e,t),[...new Set(t)]}function $2(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?$2(r,t):"field"in r&&r.field&&t.push(r.field)})}function U2(e,t=[]){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition.",target:"node"}];let r=[],n=new Map(t.map(i=>[i.logicalName,i]));return q2(e,r,n),Vc(e)||r.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),r}function q2(e,t,r){let n=!!e.rawConditionExpression;e.clauses.length===0&&!n&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition.",target:"node",messageKey:"Validation.AddClause"}),e.clauses.forEach(i=>{if(n)return;if(i.source==="BusinessProcess"){i.bpfField?i.value||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:i.id}):t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a business process field for this clause.",target:"clauseField",itemId:i.id,messageKey:"Validation.SelectBusinessProcessField"});return}let o=i.valueType==="Expression"&&!i.rawExpression?io(i.expression):null;if(!i.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause.",target:"clauseField",itemId:i.id});else if(Ln(i.operator)&&i.valueType==="Value"&&!i.value&&!I7(i,r))t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:i.id});else if(Ln(i.operator)&&i.valueType==="Value"&&i.value){let a=r.get(i.field);a?.maxLength&&i.value.length>a.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${a.maxLength} characters.`,target:"clauseValue",itemId:i.id,messageParams:{maxLength:a.maxLength}})}else Ln(i.operator)&&i.valueType==="Expression"&&!i.rawExpression&&!_a(i.expression)?t.push(o==="invalidDayCount"?fg(e.id,"clauseValue",i.id):{nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause.",target:"clauseValue",itemId:i.id,messageKey:"Validation.CompleteClauseFormula"}):Ln(i.operator)&&i.valueType==="Field"&&!i.valueField&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a field to compare to for this clause.",target:"clauseValue",itemId:i.id,messageKey:"Validation.EmptyClauseCompareField"});Ln(i.operator)&&i.valueType==="Lookup"&&(pg(i.lookupValue)||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause.",target:"clauseValue",itemId:i.id,messageKey:"Validation.EmptyClauseLookupValue"})),Ln(i.operator)&&dg(e.id,"Condition",i.field,i.valueType,r,t,{operator:i.operator,target:"clauseValue",itemId:i.id})}),[...e.trueBranch,...e.falseBranch].forEach(i=>{if(i.kind==="condition")q2(i,t,r);else{if(!("field"in i)||!i.field)t.push({nodeId:i.id,kind:"EMPTY_ACTION_FIELD",message:`${i.type}: a target field is required.`,target:"actionField",messageParams:{actionType:i.type}});else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&(i.valueType??"Value")==="Value"&&!i.value?.trim())t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please provide a value.`,target:"actionValue",messageParams:{actionType:i.type}});else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Value"&&i.value){let o=r.get(i.field);o?.maxLength&&i.value.length>o.maxLength&&t.push({nodeId:i.id,kind:"ACTION_VALUE_TOO_LONG",message:`${i.type}: value exceeds the field's maximum length of ${o.maxLength} characters.`,target:"actionValue",messageParams:{actionType:i.type,maxLength:o.maxLength}})}else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Field"){if(!i.valueField)t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please select a field to copy from.`,target:"actionValue",messageKey:"Validation.SelectActionSourceField",messageParams:{actionType:i.type}});else if(r.size>0){let o=r.get(i.field),a=r.get(i.valueField);o&&a&&!Lc(o.attributeType,a.attributeType)&&t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: the source field's type is not compatible with the target field.`,target:"actionValue",messageKey:"Validation.IncompatibleActionSourceField",messageParams:{actionType:i.type}})}}else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Expression"){let o=i.rawExpression?null:io(i.expression);!i.rawExpression&&!_a(i.expression)&&t.push(o==="invalidDayCount"?fg(i.id,"actionValue"):{nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please complete the formula.`,target:"actionValue",messageKey:"Validation.CompleteActionFormula",messageParams:{actionType:i.type}})}else(i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Lookup"&&!pg(i.lookupValue)&&t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please complete the lookup record.`,target:"actionValue",messageKey:"Validation.EmptyActionLookupValue",messageParams:{actionType:i.type}});if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.field&&(dg(i.id,i.type,i.field,i.valueType,r,t,{target:"actionValue"}),T2(i.id,i.type,i.type,i.field,i.valueType,r,t,{target:"actionValue"})),i.type==="ShowErrorMessage"&&!i.errorMessage?.trim()&&t.push({nodeId:i.id,kind:"EMPTY_ACTION_MESSAGE",message:"Show error message: please enter an error message.",target:"actionMessage"}),i.type==="Recommendation"){let o=i.applyActions??[];i.recommendationTitle?.trim()||t.push({nodeId:i.id,kind:"EMPTY_RECOMMENDATION_TITLE",message:"Recommendation: please enter a recommendation title.",target:"recommendationTitle"}),i.messageText?.trim()||t.push({nodeId:i.id,kind:"EMPTY_RECOMMENDATION_MESSAGE",message:"Recommendation: please enter a recommendation message.",target:"recommendationMessage"}),o.length===0&&t.push({nodeId:i.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply.",target:"node"}),o.forEach(a=>{if(!a.field)t.push({nodeId:i.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply.",target:"applyActionField",itemId:a.id,messageKey:"Validation.RecommendationApplyField"});else if(a.valueType==="Field")a.valueField||t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplySourceField"});else if(a.valueType==="Expression"){let s=a.rawExpression?null:io(a.expression);!a.rawExpression&&!_a(a.expression)&&t.push(s==="invalidDayCount"?fg(i.id,"applyActionValue",a.id):{nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplyFormula"})}else a.valueType==="Lookup"?pg(a.lookupValue)||t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplyLookupValue"}):a.valueType==="Clear"||a.value?.trim()||t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplyValue"});a.field&&(dg(i.id,"Recommendation",a.field,a.valueType,r,t,{target:"applyActionValue",itemId:a.id}),T2(i.id,"Recommendation","SetFieldValue",a.field,a.valueType,r,t,{target:"applyActionValue",itemId:a.id}))})}}})}var _7,R2,T7,bg=R(()=>{"use strict";Kh();Gh();kc();il();_7=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);R2=new Set(["Lookup","Customer","Owner"]);T7=10});var V2={};gn(V2,{DAY_COUNT_MAX:()=>Da,DAY_COUNT_MIN:()=>Yh,DEFAULT_DESERIALIZE_LABELS:()=>ug,WorkflowJsonMapper:()=>Pa,addElseIfInTree:()=>x2,appendToBranch:()=>O2,areFieldKindsCompatible:()=>Lc,attributeTypeToWorkflowType:()=>GT,buildWorkflowEntity:()=>PT,collectUsedFields:()=>B2,createEmptyAction:()=>M2,createEmptyCondition:()=>yg,deserializeWorkflowJson:()=>I2,findNode:()=>hg,findParent:()=>Ra,getDefaultOperatorForFieldType:()=>o2,getExpressionModelIssue:()=>io,getOperatorsForFieldType:()=>xc,hasAnyTriggerGeneratingAction:()=>Vc,isDayCountValid:()=>Zh,isExpressionModelComplete:()=>_a,isOperatorCompatible:()=>a2,isTriggerGeneratingAction:()=>mg,moveBranchItemInTree:()=>F2,operatorNeedsValue:()=>Ln,processTriggerFormIdFromScope:()=>Wh,processTriggerScopeFromScope:()=>zh,removeElseIfInTree:()=>k2,removeNodeFromTree:()=>gg,serializeToWorkflowJson:()=>_2,supportsClearForActionType:()=>Tc,updateActionInTree:()=>qc,updateConditionInTree:()=>Ci,validateBusinessRule:()=>U2});var G2=R(()=>{"use strict";Gh();RT();cg();cg();bg();bg();kc();il();il();});var wg=b(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.cloneJson=void 0;function x7(e){return JSON.parse(JSON.stringify(e))}Gc.cloneJson=x7});var tP=b(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.BUSINESS_RULE_NULL_GUID=Si.businessRuleRegistration=Si.BusinessRuleAdapter=void 0;var z2=lt(),al=(G2(),$r(V2)),W2=nr(),j2=re(),L7=wg(),an=Nr(),k7=ap(),F7=lt(),M7=Li(),B7=new Set(["ShowErrorMessage","Recommendation"]);function Q2(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)?Q2(n):B7.has(String(n.type))):!1}function $7(e){return X2((0,L7.cloneJson)(e))}function X2(e){var t,r;let n=i=>(i??[]).map(o=>U7(o)?X2(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 U7(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 q7(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new j2.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 j2.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 V7="00000000-0000-0000-0000-000000000000";Si.BUSINESS_RULE_NULL_GUID=V7;var G7=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),z7=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],W7=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],j7=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function xr(e,t){return e===void 0?t:{...e,...t}}var ao=["kind","id","type","displayName","field","stepName","stepLabels"],H2=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],H7={Recommendation:[...ao,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...ao,"lock"],ShowErrorMessage:[...ao,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...ao,...H2],SetDefaultValue:[...ao,...H2],SetBusinessRequired:[...ao,"required"],SetVisibility:[...ao,"visible"]};function K(e,t){return t===void 0?{}:{[e]:t}}function Y2(e){var t;return e===void 0?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function Ag(e){return{valueType:e.valueType,...K("valueWorkflowType",e.valueWorkflowType),...K("value",e.value),...K("valueField",e.valueField),...K("lookupValue",Y2(e.lookupValue)),...K("expression",e.expression),...K("rawExpression",e.rawExpression)}}function Z2(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 K7=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function J7(e){return xr(e.bag,{id:e.id,field:e.field,...Ag(e),...K("stepName",e.stepName),...K("displayName",e.displayName)})}function Q7(e){let t=Z2(e,K7);return{id:e.id,field:e.field,valueType:e.valueType,...K("valueWorkflowType",e.valueWorkflowType),...K("value",e.value),...K("valueField",e.valueField),...K("lookupValue",e.lookupValue),...K("expression",e.expression),...K("rawExpression",e.rawExpression),...K("stepName",e.stepName),...K("displayName",e.displayName),...K("bag",t)}}function K2(e){return{valueType:e.valueType,...K("valueWorkflowType",e.valueWorkflowType),...K("value",e.value),...K("valueField",e.valueField),...K("lookupValue",e.lookupValue),...K("expression",e.expression),...K("rawExpression",e.rawExpression)}}function J2(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var X7=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),Y7=new Set,Z7="INVALID_CLEAR_FOR_FIELD";function ej(e){let t=n=>{var i;return(0,an.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,an.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 zc=class{toArtifact(t){let r=this.residualBag(t,z7),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 xr(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,al.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return Q2(t.rootCondition)}toApiPayload(t,r,n){var i,o;let a=this.fromArtifact(t);a.wfomRoot&&(a.wfomRoot={...a.wfomRoot,name:t.name,title:t.name,primaryEntityName:t.entityLogicalName||a.wfomRoot.primaryEntityName});let s=(0,al.serializeToWorkflowJson)(a,(i=n?.baseLanguageCode)!==null&&i!==void 0?i:M7.DEFAULT_LCID),l=(o=a.ruleId)!==null&&o!==void 0?o:(0,z2.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,al.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson($7(q7(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,z2.newId)()),u}assignMissingIds(t){return(0,F7.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,an.isJsonObject)(n)?(eP(n,"/rootCondition",r),r):(r.push((0,an.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,an.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=n.rootCondition===null?null:ej(n.rootCondition),o;return r.length===0?o=X7:r.some(a=>a.requiredLevel!==void 0)?o=Y7:o=new Set([Z7]),(0,al.validateBusinessRule)(i,r).filter(a=>!o.has(a.kind)).map(a=>(0,an.issue)(`/rootCondition (${a.nodeId})`,`business-rule-${a.kind}`,a.message))}issuesBlockingPush(t,r=[],n){return this.semanticIssues(t,r)}residualBag(t,r){return Z2(t,r)}buildWorkflowEntity(t,r){return(0,al.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,W7),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,j7),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,H7[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...K("stepName",t.stepName),...K("stepLabels",t.stepLabels),...K("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...K("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(Q7),...K("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...K("messageLevel",t.messageLevel),...K("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",...K2(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...K2(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return J2(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return xr(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 xr(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,...K("value",t.value),...K("valueField",t.valueField),...K("lookupValue",Y2(t.lookupValue)),...K("expression",t.expression),...K("rawExpression",t.rawExpression),...K("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!G7.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);rj(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...K("stepName",t.stepName),...K("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return xr(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...K("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(J7),...K("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return xr(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return xr(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...K("messageLevel",t.messageLevel),...K("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return xr(t.bag,{...r,type:"SetFieldValue",...Ag(t)});case"SetDefaultValue":return xr(t.bag,{...r,type:"SetDefaultValue",...Ag(t)});case"SetBusinessRequired":return xr(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return xr(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return J2(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};Si.BusinessRuleAdapter=zc;function eP(e,t,r){(0,an.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,an.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,an.childObjects)(e,n,t,"branchItem",r).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?eP(o,`${t}/${n}/${a}`,r):tj(o,`${t}/${n}/${a}`,r)})}function tj(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,an.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function rj(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function nj(){return{adapter:new zc,api:k7.businessRuleApi,publish:(e,t,r)=>(0,W2.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,W2.boundEntityPublishScope)(t)}}Si.businessRuleRegistration=nj});var yP=b(Ni=>{"use strict";Object.defineProperty(Ni,"__esModule",{value:!0});Ni.appRegistration=Ni.AppAdapter=Ni.HEADER_NAV_BOOLEAN_RULE=void 0;var kn=Nr(),rt=ri(),ll=oi(),ij=nr(),dP=Nu(),Eg=Au(),Cg=ii(),oj=lt(),aj=ae(),pP=Li(),fP=re(),mP=Cu();Object.defineProperty(Ni,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return mP.HEADER_NAV_BOOLEAN_RULE}});var Kc="7.0.0.0",rP=`<SiteMap IntroducedVersion="${Kc}"></SiteMap>`,nP="/_imgs/imagestrips/transparent_spacer.gif",iP="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",sj=["Entity","Url","DefaultDashboard","Page","GenPageId"],sl="sitemapId",oP="sitemapName",lj="sitemapNameUnique",aP="aiDescription",sP="[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}",uj=new RegExp(`^(?:\\{${sP}\\}|${sP})$`);function lP(e,t){if(!uj.test(e.trim()))throw new fP.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function uP(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new fP.ValidationError("app",t,[hP(e)]);return e}function hP(e){return(0,kn.issue)("/headerAndNavigationRefresh",mP.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function cj(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,aj.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 dj(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 Jc=class{constructor(t=pP.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=Wc(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,rt.emptyBag)()}}fromArtifact(t){(0,Cg.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,rt.rebuildRaw)(i,(0,ll.domEngine)(n),null)}fromApiResponse(t){var r,n,i,o,a,s,l,u,c,d,p;(0,Cg.installDomShim)();let f=t??{},m=(r=f.$sitemap)!==null&&r!==void 0?r:f,h=(0,ll.parseXmlRoot)((n=m.sitemapxml)!==null&&n!==void 0?n:rP,rP),g=this.toArtifact(h);return g.id=(i=f.appmoduleid)!==null&&i!==void 0?i:"",g.name=(o=f.name)!==null&&o!==void 0?o:"",g.uniqueName=(a=f.uniquename)!==null&&a!==void 0?a:"",g.description=(s=f.description)!==null&&s!==void 0?s:"",f.aiappdescription&&(g.aiDescription=f.aiappdescription),g.bag={a:[[sl,(u=(l=m.sitemapid)!==null&&l!==void 0?l:f._sitemapid_value)!==null&&u!==void 0?u:""],[oP,(c=m.sitemapname)!==null&&c!==void 0?c:""],[lj,(d=m.sitemapnameunique)!==null&&d!==void 0?d:""],[aP,(p=f.aiappdescription)!==null&&p!==void 0?p:""]],c:[]},g}toApiPayload(t,r){var n,i,o,a,s,l,u,c,d,p,f,m,h,g,y;(0,Cg.installDomShim)();let w=(0,ll.serializeNode)(this.fromArtifact(t)),C=[],S=[];for(let O of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let k of(o=O.groups)!==null&&o!==void 0?o:[])for(let F of(a=k.subAreas)!==null&&a!==void 0?a:[])F.type==="Entity"&&F.entity?C.push(F.entity):F.type==="DashBoard"&&F.dashboardId&&S.push(F.dashboardId);let T=(s=t.bag)!==null&&s!==void 0?s:(0,rt.emptyBag)();return{sitemapId:Ng(T,sl)||(t.sitemapId?lP(t.sitemapId,t.id):""),sitemapxml:w,sitemapname:Ng(T,oP)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:Ng(T,aP))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[Eg.HEADER_AND_NAVIGATION_REFRESH]:uP(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?Eg.APP_SETTING_ON:Eg.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:(p=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&p!==void 0?p:[],charts:(m=(f=t.components)===null||f===void 0?void 0:f.charts)!==null&&m!==void 0?m:[],dashboards:[...(g=(h=t.components)===null||h===void 0?void 0:h.dashboards)!==null&&g!==void 0?g:[],...S],...((y=t.components)===null||y===void 0?void 0:y.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,oj.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:lP(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:uP(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(_g):Array.isArray(r.areas)?r.areas.forEach(_g):Array.isArray(r.groups)?_g(r):Array.isArray(r.subAreas)?vP(r):"type"in r&&Qc(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,kn.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(hP(o)),i==null)return r;if(!(0,kn.isJsonObject)(i))return r.push((0,kn.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let a=(0,kn.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return a.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,kn.childObjects)(l,"groups",c,"group",r).forEach(({node:p,index:f})=>{let m=`${c}/groups/${f}`;(0,kn.childObjects)(p,"subAreas",m,"subArea",r).forEach(({node:g,index:y})=>{let w=`${m}/subAreas/${y}`;(0,kn.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],w,"subarea-type-invalid",r);let C=cj(g);if(!C)return;let S=s.get(C);if(S===void 0){s.set(C,w);return}r.push((0,kn.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,dP.mainFormSetShapeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsByTable,dj(t))}applyServerIdentity(t,r){let n=r[sl];if(!n)return;t.bag||(t.bag=(0,rt.emptyBag)());let i=t.bag.a.find(o=>o[0]===sl);i?i[1]=n:t.bag.a.push([sl,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=Wc(t,"Group"),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Sg(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}=Wc(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Sg(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:n}}subAreaToJson(t){var r;let{bag:n}=Wc(t,null),i=pj(t),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:Sg(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!==nP&&(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,rt.emptyBag)(),l=jc(a)?[["IntroducedVersion",Kc]]:[],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,rt.mergeAttrs)(a.a,l),c:(0,rt.spliceChildren)(a.c,u)}}areaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,rt.emptyBag)(),i=jc(n),o=[],a=[];t.id&&o.push(["Id",t.id]),i&&o.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",Kc]),t.icon!==void 0?o.push(["Icon",t.icon]):Hc(n.a,"Icon")&&a.push("Icon"),t.vectorIcon!==void 0?o.push(["VectorIcon",t.vectorIcon]):Hc(n.a,"VectorIcon")&&a.push("VectorIcon");let s=t.groups.map(u=>this.groupToRaw(u)),l=Dg((0,rt.spliceChildren)(n.c,s),t.title,i,this.lcid);return{n:"Area",a:(0,rt.mergeAttrs)(n.a,o,a),c:l}}groupToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,rt.emptyBag)(),i=jc(n),o=[];t.id&&o.push(["Id",t.id]),i&&o.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",Kc],["IsProfile","false"]);let a=t.subAreas.map(l=>this.subAreaToRaw(l)),s=Dg((0,rt.spliceChildren)(n.c,a),t.title,i,this.lcid);return{n:"Group",a:(0,rt.mergeAttrs)(n.a,o),c:s}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,rt.emptyBag)(),i=jc(n),o=mj(n.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]),gj(a,t),i?(a.push(["ResourceId","SitemapDesigner.NewSubArea"],["Client","All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web"],["Sku","All,OnPremise,Live,SPLA"],["AvailableOffline","true"],["PassParams","false"]),t.icon&&a.push(["Icon",t.icon])):t.icon!==void 0?a.push(["Icon",t.icon]):Hc(o,"Icon",nP)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Hc(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",iP]):s.push("VectorIcon"):t.type==="GenPage"&&!fj(o,"VectorIcon")&&a.push(["VectorIcon",iP]);let l=Dg((0,rt.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,rt.mergeAttrs)(o,a,s),c:l}}};Ni.AppAdapter=Jc;function Wc(e,t){let r=(0,ll.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,rt.rawFromNode)((0,ll.nodeLikeFromDom)(l))}),a+=1)}return{bag:{a:r,c:n},modeledEls:i}}function cP(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 Sg(e,t){var r;let n=cP(e,"Titles")[0];if(!n)return"";let o=cP(n,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(r=o.getAttribute("Title"))!==null&&r!==void 0?r:""}function pj(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function jc(e){return e.a.length===0&&e.c.length===0}function fj(e,t){return e.some(([r])=>r===t)}function Hc(e,t,r){let n=e.find(([o])=>o===t),i=n?.[1];return!!i&&i!==r}function Ng(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function mj(e,t){let r=hj(t);return e.filter(([n])=>!sj.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function hj(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 gj(e,t){var r,n,i,o,a;switch(t.type){case"Entity":e.push(["Entity",(r=t.entity)!==null&&r!==void 0?r:""]);break;case"URL":e.push(["Url",(n=t.url)!==null&&n!==void 0?n:""]);break;case"DashBoard":e.push(["DefaultDashboard",(i=t.dashboardId)!==null&&i!==void 0?i:""]),t.dashboardUrl!==void 0&&e.push(["Url",t.dashboardUrl]);break;case"CustomPage":e.push(["Page",(o=t.page)!==null&&o!==void 0?o:""]);break;case"GenPage":e.push(["GenPageId",(a=t.genPageId)!==null&&a!==void 0?a:""]);break;default:break}}function Dg(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]=vj(e[i],t,n),o}return r?[yj(t,n),...e]:e}function vj(e,t,r){let n=!1,i=e.c.map(o=>!n&&o.n==="Title"&&bj(o,"LCID")===String(r)?(n=!0,{n:o.n,a:(0,rt.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return n||i.unshift(gP(t,r)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function yj(e,t){return{n:"Titles",a:[],c:[gP(e,t)]}}function gP(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function bj(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function wj(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function Qc(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${wj(8)}`)}function _g(e){var t;Qc(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])vP(r)}function vP(e){var t;Qc(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])Qc(r,"subarea")}function Aj(e=pP.DEFAULT_LCID){return{adapter:new Jc(e),api:dP.appApi,languageSensitive:!0,publish:(t,r)=>(0,ij.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]})}}Ni.appRegistration=Aj});var bP={};gn(bP,{ActionType:()=>Tg,AppActionOrigin:()=>Mg,AppActionVisibilityType:()=>Fg,ButtonType:()=>Rg,CannotUpdateAppActionColumns:()=>Ej,Context:()=>xg,IconType:()=>Pg,Location:()=>Og,OnClickEventType:()=>kg,Scope:()=>Lg,VisibilityType:()=>Ig});var Ig,Tg,Pg,Rg,Og,xg,Lg,kg,Fg,Mg,Ej,wP=R(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(Ig||(Ig={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(Tg||(Tg={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(Pg||(Pg={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(Rg||(Rg={}));(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"})(Og||(Og={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(xg||(xg={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(Lg||(Lg={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(kg||(kg={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(Fg||(Fg={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(Mg||(Mg={}));Ej=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var SP=b(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.commandApi=void 0;var AP=Rt(),Lr=be(),CP=re(),gr=ae(),Cj="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function Xc(e,t){let r=`/EntityDefinitions(LogicalName='${(0,gr.odataPathLiteral)(t)}')${(0,gr.odataQuery)([["$select","MetadataId"]])}`,i=(0,Lr.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,o=i?.MetadataId;return o?(0,gr.normalizeGuid)(o,"entityMetadataId"):""}Yc.commandApi={async get(e,t){let r=t,n=await Xc(e,r),i=n?`_contextentity_value eq ${n}`:`contextvalue eq '${(0,gr.odataLiteral)(r)}'`,o=`/appactions${(0,gr.odataQuery)([["$expand",Cj],["$filter",i]])}`,a,s=await(0,AP.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 p=c["@odata.etag"];u[(0,gr.normalizeGuid)(d,"appactionid")]=typeof p=="string"?p:null}}return{raw:l,etag:a?(0,Lr.readEtag)(a):null,memberEtags:u}},async list(e,t){let r=t?.entityLogicalName;return r?[{type:"command",id:r,name:`${r} commands`,entityLogicalName:r,isDirty:!1}]:[]},async create(e,t){let r=t,n=r.entityMetadataId||await Xc(e,r.entityLogicalName);return EP(e,{...r,entityMetadataId:n},!1)},async update(e,t,r,n,i){let o=r,a=o.entityMetadataId||await Xc(e,o.entityLogicalName);return EP(e,{...o,entityMetadataId:a},!0,i)},async delete(e,t){let r=await Xc(e,t),n=r?`_contextentity_value eq ${r}`:`contextvalue eq '${(0,gr.odataLiteral)(t)}'`,i=`/appactions${(0,gr.odataQuery)([["$select","appactionid"],["$filter",n]])}`,o=await(0,AP.collectPages)(e,i,"deleteArtifact('command')");for(let a of o)a.appactionid&&await(0,Lr.deleteRecord)(e,"appactions",a.appactionid)}};async function EP(e,t,r,n){let i=t.entityMetadataId?(0,gr.normalizeGuid)(t.entityMetadataId,"entityMetadataId"):"",o=Nj(t.rows),a={};try{await Sj(e,t,o,i,r,n,a)}catch(s){throw(0,CP.withPartialTokens)(s,{memberEtags:a})}return{id:t.entityLogicalName,etag:null,memberEtags:a}}async function Sj(e,t,r,n,i,o,a){var s,l,u;for(let c of r)if(i&&c.exists){let d=(0,gr.normalizeGuid)(c.appactionid,"id"),p=(s=o?.[d])!==null&&s!==void 0?s:c.etag,f=(0,Lr.echoWrite)("appactionid",p?{"If-Match":p}:void 0),m=`/appactions(${d})${f.query}`,h=(0,Lr.ensureSuccess)(await e.patch(m,c.body,f.options),e.apiUrl(m));a[d]=(0,Lr.readEtag)(h)}else{let d=(0,Lr.echoWrite)("appactionid"),p=`/appactions${d.query}`,f={...c.body};if(f["[email protected]"]===void 0){if(!n)throw new CP.SdkError("COMMAND_CONTEXT_ENTITY_UNRESOLVED",`Cannot create app action '${c.appactionid}' for entity '${t.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.`);f["[email protected]"]=`/entities(${n})`}let m=(0,Lr.ensureSuccess)(await e.post(p,f,d.options),e.apiUrl(p)),h=(0,Lr.readCreatedId)(m,"appactionid");h&&(a[(0,gr.normalizeGuid)(h,"appactionid")]=(0,Lr.readEtag)(m))}for(let c of[...(l=t.deletedRowIds)!==null&&l!==void 0?l:[]].reverse()){let d=(0,gr.normalizeGuid)(c,"id");await(0,Lr.deleteRecord)(e,"appactions",d,(u=o?.[d])!==null&&u!==void 0?u:void 0),delete a[d]}}function Nj(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 MP=b(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.commandRegistration=Oa.CommandAdapter=void 0;var Ue=(wP(),$r(bP)),NP=nr(),vr=Nr(),Dj=SP(),_j=lt(),xa=ae(),Ug="$ClientSvg:",qg=".svg",Ij=2,Tj=1,Pj=1,IP="entityMetadataId",Rj=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"]),Zc=class{toArtifact(t){var r,n,i,o,a,s;let l=(r=t.appActions)!==null&&r!==void 0?r:[],u=(n=t.entityLogicalName)!==null&&n!==void 0?n:"",c=new Map;for(let f of l){let m=typeof f._parentappactionid_value=="string"&&f._parentappactionid_value?f._parentappactionid_value:"",h=(i=c.get(m))!==null&&i!==void 0?i:[];h.push(f),c.set(m,h)}let d=new Map;for(let f of(o=c.get(""))!==null&&o!==void 0?o:[]){let m=Fj(f.location),h=(a=d.get(m))!==null&&a!==void 0?a:[];h.push(f),d.set(m,h)}let p=[];for(let[f,m]of d)p.push({location:f,groups:xj(m,c,xP(f),u)});return{id:u,entityLogicalName:u,commandBars:kj(p),bag:{a:[[IP,(s=t.entityMetadataId)!==null&&s!==void 0?s:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:Gg(t),appActions:Bg(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?Bg(r).map(l=>l.appactionid):[]),i=Bg(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?Kj(l.row):FP(l.row)}}),s=[...n].filter(l=>!o.has(l));return{entityLogicalName:t.entityLogicalName,entityMetadataId:Gg(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,_j.assignMissingIds)(t)}validate(t){let r=[];return(0,vr.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,vr.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",r),(0,vr.childObjects)(i,"groups",a,"group",r).forEach(({node:l,index:u})=>{let c=`${a}/groups/${u}`;TP(l.bag)||((0,vr.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."})),PP((0,vr.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};Oa.CommandAdapter=Zc;function TP(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function PP(e,t,r){e.forEach(({node:n,index:i})=>{let o=`${t}/${i}`;TP(n.bag)||(0,vr.optionalGuidId)(n,"id",o,"control-id-invalid",r),(0,vr.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,vr.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,vr.isJsonObject)(n.action)?(0,vr.optionalEnum)(n.action,"type",["javascript"],`${o}/action`,"action-type-invalid",r):r.push((0,vr.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,vr.childObjects)(n,"children",o,"control",r);s.length>0&&PP(s,`${o}/children`,r)})}function Vg(e){return{a:Object.entries(e)}}function Oj(e){return Object.fromEntries(e.a)}function ed(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function Gg(e){let t=ed(e.bag,IP);return typeof t=="string"?t:""}function xj(e,t,r,n){var i,o;let a=[],s=[];for(let l of rd(e))l.type===Ue.ButtonType.Group?a.push({id:OP(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:rd((o=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(u=>td(u,t,r,n)),bag:Vg(l)}):s.push(td(l,t,r,n));return s.length>0&&a.unshift({id:Hj(n,r),title:"",controls:s}),a}function zg(e){let t=e.bag?ed(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function td(e,t,r,n){var i,o,a,s,l;let u=OP(e.name,n),c={id:u,type:Mj(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:Vg(e)},d=RP(e);d&&(c.icon=d);let p=Lj(e);p&&(c.action=p),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 f=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(f&&f.length>0){let m=[],h=[];for(let g of rd(f))if(g.type===Ue.ButtonType.Group){let y=(o=g.appactionid)!==null&&o!==void 0?o:"",w=Vg(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 rd((l=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let T=td(S,t,r,n);m.push(T),C.push(zg(T))}h.push({id:y,bag:w,childIds:C})}else m.push(td(g,t,r,n));c.children=m,h.length>1&&(c.flyoutGroups=h)}return c}function RP(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(Ug)?e.fonticon.slice(Ug.length)+qg:e.fonticon}function Lj(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 DP(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function rd(e){return[...e].sort((t,r)=>DP(t)-DP(r))}function kj(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 OP(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 Fj(e){switch(e){case Ue.Location.Form:case Ue.Location.QuickForm:return"MainTab";case Ue.Location.HomePageGrid:case Ue.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function xP(e){switch(e){case"MainTab":return Ue.Location.Form;case"HomeTab":return Ue.Location.HomePageGrid;default:return Ue.Location.SubGridStandard}}function Mj(e){switch(e){case Ue.ButtonType.Dropdown:return"FlyoutAnchor";case Ue.ButtonType.Split:return"SplitButton";default:return"Button"}}function Bj(e){switch(e){case"FlyoutAnchor":return Ue.ButtonType.Dropdown;case"SplitButton":return Ue.ButtonType.Split;default:return Ue.ButtonType.Standard}}function $j(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function LP(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 Bg(e,t=new Set){var r,n,i,o;let a=[],s=Gg(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=xP(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(f=>{var m;return(m=f.controls)!==null&&m!==void 0?m:[]}),d=c.length>0&&c.every(f=>!LP(f,t)),p=0;for(let f of(i=l.groups)!==null&&i!==void 0?i:[]){let m;if($j(f)){let h=qj(f,u,void 0,e,s);a.push(h),m=h.appactionid}for(let h of(o=f.controls)!==null&&o!==void 0?o:[])kP(h,u,m,e,s,a,d?p:void 0,t),p+=1}}return a}function kP(e,t,r,n,i,o,a,s=new Set){var l;let u=Uj(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=>!LP(h,s)),p=(h,g,y)=>{kP(h,t,g,n,i,o,d?y:void 0,s)},f=e.flyoutGroups;if(f&&f.length>0){let h=new Map(c.map(S=>[zg(S),S])),g=new Set,y=0,w;for(let[S,T]of f.entries()){let O=T.id||(S===0?$g(u.appactionid):jg("flyout-group",`${u.appactionid}#${S}`)),k=_P(O,t,u.appactionid,n,i,T.bag);o.push(k);let F=k.appactionid;w===void 0&&(w=F);for(let P of T.childIds){let q=h.get(P);!q||g.has(P)||(g.add(P),p(q,F,y),y+=1)}}let C=w??$g(u.appactionid);for(let S of c){let T=zg(S);g.has(T)||(g.add(T),p(S,C,y),y+=1)}return}let m=e.flyoutGroupId||$g(u.appactionid);o.push(_P(m,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,g]of c.entries())p(g,m,h)}function Uj(e,t,r,n,i,o){let a=Wg(e,t,r,n,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let l=RP(s);return e.location!==void 0&&(s.location=e.location),s.type=Bj(e.type),s.buttonlabeltext=e.label,Gj(s,e.icon,l),Wj(s,e.action),zj(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function qj(e,t,r,n,i){let o=Wg(e,t,r,n,i);return o.row.type=Ue.ButtonType.Group,o.row.grouptitle=e.title,o}function _P(e,t,r,n,i,o){let a=Wg({id:e,bag:o},t,r,n,i),s=a.row;return s["[email protected]"]=`/appactions(${(0,xa.normalizeGuid)(r,"Command flyout group id")})`,s.type=Ue.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),a}function Wg(e,t,r,n,i){let o,a,s,l;if(e.bag&&e.bag.a.length>0){o=Oj(e.bag),a=!0;let u=ed(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=ed(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else l=e.id,o=Vj(l,t,n,i),a=!1,s=null;return r?o["[email protected]"]=`/appactions(${(0,xa.normalizeGuid)(r,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==Ue.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:l,exists:a,etag:s,row:o}}function Vj(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:Ue.Context.Entity,contextvalue:r.entityLogicalName,scope:Ue.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,xa.normalizeGuid)(n,"Command context entity metadata id")})`),i}function Gj(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,xa.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(qg)?Ug+t.slice(0,t.length-qg.length):t,e.IconWebResourceId=null}function zj(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,xa.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===Tj&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===Pj)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function Wj(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=Ij,t.webResourceId){let r=(0,xa.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 jj(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 jg(e,t){let r="";for(let n=0;n<4;n+=1)r+=jj(`${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 $g(e){return jg("flyout-group",e)}function Hj(e,t){return jg("loose-group",`${e}|${t}`)}function FP(e){let t={...e};for(let r of Rj)delete t[r];return t}function Kj(e){let t=FP(e);for(let r of Ue.CannotUpdateAppActionColumns)delete t[r];return t}function Jj(){return{adapter:new Zc,api:Dj.commandApi,publish:(e,t,r)=>(0,NP.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,NP.boundEntityPublishScope)(t)}}Oa.commandRegistration=Jj});var BP=b(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});nd.chartApi=void 0;var Qj=Rt(),Zt=be(),La=ae(),Xj="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",Yj="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";nd.chartApi={async get(e,t){let r=(0,La.normalizeGuid)(t,"id"),n=await(0,Zt.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,La.odataQuery)([["$select",Xj]]);return{raw:(0,Zt.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},readToken(e,t){return(0,Zt.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",(0,La.normalizeGuid)(t,"id"))},async list(e,t){let r=`/savedqueryvisualizations${(0,La.odataQuery)([["$select",Yj],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,La.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,Qj.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,Zt.echoWrite)("savedqueryvisualizationid"),o=`/savedqueryvisualizations${i.query}`,a=(0,Zt.ensureSuccess)(await e.post(o,(0,Zt.withClientMintedId)({name:n.name,description:n.description,datadescription:n.datadescription,presentationdescription:n.presentationdescription,primaryentitytypecode:n.primaryentitytypecode,charttype:n.charttype,isdefault:n.isdefault},"savedqueryvisualizationid",r),i.options),e.apiUrl(o));return{id:(0,Zt.resolveCreatedId)(a,"savedqueryvisualizationid","chart",r),etag:(0,Zt.readEtag)(a)}},async update(e,t,r,n){let i=r,o=(0,La.normalizeGuid)(t,"id"),a=(0,Zt.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,Zt.requireEtag)(n,"chart",o)}),s=`/savedqueryvisualizations(${o})${a.query}`,l=(0,Zt.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,Zt.readEtag)(l)}},delete(e,t){return(0,Zt.deleteRecord)(e,"savedqueryvisualizations",t)}}});var rR=b(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});Fa.chartRegistration=Fa.ChartAdapter=void 0;var Hg=ri(),$P=Nr(),sn=oi(),UP=nr(),Zj=BP(),Kg=ii(),eH=lt(),tH=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],rH=new Map(tH.map(e=>[e.toLowerCase(),e]));function WP(e){var t;return e&&(t=rH.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function nH(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function iH(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="${ka(h.series.attribute)}" aggregate="${ka(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${ka(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${ka(h.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(h,g)=>{if(!h){l.push(g);return}let y=u.get(h);y?y.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="${ka(h)}">${g.join("")}</link-entity>`).join(""),p=l.join("")+d,f=i.map(h=>`<measurecollection><measure alias="${h.alias}" /></measurecollection>`).join(""),m=(r=(t=o[0])===null||t===void 0?void 0:t.alias)!==null&&r!==void 0?r:"";return`<datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="${ka(n)}">${p}</entity></fetch></fetchcollection><categorycollection><category alias="${m}">${f}</category></categorycollection></datadefinition>`}var id=class{toArtifact(t){var r,n,i,o,a,s,l;(0,Kg.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,sn.parseXmlRoot)(u,"<datadefinition/>"),p=(0,sn.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:jP(p),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:JP(d),categories:QP(d),presentation:HP(p),dataBag:u?(0,sn.projectElementBag)(d):void 0,presentationBag:c?(0,sn.projectElementBag)(p):void 0,rowBag:oH(t.charttype,t.type)}}fromArtifact(t){(0,Kg.installDomShim)();let{datadescription:r,presentationdescription:n}=aH(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:qP(t.rowBag,"charttype"),type:qP(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,Kg.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,eH.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,$P.childObjects)(n,"series","","series",r),(0,$P.childObjects)(n,"categories","","category",r),r}};Fa.ChartAdapter=id;function oH(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 qP(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 jP(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return WP(t[r].getAttribute("ChartType"));return"Column"}function HP(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 od(e){return e.getElementsByTagName("fetch")[0]}function KP(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 JP(e){let t=od(e);if(!t)return[];let r=KP(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=WP(c));let d=a.getAttribute("alias");d&&(u.alias=d);let p=d??l,f=r.get(p);f&&(u.relatedEntity=f),i.push(u)}return i}function QP(e){var t;let r=od(e);if(!r)return[];let n=KP(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 p=d??l,f=n.get(p);f&&(u.relatedEntity=f),o.push(u)}return o}function aH(e){if(!VP(e.dataBag)||!VP(e.presentationBag)){let o=iH(e);return{datadescription:o,presentationdescription:NH(e,o)}}let t=new DOMParser().parseFromString("<root/>","text/xml"),r=GP(e.dataBag,"datadefinition",t),n=GP(e.presentationBag,"Chart",t),i=JP(r);if(!Jg(e.series,i)){let o=Qg(r);sH(t,r,e.series);let a=Qg(r),s=a.length>0?a:e.series.map(()=>"");XP(t,n,s,o,e.chartType)}return Jg(e.categories,QP(r))||lH(t,r,e.categories),e.chartType!==jP(n)&&eR(n,e.chartType),Jg(e.presentation,HP(n))||tR(n,e.presentation),{datadescription:(0,sn.serializeNode)(r),presentationdescription:(0,sn.serializeNode)(n)}}function VP(e){return!!e&&(e.c.length>0||e.a.length>0)}function XP(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,p)=>{let f=s[p];if(!f)return;let m=u.get(d);m?m.push(f):u.set(d,[f])});let c=r.map(d=>{let p=u.get(d),f=p&&p.length>0?p.shift():void 0;if(f)return f;let m=e.createElement("Series");m.setAttribute("ChartType",i);let h=s.length>0?s[0].getAttribute("ChartArea"):null;return h&&m.setAttribute("ChartArea",h),m});for(let d of s)o.removeChild(d);for(let d of c)o.appendChild(d)}function Qg(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 GP(e,t,r){let n={n:t,a:(0,Hg.mergeAttrs)(e.a,[]),c:(0,Hg.spliceChildren)(e.c,[])};return(0,Hg.rebuildRaw)(n,(0,sn.domEngine)(r),null)}function sH(e,t,r){let n=od(t),i=n?.getElementsByTagName("entity")[0];!n||!i||YP(e,t,i,hH(n),r,vH,{aliasPrefix:"aggregate_column",addRef:dH,removeRef:mH})}function lH(e,t,r){let n=od(t),i=n?.getElementsByTagName("entity")[0];!n||!i||YP(e,t,i,gH(n),r,yH,{aliasPrefix:"groupby_column",addRef:pH,removeRef:fH})}function YP(e,t,r,n,i,o,a){let s=new Map;for(let f of n){let m=f.getAttribute("alias");m&&s.set(m,f)}let l=new Set,u=[],c=(f,m)=>{var h;let g=bH(r,f),y=m.relatedEntity;(g??void 0)!==(y??void 0)&&((h=f.parentNode)===null||h===void 0||h.removeChild(f),zP(e,r,f,y))};for(let f of i){let m=f.alias?s.get(f.alias):void 0;m&&!l.has(m)?(o(m,f),c(m,f),l.add(m)):u.push(f)}let d=n.filter(f=>!l.has(f)),p=0;for(let f of u)if(p<d.length){let m=d[p];o(m,f),c(m,f),l.add(m),p+=1}else{let m=e.createElement("attribute"),h=f.alias||cH(t,a.aliasPrefix);m.setAttribute("alias",h),o(m,f),zP(e,r,m,f.relatedEntity),a.addRef(e,t,h)}for(let f of n)if(!l.has(f)){let m=f.getAttribute("alias");m&&a.removeRef(t,m),AH(f)}}function uH(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 cH(e,t){let r=uH(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function ZP(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function dH(e,t,r){let n=ZP(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 pH(e,t,r){let n=ZP(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function fH(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 mH(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"&&!CH(a)&&((r=a.parentNode)===null||r===void 0||r.removeChild(a))}}function hH(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 gH(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 vH(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function yH(e,t){e.setAttribute("name",t.attribute),e.setAttribute("groupby","true"),t.dateGrouping?e.setAttribute("dategrouping",t.dateGrouping):e.getAttribute("dategrouping")!==null&&e.removeAttribute("dategrouping")}function bH(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 zP(e,t,r,n){n?wH(e,t,n).appendChild(r):t.appendChild(r)}function wH(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 AH(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!EH(t))){let r=t.parentNode;r&&r.removeChild(t)}}function EH(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 CH(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function eR(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(!SH(r[i])){r[i].setAttribute("ChartType",t);return}}}function SH(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 tR(e,t){var r;let n=e.ownerDocument;if(t.palette!==void 0&&e.setAttribute("Palette",t.palette),t.showLegend!==void 0){let i=[],o=e.getElementsByTagName("Legends");for(let a=0;a<o.length;a+=1)i.push(o[a]);if(t.showLegend&&i.length===0){let a=n.createElement("Legends"),s=n.createElement("Legend");s.setAttribute("Name","Default"),a.appendChild(s),e.appendChild(a)}else if(!t.showLegend)for(let a of i)(r=a.parentNode)===null||r===void 0||r.removeChild(a)}if(t.title!==void 0){let i=e.getElementsByTagName("Title")[0];i&&(i.textContent=t.title)}}function NH(e,t){let r=(0,sn.parseXmlRoot)(nH(),"<Chart/>");eR(r,e.chartType),tR(r,e.presentation);let n=Qg((0,sn.parseXmlRoot)(t,"<datadefinition/>"));return n.length>0&&XP(r.ownerDocument,r,n,n.slice(0,1),e.chartType),(0,sn.serializeNode)(r)}function Jg(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ka(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function DH(){return{adapter:new id,api:Zj.chartApi,publish:(e,t,r)=>(0,UP.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,UP.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}Fa.chartRegistration=DH});var aR=b(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.dashboardApi=Ba.dashboardEntity=void 0;var _H=Rt(),Di=be(),Ma=ae(),nR=cf();function iR(e){return e&&e.toLowerCase()!=="none"?e:void 0}Ba.dashboardEntity=iR;var oR="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",IH={select:oR,required:["name","type","objecttypecode","istabletenabled"]},TH="formid,name,type,objecttypecode",PH=0,RH=10;Ba.dashboardApi={async get(e,t){let n=`/systemforms(${(0,Ma.normalizeGuid)(t,"id")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Ma.odataQuery)([["$select",oR]]),i=(0,Di.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Di.readEtag)(i)}},async list(e,t){let r=[`(type eq ${PH} or type eq ${RH})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,Ma.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,Ma.odataQuery)([["$select",TH],["$filter",r.join(" and ")]])}`;return(await(0,_H.collectPages)(e,n,"listArtifacts('dashboard')")).map(o=>{var a,s;let l=iR(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,Di.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,Di.ensureSuccess)(await e.post(o,(0,Di.withClientMintedId)(a,"formid",r),i.options),e.apiUrl(o));return{id:(0,Di.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Di.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,nR.patchSystemForm)(e,(0,Ma.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,IH)},readToken(e,t){return(0,nR.readSystemFormContentEtag)(e,(0,Ma.normalizeGuid)(t,"id"))},delete(e,t){return(0,Di.deleteRecord)(e,"systemforms",t)}}});var bR=b(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.dashboardRegistration=ln.TILE_CLASS_ID=ln.DashboardAdapter=void 0;var cl=ri(),yr=oi(),Xg=nr(),ul=Nr(),pR=aR(),Yg=ii(),so=lt(),fR=ae(),mR=Li(),OH=Sh(),sR="0",Zg="10",xH=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"]]),LH="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",sd=class{constructor(t=mR.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,o,a;(0,Yg.installDomShim)();let s=(r=t.formxml)!==null&&r!==void 0?r:"",l=(0,yr.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:kH(t.type),entityLogicalName:(a=(0,pR.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:FH(l),components:lR(l,this.lcid),bag:(0,yr.projectElementBag)(l)}}fromArtifact(t){var r;return(0,Yg.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?Zg:sR,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:uR(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}completeAsStored(t,r){return(0,OH.completeRecordAsStored)(t,r,this.lcid)}toApiPayload(t){return{name:t.name,description:t.description,formxml:uR(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?Zg:sR,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,o,a,s,l,u;(0,Yg.installDomShim)();let c=(0,yr.parseXmlRoot)(JH(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,so.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:lR(c,this.lcid),bag:(0,yr.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,so.newId)())}return t}validate(t){let r=[],n=(0,ul.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,ul.isJsonObject)(u)&&r.push((0,ul.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,ul.isJsonObject)(o.position)){let l=dl(o.position);i.has(l)?r.push((0,ul.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};ln.DashboardAdapter=sd;function kH(e){return String(e??"")===Zg?"Interactive":"Standard"}function FH(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),r=parseInt(t??"",10);return Number.isNaN(r)?0:r}function ee(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 lR(e,t){let r=[];return ee(e,"tabs").flatMap(i=>ee(i,"tab")).forEach((i,o)=>{ee(i,"columns").flatMap(s=>ee(s,"column")).forEach((s,l)=>{ee(s,"sections").flatMap(c=>ee(c,"section")).forEach((c,d)=>{MH(c,{tabIndex:o,columnIndex:l,sectionIndex:d},r,t)})})}),r}function MH(e,t,r,n){ee(e,"rows").flatMap(o=>ee(o,"row")).forEach((o,a)=>{ee(o,"cell").forEach((s,l)=>{let u=BH(s,{...t,rowIndex:a,cellIndex:l},n);u&&r.push(u)})})}function BH(e,t,r){var n,i;let o=vR((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(o.toLowerCase().startsWith("spacer"))return null;let a=ee(e,"control")[0];if(!a)return null;let s=(i=a.getAttribute("classid"))!==null&&i!==void 0?i:"",l=qH(a),u=VH(s,l,a),c=$H(a);return{id:a.getAttribute("id")||o,type:u,name:gR(e,r),classId:s,position:t,colspan:e0(e,"colspan",1),rowspan:e0(e,"rowspan",1),parameters:l,bag:(0,yr.projectElementBag)(e),...c?{icProperties:c}:{}}}function hR(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 $H(e){let t=hR(e);return t?(0,yr.serializeNode)(t):void 0}function UH(e,t,r){let n=hR(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,o=(0,cl.rebuildRaw)((0,cl.rawFromNode)((0,yr.nodeLikeFromDom)(i)),(0,yr.domEngine)(e),null);n&&(0,yr.serializeNode)(n)===(0,yr.serializeNode)(o)||(n?t.replaceChild(o,n):t.appendChild(o))}function gR(e,t){var r,n;let i=ee(e,"labels")[0];if(!i)return"";let o=ee(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 qH(e){var t;let r={},n=ee(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 VH(e,t,r){var n;let i=xH.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"&&((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===LH?"assistant":i:"unknown"}function e0(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 vR(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function GH(e,t){let r={n:"form",a:(0,cl.mergeAttrs)(e.bag.a,[]),c:(0,cl.spliceChildren)(e.bag.c,[])};return(0,cl.rebuildRaw)(r,(0,yr.domEngine)(t),null)}function uR(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=GH(e,r);return jH(r,n,e.components,t),zH(r,n,e.components,t),(0,yr.serializeNode)(n)}function zH(e,t,r,n){let i=yR(t);for(let o of r)i.has(dl(o.position))||WH(e,t,o,n)}function WH(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=QH(t,e,l);for(let q of ee(u,"row"))ee(q,"cell").some(V=>ee(V,"control").length>0)||u.removeChild(q);let c=r.classId||ln.TILE_CLASS_ID[r.type]||ln.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,p=r.bag&&cR(r.bag,"id")?String(cR(r.bag,"id")):ad((0,so.newId)()),f=r.id?ad(r.id):ad((0,so.newId)()),m=u.parentNode,h=Math.max(1,parseInt(m&&m.getAttribute&&m.getAttribute("columns")||"1",10)||1),g=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),h),y=ee(u,"row"),w=y[y.length-1],C=w?ee(w,"cell").reduce((q,V)=>q+e0(V,"colspan",1),0):0;(!w||C+g>h)&&(w=e.createElement("row"),u.appendChild(w));let S=e.createElement("cell");S.setAttribute("id",p),S.setAttribute("colspan",String(g)),S.setAttribute("rowspan",String(d)),S.setAttribute("showlabel","true");let T=e.createElement("labels"),O=e.createElement("label");O.setAttribute("description",(a=r.name)!==null&&a!==void 0?a:""),O.setAttribute("languagecode",String(n)),T.appendChild(O),S.appendChild(T);let k=e.createElement("control");k.setAttribute("id",f),k.setAttribute("classid",ad(c));let F=e.createElement("parameters"),P=(s=r.parameters)!==null&&s!==void 0?s:{};for(let q of Object.keys(P)){let V=(0,fR.createSafeXmlElement)(e,q,"dashboard tile parameter");V.textContent=P[q],F.appendChild(V)}k.appendChild(F),S.appendChild(k),w.appendChild(S)}function cR(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function jH(e,t,r,n){var i;let o=yR(t),a=new Set(r.map(s=>dl(s.position)));for(let s of r){let l=o.get(dl(s.position));if(!l)continue;let u=ee(l,"control")[0];u&&(HH(e,l,s.name,n),KH(e,u,s.parameters),dR(l,"colspan",s.colspan),dR(l,"rowspan",s.rowspan),s.icProperties!==void 0&&UH(e,u,s.icProperties))}for(let[s,l]of o)a.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function yR(e){let t=new Map;return ee(e,"tabs").flatMap(n=>ee(n,"tab")).forEach((n,i)=>{ee(n,"columns").flatMap(a=>ee(a,"column")).forEach((a,s)=>{ee(a,"sections").flatMap(u=>ee(u,"section")).forEach((u,c)=>{ee(u,"rows").flatMap(p=>ee(p,"row")).forEach((p,f)=>{ee(p,"cell").forEach((m,h)=>{var g;vR((g=m.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||ee(m,"control")[0]&&t.set(dl({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:f,cellIndex:h}),m)})})})})}),t}function dl(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function HH(e,t,r,n){if(r===gR(t,n))return;let i=ee(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let o=ee(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 KH(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let o=ee(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,fR.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,o.appendChild(d)}}}function dR(e,t,r){var n;((n=e.getAttribute(t))!==null&&n!==void 0?n:"")!==String(r)&&e.setAttribute(t,String(r))}function JH(e=2){let t=`{${(0,so.newId)()}}`,r=`{${(0,so.newId)()}}`,n=`{${(0,so.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>`}ln.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 ad(e){return`{${e.replace(/[{}]/g,"")}}`}function QH(e,t,r){var n;let i=ee(e,"tabs").flatMap(u=>ee(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let o=ee(i,"columns").flatMap(u=>ee(u,"column"))[0];if(!o)throw new Error("addDashboardTile: dashboard formxml has no <column>");let a=ee(o,"sections").flatMap(u=>ee(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=ee(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function XH(e=mR.DEFAULT_LCID){return{adapter:new sd(e),api:pR.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,Xg.publishBoundEntity)(t,n):(0,Xg.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,Xg.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}ln.dashboardRegistration=XH});var LR=b(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});cd.genPageApi=void 0;var ud=Rt(),TR=ql(),_e=be(),se=ae(),kr=bu(),ke=re(),PR=lt();function YH(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 un="uxagentprojects",uo="uxagentprojectfiles",ml="agentconversationmessages",hl="uxagentprojectid",Dt="uxagentprojectfileid",co="agentconversationmessageid",pl=`${hl},name`,ZH=`${Dt},filename,filetype`,RR=2e8,OR=200000001,po={"MSCRM.IncludeUnpublished":"true"},t0={};function lo(e,t){return{"MSCRM.VersioningChangeset":e,...po,...t}}async function n0(e,t,r,n){var i;let o=`/${t}(${r})`+(0,se.odataQuery)([["$select",n]]),a=(0,_e.ensureSuccess)(await e.get(o,{headers:{...po}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,_e.readEtag)(a)}}async function ld(e,t,r=po){let n=`/${uo}(${t})/filecontent/$value`,i=await e.get(n,{headers:{...r}});if(i.status===404)return{status:"unavailable",reason:"missing"};(0,_e.ensureSuccess)(i,e.apiUrl(n));let o=i.body,a=YH(o);if(a)return{status:"available",data:(0,kr.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,kr.utf8ToBase64)(o)};throw new ke.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 xR(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function eK(e,t,r,n,i,o){if(!e.supportsBinaryPatch)throw new ke.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=`/${uo}(${t})/filecontent`,s=(0,kr.base64ToBytes)(n);(0,se.assertNoControlChars)(r,"generative-page file name"),(0,_e.ensureSuccess)(await e.patchRaw(a,s,{headers:lo(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":xR(r),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function fl(e,t,r=po){let n=`/${uo}`+(0,se.odataQuery)([["$select",ZH],["$filter",`_${hl}_value eq ${t}`]]);return(await(0,ud.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 r0(e,t){let r=`/${ml}`+(0,se.odataQuery)([["$select",`${co},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,ud.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{...po}})}async function wR(e,t){var r,n,i;let{row:o,etag:a}=await n0(e,un,t,pl),s=new Map;for(let{row:l,etag:u}of await fl(e,t))s.set((0,se.normalizeGuid)(String((r=l[Dt])!==null&&r!==void 0?r:""),Dt),{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 AR(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,se.normalizeGuid)(c.id,"file id");u.add(d);let p=r?.rows.get(d);if(c.content.status==="retain"){if(!r)throw new ke.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(!p)throw new ke.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}p&&c.unchanged||(p?(p.filename!==c.name||p.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:p!==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 o0(e){let t=(0,kr.base64ToUtf8)(e);return(0,kr.utf8ToBase64)(t)===(0,kr.bytesToBase64)((0,kr.base64ToBytes)(e))?t:void 0}function tK(e,t,r,n){var i,o,a,s,l,u,c,d;let p=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?{[co]:(0,se.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${un}(${e})`,message:t.message,messagecontext:JSON.stringify(p),messagesender:t.sender==="user"?RR:OR}}async function rK(e,t,r){var n,i,o,a;let s=((n=r.messages)!==null&&n!==void 0?n:[]).map(p=>p.id).filter(p=>typeof p=="string"&&p!=="").map(p=>(0,se.normalizeGuid)(p,"message id"));if(s.length===0)return r;let l=`/${ml}`+(0,se.odataQuery)([["$select",`${co},message,messagesender,_regardingobjectid_value`],["$filter",s.map(p=>`${co} eq ${p}`).join(" or ")]]),u=await(0,ud.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{...po}});if(u.length===0)return r;let c=new Map(u.map(p=>{var f;return[String((f=p[co])!==null&&f!==void 0?f:"").toLowerCase(),p]})),d=[];for(let p of(i=r.messages)!==null&&i!==void 0?i:[]){let f=p.id?c.get((0,se.normalizeGuid)(p.id,"message id")):void 0;if(!f){d.push(p);continue}if(!(String((o=f.message)!==null&&o!==void 0?o:"")===p.message&&Number(f.messagesender)===(p.sender==="user"?RR:OR)&&String((a=f._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new ke.SdkError("GENPAGE_TURN_CONFLICT",`Refusing to push generative page '${t}': its pending turn's identity is already recorded \u2014 as a DIFFERENT ${p.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 i0(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${un}`,body:(0,_e.withClientMintedId)({name:t.name},hl,e),headers:lo(n)};case"createRow":return{method:"POST",path:`/${uo}`,body:(0,_e.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${hl}@odata.bind`]:`/${un}(${e})`},Dt,(0,se.normalizeGuid)(t.file.id,"file id")),headers:lo(n)};case"renameRow":return{method:"PATCH",path:`/${uo}(${(0,se.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:lo(n,{"If-Match":"*"})};case"content":{let i=o0(t.data);if(i===void 0)throw new ke.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,se.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${uo}(${(0,se.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:lo(n,{"x-ms-file-name":xR(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${uo}(${t.fileId})`,headers:lo(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${un}(${e})`,body:{name:t.name},headers:lo(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${ml}`,body:tK(e,t.turn,r,n)};default:{let i=t;throw new ke.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function ER(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||o0(r.data)!==void 0)}async function CR(e,t,r,n,i){await(0,TR.postChangeSet)(e,r.map(o=>i0(t,o,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function SR(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 eK(e,(0,se.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=i0(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,_e.ensureSuccess)(c,e.apiUrl(l.path))}if(a.length===0)return{warnings:[],turnRecorded:!0};try{let s=a.map(l=>i0(t,l,n,i));if(e.supportsAtomicBatch)await(0,TR.postChangeSet)(e,s,`the conversation turn of generative page '${t}'`);else for(let l of s)(0,_e.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 NR(e,t,r,n,i,o,a){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...a,u]});try{let u=await wR(e,t),c=new Map;for(let C of r)(C.kind==="createRow"||C.kind==="renameRow"||C.kind==="content")&&c.set((0,se.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 T=u.rows.get(C);T&&(T.filename!==S.name||T.filetype!==S.fileType)&&d.push(`file '${S.name}' is stored as '${T.filename}' (type ${T.filetype})`)}for(let C of r){if(C.kind!=="content")continue;let S=await ld(e,(0,se.normalizeGuid)(C.file.id,"file id")),T=(0,kr.bytesToBase64)((0,kr.base64ToBytes)(C.data));(S.status!=="available"||S.data!==T)&&d.push(S.status==="available"?`file '${C.file.name}' holds ${(0,kr.base64ToBytes)(S.data).byteLength} byte(s) that differ from the ${(0,kr.base64ToBytes)(T).byteLength} written`:`file '${C.file.name}' holds no content`)}let p=new Set(r.filter(C=>C.kind==="content").map(C=>(0,se.normalizeGuid)(C.file.id,"file id")));for(let[C,S]of c)!p.has(C)&&(await ld(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 f=await wR(e,t),m=[...f.rows.keys()],h=f.etag!==u.etag||f.rows.size!==u.rows.size||m.some(C=>{var S,T;return((S=u.rows.get(C))===null||S===void 0?void 0:S.etag)!==((T=f.rows.get(C))===null||T===void 0?void 0:T.etag)}),g=m.length!==i.size||m.some(C=>!i.has(C)),y={},w=[];for(let[C,S]of f.rows){let T=c.has(C)||!o?S.etag:(s=o.get(C))!==null&&s!==void 0?s:null;y[C]=T,T!==S.etag&&w.push(S.filename)}return h||g||!f.etag||Object.values(y).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.`):nK({id:t,etag:f.etag,memberEtags:y},[...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.`)}}cd.genPageApi={async get(e,t){var r;let n=(0,se.normalizeGuid)(t,"id"),{row:i,etag:o}=await n0(e,un,n,pl),a=await fl(e,n),s={},l=[];for(let{row:c,etag:d}of a){let p=(0,se.normalizeGuid)(String((r=c[Dt])!==null&&r!==void 0?r:""),Dt);s[p]=d;let f=await ld(e,p);l.push({...c,content:f})}let u=await r0(e,n);return{raw:{project:i,files:l,conversation:u},etag:o,memberEtags:s}},async getPublished(e,t){var r,n;let i=(0,se.normalizeGuid)(t,"id"),o=`/${un}(${i})`+(0,se.odataQuery)([["$select",pl]]),a=await e.get(o);if(a.status===404)return null;(0,_e.ensureSuccess)(a,e.apiUrl(o));let s=(r=a.body)!==null&&r!==void 0?r:{},l={},u=[],c=await fl(e,i,t0);for(let{row:g,etag:y}of c){let w=(0,se.normalizeGuid)(String((n=g[Dt])!==null&&n!==void 0?n:""),Dt);l[w]=y,u.push({...g,content:await ld(e,w,t0)})}let d=g=>g.map(({row:y,etag:w})=>`${String(y[Dt])}@${String(w)}`).sort().join("|"),p=()=>new ke.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.`),f=await e.get(o);if(f.status===404)throw p();(0,_e.ensureSuccess)(f,e.apiUrl(o));let m=await fl(e,i,t0);if([(0,_e.readEtag)(a),(0,_e.readEtag)(f),...[...c,...m].map(g=>g.etag)].some(g=>!g))throw new ke.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,_e.readEtag)(f)!==(0,_e.readEtag)(a)||d(m)!==d(c))throw p();return{raw:{project:s,files:u,conversation:[]},etag:(0,_e.readEtag)(a),memberEtags:l}},async list(e,t){let r=`/${un}`+(0,se.odataQuery)([["$select",pl]]);return(await(0,ud.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{...po}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[hl])!==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;IR(e,i);let o=r?(0,se.normalizeGuid)(r,"id"):(0,PR.newId)();_R(e,o,i);let a=AR(o,i,void 0),s=DR(),l=[],u=!0;ER(e,a)?await CR(e,o,a,i,s):{warnings:l,turnRecorded:u}=await SR(e,o,a,i,s);let c=new Set(((n=i.files)!==null&&n!==void 0?n:[]).map(p=>(0,se.normalizeGuid)(p.id,"file id"))),d=await NR(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,se.normalizeGuid)(t,"id");IR(e,s);let u=await rK(e,l,s);_R(e,l,u);let c=await fl(e,l),{row:d,etag:p}=await n0(e,un,l,pl);if(n&&p&&n!==p)throw new ke.SdkError(_e.VERSION_CONFLICT_CODE,`Generative page '${l}' changed on the server after it was fetched (baseline ${n}, server ${p}) \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||!p)throw new ke.SdkError(_e.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 f=new Map(c.map(({row:k})=>{var F,P;return[(0,se.normalizeGuid)(String((F=k[Dt])!==null&&F!==void 0?F:""),Dt),{filename:String((P=k.filename)!==null&&P!==void 0?P:""),filetype:Number(k.filetype)}]})),m=new Set(f.keys()),h=new Set(((o=u.files)!==null&&o!==void 0?o:[]).map(k=>(0,se.normalizeGuid)(k.id,"file id")));if(!i)throw new ke.SdkError(_e.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(k=>k.toLowerCase()));for(let k of h)if(!m.has(k)&&g.has(k))throw new ke.SdkError(_e.VERSION_CONFLICT_CODE,`Generative-page file '${k}' 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 k of m)if(!g.has(k))throw new ke.SdkError(_e.VERSION_CONFLICT_CODE,`Generative-page file '${k}' 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 y=new Map(c.map(({row:k,etag:F})=>{var P;return[(0,se.normalizeGuid)(String((P=k[Dt])!==null&&P!==void 0?P:""),Dt),F]}));for(let[k,F]of Object.entries(i)){let P=k.toLowerCase();if(!m.has(P))continue;let q=y.get(P);if(!F||!q)throw new ke.SdkError(_e.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${P}' before writing: ${F?"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(F!==q)throw new ke.SdkError(_e.VERSION_CONFLICT_CODE,`Generative-page file '${P}' changed on the server after this page was fetched (baseline ${F}, server ${q}) \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=AR(l,u,{rows:f,name:String((a=d.name)!==null&&a!==void 0?a:"")});if(w.length===0)return{id:l,etag:p,memberEtags:Object.fromEntries(c.map(({row:k,etag:F})=>{var P;return[(0,se.normalizeGuid)(String((P=k[Dt])!==null&&P!==void 0?P:""),Dt),F]}))};let C=DR(),S=[],T=!0;ER(e,w)?await CR(e,l,w,u,C):{warnings:S,turnRecorded:T}=await SR(e,l,w,u,C);let O=await NR(e,l,w,u,h,y,S);return T?O:{...O,intentPending:!0}},async delete(e,t){var r;let n=(0,se.normalizeGuid)(t,"id"),i=await r0(e,n);await(0,_e.deleteRecord)(e,un,n);let o=new Set(i.map(l=>{var u;return String((u=l[co])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),a=!1;try{for(let l of await r0(e,n)){let u=String((r=l[co])!==null&&r!==void 0?r:"");u!==""&&o.add(u)}}catch{a=!0}let s=[];for(let l of o)try{await(0,_e.deleteRecord)(e,ml,l)}catch(u){u instanceof ke.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||a)throw new ke.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 ${ml} rows regarding '${n}'.`)}};function DR(){return`uxagentproject_${(0,PR.newId)()}`}function nK(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function _R(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 ke.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 IR(e,t){var r,n;if(((r=t.files)!==null&&r!==void 0?r:[]).some(a=>a.content.status==="available"&&!a.unchanged)&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new ke.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient implements neither patchRaw() nor postRaw(). A Dataverse File column is not writable through a JSON body, so proceeding would create the page and its rows and then fail, leaving a page whose source never uploaded.");if(((n=t.files)!==null&&n!==void 0?n:[]).some(a=>a.content.status==="available"&&!a.unchanged&&o0(a.content.data)===void 0)&&!e.supportsBinaryPatch)throw new ke.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 QR=b(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.genPageRegistration=Ua.GenPageAdapter=void 0;var iK=LR(),oK=nr(),he=Nr(),gd=lt(),vd=bu(),fo=re(),kR=bf(),a0=Ep(),_i=2e8,jR=200000001,Mn={source:{name:"src/pages/page.tsx",fileType:_i},output:{name:"src/pages/page.compiled",fileType:jR},config:{name:"config.json",fileType:_i},prompt:{name:"firstPrompt.json",fileType:_i}},HR=Object.keys(Mn),aK=["dataSources","model","connectorBindings","actionBindings"],sK=["userMessage","agentMessage"],FR=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,lK={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},uK="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function KR(e,t){var r;let n=e.replace(/[{}-]/g,"").toLowerCase(),i=[];for(let a=0;a<32;a+=1)i.push(parseInt((r=n[a])!==null&&r!==void 0?r:"0",16)^parseInt(t[a],16));i[12]=4,i[16]=i[16]&3|8;let o=i.map(a=>(Number.isNaN(a)?0:a).toString(16)).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function dd(e,t){return KR(e,lK[t])}function cK(e,t){let r=KR(e,uK),n=parseInt(r.slice(24),16)%2**47+(t==="agent"?1:0);return`${r.slice(0,24)}${n.toString(16).padStart(12,"0")}`}function MR(e){return typeof e=="string"&&e.trim()!==""?e:(0,gd.newId)()}function Fn(e){return(0,he.isJsonObject)(e)?e:{}}function $a(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function pd(e){return JSON.parse(JSON.stringify(e))}function dK(e){let t=Fn(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function fd(e){if(!e||e.status!=="available")return;let t=(0,vd.base64ToUtf8)(e.data);return(0,vd.utf8ToBase64)(t)===e.data?t:void 0}function md(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,he.isJsonObject)(t)?t:void 0}catch{return}}function BR(e,t){if(t===_i&&e.includes("page.tsx"))return"source";if(t===jR&&e.includes(".compiled"))return"output";if(t===_i&&e===Mn.config.name)return"config";if(t===_i&&e===Mn.prompt.name)return"prompt"}function $R(e){let t=e.toLowerCase();return HR.some(r=>Mn[r].name.toLowerCase()===t)}function s0(e){return Object.fromEntries(e)}function JR(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),s0(i)}function UR(e){var t,r,n;return JR({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},aK,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function qR(e){var t,r;return JR({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},sK,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function VR(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=s0(n)),!0}function GR(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=s0(n)),!0}function vl(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 pK=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function zR(e){return vl(e)?[]:pK.filter(t=>e[t]!==void 0).map(t=>(0,he.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 WR(){return(0,he.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 hd(e){return{status:"available",data:(0,vd.utf8ToBase64)(e)}}function gl(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 yd=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=Fn(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(g=>{var y,w,C;let S=Fn(g);return{id:String((y=S.uxagentprojectfileid)!==null&&y!==void 0?y:""),name:String((w=S.filename)!==null&&w!==void 0?w:""),fileType:Number((C=S.filetype)!==null&&C!==void 0?C:_i),content:dK(S.content)}}),o=Array.isArray(r?.conversation)?r.conversation.map(g=>{var y,w;let C=Fn(g);return{sender:Number(C.messagesender)===200000001?"agent":"user",message:String((y=C.message)!==null&&y!==void 0?y:""),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 y=BR(g.name,g.fileType);y?((s.has(y)||g.name!==Mn[y].name)&&(u=!1),s.set(y,g)):($R(g.name)&&(u=!1),l.push(g))}if(!u||s.size===0)return a(gl(n,i));let c=gl(n,l),d={rows:{}};for(let[g,y]of s)d.rows[g]=y.id;let p=s.get("source");if(p){let g=fd(p.content);if(g===void 0)return a(gl(n,i));c.source=g}let f=s.get("output");f&&(d.output=f.content);let m=s.get("config");if(m){let g=md(fd(m.content));if(!g||!VR(c,d,g))return a(gl(n,i))}let h=s.get("prompt");if(h){let g=md(fd(h.content));if(!g||!GR(c,d,g))return a(gl(n,i))}return c.bag=d,a(c)}async toApiPayload(t,r,n){var i,o,a,s,l,u,c,d,p,f,m,h,g,y,w;if(r&&!$a((i=t.conversation)!==null&&i!==void 0?i:[],(o=r.conversation)!==null&&o!==void 0?o:[]))throw new fo.ValidationError("genPage",t.id,[(0,he.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 C=zR(t);if(C.length>0)throw new fo.ValidationError("genPage",t.id,C);let S=[],T=r===void 0,O=T&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(vl(O)){let P=(s=(a=O.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},q=Z=>{var ye;return(ye=P[Z])!==null&&ye!==void 0?ye:dd(O.id,Z)},V=(Z,ye,hn)=>{S.push({id:q(Z),name:Mn[Z].name,fileType:Mn[Z].fileType,content:ye,unchanged:hn})};if(O.source!==void 0){V("source",hd(O.source),!T&&r?.source===O.source&&P.source!==void 0);let Z=!T&&r?.source===O.source&&$a((l=r?.dataSources)!==null&&l!==void 0?l:[],(u=O.dataSources)!==null&&u!==void 0?u:[]),ye=fd((c=O.bag)===null||c===void 0?void 0:c.output);Z&&P.output!==void 0&&(0,kR.isLoadableGenPageOutput)(ye)?V("output",{status:"retain"},!0):V("output",hd(await this.compile(O,O.source,n)),!1)}else{if(P.source!==void 0)throw new fo.ValidationError("genPage",O.id,[WR()]);if(P.output!==void 0){if(!T&&!$a((d=r?.dataSources)!==null&&d!==void 0?d:[],(p=O.dataSources)!==null&&p!==void 0?p:[]))throw new fo.ValidationError("genPage",O.id,[(0,he.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.")]);V("output",{status:"retain"},!0)}}let Ve=UR(O),Pt=!T&&r!==void 0&&$a(UR(r),Ve);(T||P.config!==void 0||!Pt)&&V("config",hd(JSON.stringify(Ve)),Pt&&P.config!==void 0);let Je=qR(O),Ge=!T&&r!==void 0&&$a(qR(r),Je);(P.prompt!==void 0||Object.keys(Je).length>0&&!Ge)&&V("prompt",hd(JSON.stringify(Je)),Ge&&P.prompt!==void 0)}for(let P of(f=O.files)!==null&&f!==void 0?f:[]){let q=(m=r?.files)===null||m===void 0?void 0:m.find(V=>V.id===P.id);S.push({id:P.id,name:P.name,fileType:P.fileType,content:P.content,unchanged:q!==void 0&&$a(q,P)})}let k=[];if(O.newTurn){let P=O.newTurn.id,q=V=>P?{id:cK(P,V)}:{};k.push({...q("user"),sender:"user",message:O.newTurn.prompt}),O.newTurn.agentMessage&&k.push({...q("agent"),sender:"agent",message:O.newTurn.agentMessage})}let F=(g=(h=O.bag)===null||h===void 0?void 0:h.config)!==null&&g!==void 0?g:{};return{name:O.name,files:S,...k.length>0?{messages:k,messageContext:{dataSources:(y=O.dataSources)!==null&&y!==void 0?y:[],model:(w=O.model)!==null&&w!==void 0?w:"",enabledTools:Array.isArray(F.enabledTools)?F.enabledTools:[],configurableTools:Array.isArray(F.configurableTools)?F.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:pd(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,o,a,s,l;if(!vl(t)&&!t.newTurn)return t;let u=pd(t);if(delete u.newTurn,!vl(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 p=HR.find(m=>Mn[m].name===d.name&&Mn[m].fileType===d.fileType);if(!p||u.files.some(m=>m.id===d.id)||(c.rows[p]=d.id,d.content.status!=="available"))continue;let f=(0,vd.base64ToUtf8)(d.content.data);p==="output"?c.output={status:"available",data:d.content.data}:p==="config"?(delete c.config,delete u.dataSources,delete u.model,delete u.connectorBindings,delete u.actionBindings,VR(u,c,(s=md(f))!==null&&s!==void 0?s:{})):p==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,GR(u,c,(l=md(f))!==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,he.isJsonObject)(r)||typeof r.id=="string"&&FR.test(r.id)?t:{...t,newTurn:{...r,id:(0,gd.newId)()}}}async compile(t,r,n){var i;let o=(i=t.dataSources)!==null&&i!==void 0?i:[],a=[],s=[];if(o.forEach((p,f)=>{var m;let h=(m=n?.resolveEntity)===null||m===void 0?void 0:m.call(n,p);h&&h.columnDetailComplete===!0?a.push(h):s.push((0,he.issue)(`/dataSources/${f}`,h?"genpage-data-source-incomplete":"genpage-data-source-unresolved",h?`the column metadata of data source '${p}' could not be read completely (a choice or lookup request failed), so the page cannot be compiled with its enums. Retry the push.`:`the metadata of data source '${p}' could not be read, so the page cannot be compiled with its enums. Check the table's logical name and that it exists in this environment.`))}),s.length>0)throw new fo.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new fo.ValidationError("genPage",t.id,[(0,he.issue)("/source","genpage-compiler-unavailable","no TypeScript compiler is available to compile the page")]);let l=await n.loadTypeScript(),u=a.length>0?(0,a0.buildGenPageRuntimeTypes)(a):void 0,c=a.length>0?(0,a0.buildGenPageLegacyEnums)(a):void 0,d=(0,kR.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new fo.ValidationError("genPage",t.id,d.diagnostics.map(fK));return d.code}metadataNeeds(t){return t.source===void 0||!Array.isArray(t.dataSources)?[]:t.dataSources.filter(r=>typeof r=="string"&&r!=="").map(r=>({entityLogicalName:r,fieldName:"",needsColumnDetail:!0}))}createDefault(t){var r,n;let i=MR(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:MR(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=a.fileType)!==null&&l!==void 0?l:_i,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=pd(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=pd(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:dd(i,"source"),output:dd(i,"output"),config:dd(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,gd.newId)()};if(!(0,he.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,gd.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,he.issue)(`/${s}`,"genpage-field-type",`${s} must be a string, got ${typeof n[s]}`));if(n.source===void 0&&Fn(Fn(n.bag).rows).source!==void 0&&r.push(WR()),r.push(...zR(t)),n.newTurn!==void 0){let s=Fn(n.newTurn);(!(0,he.isJsonObject)(n.newTurn)||typeof s.prompt!="string"||s.prompt.trim()==="")&&r.push((0,he.issue)("/newTurn/prompt","genpage-turn-prompt","newTurn needs a non-empty prompt")),s.agentMessage!==void 0&&typeof s.agentMessage!="string"&&r.push((0,he.issue)("/newTurn/agentMessage","genpage-field-type","newTurn.agentMessage must be a string")),s.id!==void 0&&(typeof s.id!="string"||!FR.test(s.id))&&r.push((0,he.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,he.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"||!a0.TABLE_LOGICAL_NAME.test(l)?r.push((0,he.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,he.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,he.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,he.issue)("/files","files-must-be-array",`files must be an array, got ${typeof i}`)),r;let o=vl(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=Fn(s),d=typeof c.id=="string"?c.id.trim().toLowerCase():"";if(d==="")r.push((0,he.issue)(u,"file-id-required","a generative-page file needs an id"));else{let g=a.get(d);g!==void 0?r.push((0,he.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 p=typeof c.name=="string"?c.name:"",f=p.split("/");p===""||/[\u0000-\u001F\u007F]/.test(p)||p.includes("\\")||f.some(g=>g===""||g==="."||g==="..")?r.push((0,he.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 '${p}'`)):o&&($R(p)||BR(p,Number(c.fileType))!==void 0)&&r.push((0,he.issue)(u+"/name","file-name-reserved",`'${p}' would be read by the maker portal as one of the page's managed rows (its source, output, config or first prompt), which the SDK writes from source and the configuration fields; it cannot also be a file in files[]`));let m=c.content;if(m===void 0){r.push((0,he.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=Fn(m);h.status==="available"?typeof h.data!="string"&&r.push((0,he.issue)(u+"/content/data","file-content-data-invalid","available content needs base64 `data`")):h.status!=="unavailable"&&r.push((0,he.issue)(u+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(h.status)}`))}),r}};Ua.GenPageAdapter=yd;function fK(e){let t=`line ${e.line}, column ${e.column}`;return e.rule==="genpage-source-syntax"?(0,he.issue)("/source",e.rule,`${t}: ${e.message} (TS${e.code}) \u2014 the page cannot run, so it was not pushed`):(0,he.issue)("/source",e.rule,`${t}: ${e.message}`)}function mK(){return{adapter:new yd,api:iK.genPageApi,publish:(e,t)=>(0,oK.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}Ua.genPageRegistration=mK});var YR=b(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});Ad.reconcileBpfSecurityRoles=void 0;var wd=be(),bd=ae(),hK="Global",XR={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function gK(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,bd.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,a=(n=(r=(0,wd.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[],s={},l=new Set;return Object.keys(XR).forEach(u=>{let c=a.find(d=>d.PrivilegeType===XR[u]);if(c){let d=(0,bd.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function vK(e,t){var r,n;let i=`/RetrieveRolePrivilegesRole(RoleId=${t})`,a=(n=(r=(0,wd.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.RolePrivileges)!==null&&n!==void 0?n:[];return new Set(a.map(s=>(0,bd.normalizeGuid)(s.PrivilegeId,"PrivilegeId")))}async function yK(e,t,r){if(r.length===0)return;let n={Privileges:r.map(o=>({Depth:hK,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,wd.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function bK(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,wd.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function wK(e,t,r){var n;if(!r||r.length===0)return;let i=await gK(e,t.toLowerCase());for(let o of r){let a=(0,bd.normalizeGuid)(o.roleId,"roleId"),s=new Set(((n=o.access)!==null&&n!==void 0?n:[]).map(p=>i.byAccess[p]).filter(p=>!!p)),l=await vK(e,a),u=new Set([...l].filter(p=>i.all.has(p))),c=[...s].filter(p=>!u.has(p)),d=[...u].filter(p=>!s.has(p));await yK(e,a,c);for(let p of d)await bK(e,a,p)}}Ad.reconcileBpfSecurityRoles=wK});var sO=b(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});Nd.bpfApi=void 0;var br=Ti(),AK=Rt(),wr=re(),_t=be(),Bn=ae(),EK=YR(),CK={"Content-Type":"application/json",Accept:"application/json"},Ed={...CK,Prefer:"return=representation"},SK=new Set([408,502,503,504]),NK=`category eq ${br.WorkflowCategory.BusinessProcessFlow} and type eq ${br.WorkflowTypeCode.Definition} and businessprocesstype eq ${br.BusinessProcessType.BusinessFlow}`,DK="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",_K="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",IK=["xaml","name","description","processorder"];async function ZR(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,EK.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function aO(e,t,r){let n={statecode:br.StateCode.Activated,statuscode:br.StatusCode.Activated},i=`/workflows(${t})`,o={...Ed};return r&&(o["If-Match"]=r),(0,_t.ensureSuccess)(await e.patch(i,n,{headers:o}),e.apiUrl(i))}async function eO(e,t,r){return(0,_t.readEtag)(await aO(e,t,r))}function tO(e,t){return new wr.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. `+Sd(e))}async function Cd(e,t){var r;let n=`/workflows(${t})${(0,Bn.odataQuery)([["$select","statecode"]])}`,i=(0,_t.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 wr.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 l0(e,t,r){if(await Cd(e,t)!==br.StateCode.Activated)return{deactivated:!1,etag:null};let n={statecode:br.StateCode.Draft,statuscode:br.StatusCode.Draft},i=`/workflows(${t})`,o={...Ed};r&&(o["If-Match"]=r);let a;try{a=await e.patch(i,n,{headers:o})}catch(l){return await rO(e,t,l)}if(SK.has(a.status))return await rO(e,t,new wr.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' answered HTTP ${a.status} from an intermediary, so whether it committed is unknown.`));let s=(0,_t.ensureSuccess)(a,e.apiUrl(i));return{deactivated:!0,etag:(0,_t.readEtag)(s)}}async function rO(e,t,r){let n;try{n=await Cd(e,t)}catch{n=void 0}if(n===br.StateCode.Draft)return{deactivated:!0,etag:null,uncertainCause:r};if(n===br.StateCode.Activated)throw r;let i=new wr.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`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 i.cause=r,i}async function nO(e,t){let r=(0,Bn.normalizeGuid)(t,"workflowid");try{return await aO(e,r,null),"restored"}catch{try{let n=await Cd(e,r);return n===br.StateCode.Activated?"restored":n===br.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}}function iO(e,t,r,n){let i=`Original failure: ${n instanceof Error?n.message:String(n)}`,o=r==="disabled"?new wr.SdkError("BPF_LEFT_DEACTIVATED",`Business process flow '${e}' was deactivated ${t}, and it could NOT be reactivated \u2014 it is left DISABLED. ${i}`):new wr.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",`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. ${i}`);return o.cause=n,o}async function TK(e,t){try{return await Cd(e,t),"survived"}catch(r){return r instanceof wr.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function PK(e,t,r){if(r)try{let{deactivated:n,etag:i}=await l0(e,t,r),o=n?i:r;if(o)return await(0,_t.deleteRecord)(e,"workflows",t,o),"removed"}catch{}return TK(e,t)}function Sd(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 oO(e,t){return new wr.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. ${Sd(e)}`)}function RK(e,t){let r=new wr.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.) ${Sd(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return r.cause=t,r}function OK(e,t){let r=new wr.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. ${Sd(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return r.cause=t,r}function xK(e,t){let r=new wr.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 r.cause=t,r}function LK(e){let t={};for(let r of IK)e[r]!==void 0&&(t[r]=e[r]);return t}Nd.bpfApi={async get(e,t){let n=`/workflows(${(0,Bn.normalizeGuid)(t,"id")})${(0,Bn.odataQuery)([["$select",_K]])}`,i=(0,_t.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,_t.readEtag)(i)}},async list(e,t){let r=[NK];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,Bn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,Bn.odataQuery)([["$select",DK],["$filter",r.join(" and ")]])}`;return(await(0,AK.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,Bn.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",o=(0,_t.ensureSuccess)(await e.post(i,r.record,{headers:Ed}),e.apiUrl(i)),a=(0,_t.readEtag)(o);if(!a)throw oO(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 eO(e,n,a)),await ZR(e,r)}catch(l){let u=await PK(e,n,s);throw u==="survived"?RK(n,l):u==="unknown"?OK(n,l):l instanceof wr.SdkError&&l.code===_t.VERSION_CONFLICT_CODE?xK(n,l):l}if(!s)throw oO(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,Bn.normalizeGuid)(t,"id"),a=(0,_t.requireEtag)(n,"bpf",o),{deactivated:s,etag:l,uncertainCause:u}=await l0(e,o,a);try{if(u!==void 0)throw u;let c=a;if(s){if(!l)throw tO(o,"deactivation");c=l}let d=`/workflows(${o})`,p=(0,_t.ensureSuccess)(await e.patch(d,LK(i.record),{headers:{...Ed,"If-Match":c}}),e.apiUrl(d)),f=(0,_t.readEtag)(p);if(i.status==="Active"){if(!f)throw tO(o,"definition write");f=await eO(e,o,f)}return await ZR(e,i),{id:o,etag:f}}catch(c){if(s){let d=await nO(e,o);if(d!=="restored")throw iO(o,"to apply an edit, the edit failed",d,c)}throw c}},async delete(e,t){let r=(0,Bn.normalizeGuid)(t,"id"),{deactivated:n}=await l0(e,r,null);try{await(0,_t.deleteRecord)(e,"workflows",r)}catch(i){if(n){let o=await nO(e,r);if(o!=="restored")throw iO(r,"so it could be deleted, the delete failed",o,i)}throw i}}}});var zO=b(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.bpfRegistration=Va.BpfAdapter=void 0;var Dd=Ti(),kK=sO(),u0=ri(),mo=oi(),wO=ii(),er=Nr(),jt=lt(),cn=re(),FK=100,d0='<?xml version="1.0" encoding="utf-16"?>',lO=1033,AO="mxswa:Workflow",MK="mxswa:ActivityReference.Properties",BK="mcwo:StepLabel",$K="mcwb:Control",uO="mcwb:Control.ControlDisplayName",EO="mcwb:Control.DataFieldName",CO="DataFieldName",cO="ControlDisplayName",SO="Literal",_d="x:Null",dO="x:String",p0="x:Key",f0="DisplayName",Td="Activities",UK="StepLabels",NO="StageId",DO="StageCategory",_O="NextStageId",IO="ProcessStepId",m0="IsProcessRequired",TO="EntityComposite",PO="StageComposite",RO="StepComposite";function c0(e){return(0,er.isJsonObject)(e)?e:{}}function dn(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 ho(e,t){var r;return(r=dn(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function pn(e){return ho(e,MK)}function It(e,t){var r;return(r=dn(e).find(n=>n.getAttribute(p0)===t))!==null&&r!==void 0?r:null}function qa(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function Un(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function OO(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function yl(e){var t;let r=(t=e.getAttribute(f0))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function xO(e,t){var r;let n=(r=e.getAttribute(f0))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(f0,i>=0?n.slice(0,i+2)+t:t)}function LO(e,t){let r=It(e,UK),n=ho(r,BK);n&&n.setAttribute("Description",t)}function qK(e){let t=It(e,DO);if(!t||t.tagName===_d)return;let r=Un(t).trim();return r===""?void 0:Number(r)}function VK(e){let t=It(e,_O);if(!t||t.tagName===_d)return;let r=Un(t).trim();return r===""?void 0:r}function kO(e){let t=FO(e);if(!t)return;let r=BO(t,CO,EO);return r===""?void 0:r}function h0(e,t){let r=dn(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of dn(n))r.push(i)}return null}function FO(e){let t=It(pn(e),Td);return t?h0(t,$K):null}function MO(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 BO(e,t,r){var n;return MO(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":HK(e,r)}function pO(e,t,r,n){if(MO(e,t)){e.setAttribute(t,n);return}if(ho(e,r)){GK(e,r,n);return}throw new cn.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function GK(e,t,r){let n=ho(e,t),i=n?h0(n,SO):null;i&&i.setAttribute("Value",r)}function $O(e){return yl(e)}function Pd(e){let t=ho(e,AO),r=[];for(let n of dn(t).filter(i=>qa(i,TO))){let i=It(pn(n),Td);for(let o of dn(i).filter(a=>qa(a,PO)))r.push({el:o,entity:$O(n)})}return r}function g0(e){let t=It(pn(e),Td);return dn(t).filter(r=>qa(r,RO))}function zK(e){let t=pn(e),r=Un(It(t,m0)).trim().toLowerCase(),n=kO(e),i={id:Un(It(t,IO)),name:yl(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function WK(e,t){let r=pn(e),n=qK(r),i=VK(r),o={id:Un(It(r,NO)),name:yl(e),entityLogicalName:t,steps:g0(e).map(zK)};return n!==void 0&&(o.category=n),i!==void 0&&(o.nextStageId=i),o}function jK(e){return Pd(e).map(({el:t,entity:r})=>WK(t,r))}function $n(e){return new cn.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 HK(e,t){var r;let n=ho(e,t),i=n?h0(n,SO):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function v0(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(v0(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function UO(e){return It(pn(e),Td)}function KK(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,jt.newId)(),{body:a}=Rd(y0(i,(0,jt.newId)(),t.id,o));return v0(e,Pd((0,mo.parseXmlRoot)(a,"<Activity/>"))[0].el)}function JK(e,t){let{body:r}=Rd(y0("account",(0,jt.newId)(),(0,jt.newId)(),t.id));return v0(e,g0(Pd((0,mo.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function qO(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function VO(e,t,r,n){let i=It(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw $n(`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!==_d){let s=t.createElement(_d);s.setAttribute(p0,r),o.replaceChild(s,i)}return}if(i.tagName===dO){Un(i)!==n&&OO(i,t,n);return}let a=t.createElement(dO);a.setAttribute(p0,r),a.appendChild(t.createTextNode(n)),o.replaceChild(a,i)}function QK(e,t,r){VO(e,t,DO,r===void 0?void 0:String(r))}function XK(e,t,r){VO(e,t,_O,r)}function GO(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 fO(e){return Un(It(pn(e),NO))}function mO(e){return Un(It(pn(e),IO))}function hO(e,t,r){var n,i,o,a;let s=pn(e);r.name!==yl(e)&&(xO(e,r.name),LO(s,r.name));let l=Un(It(s,m0)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=It(s,m0);u&&OO(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((o=kO(e))!==null&&o!==void 0?o:"")){let u=FO(e);if(!u)throw new cn.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=r.fieldName)!==null&&a!==void 0?a:"";pO(u,CO,EO,c),c!==""&&BO(u,cO,uO)===""&&pO(u,cO,uO,c)}}function gO(e,t,r,n){var i;let o=pn(e);if(!o)throw new cn.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==yl(e)&&(xO(e,r.name),LO(o,r.name)),QK(o,t,r.category),XK(o,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw $n("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw $n("stage actions or conditional branching");let a=UO(e);if(!a)throw new cn.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new cn.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=g0(e);if(GO(l,s.map(d=>d.id),mO)){l.forEach((d,p)=>hO(d,t,s[p]));return}let u=new Map(l.map(d=>[mO(d),d]));if(dn(a).some(d=>!qa(d,RO)))throw $n("adding, removing or reordering steps on a stage that also contains branching or actions");let c=s.map(d=>{var p;return(p=u.get(d.id))!==null&&p!==void 0?p:JK(t,d)});qO(a,c),c.forEach((d,p)=>hO(d,t,s[p]))}function YK(e,t,r){let n=ho(e,AO);if(!n)throw new cn.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw $n("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new cn.InvalidArgumentError("a BPF must have at least one stage");let i=Pd(e),o=i.map(p=>p.el);if(GO(o,r.stages.map(p=>p.id),fO)){i.forEach(({el:p,entity:f},m)=>{let h=r.stages[m];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==f)throw $n(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${f}')`);gO(p,t,h,h.nextStageId)});return}let a=dn(n).filter(p=>qa(p,TO));if(a.length!==1)throw $n("adding, removing or reordering stages on a multi-table process");let s=a[0],l=$O(s),u=UO(s);if(!u)throw new cn.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(dn(u).some(p=>!qa(p,PO)))throw $n("adding, removing or reordering stages on a process whose primary composite holds non-stage activities (multi-table nesting or advanced constructs)");for(let p of r.stages)if(p.entityLogicalName&&p.entityLogicalName.trim()!==""&&p.entityLogicalName!==l)throw $n(`a stage on a different table ('${p.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(o.map(p=>[fO(p),p])),d=r.stages.map(p=>{var f;return(f=c.get(p.id))!==null&&f!==void 0?f:KK(t,p,l)});qO(u,d),d.forEach((p,f)=>{let m=f<d.length-1?r.stages[f+1].id:void 0;gO(p,t,r.stages[f],m)})}function Rd(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function ZK(e){var t,r,n,i,o,a;(0,wO.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let p=new DOMParser().parseFromString("<root/>","text/xml"),f={n:"Activity",a:(0,u0.mergeAttrs)(s.a,[]),c:(0,u0.spliceChildren)(s.c,[])};return{root:(0,u0.rebuildRaw)(f,(0,mo.domEngine)(p),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:d0,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=y0(e.entityLogicalName,(0,jt.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,jt.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,jt.newId)()),{body:d}=Rd(c);return{root:(0,mo.parseXmlRoot)(d,"<Activity/>"),prolog:d0,eol:"lf"}}function eJ(e){let{root:t,prolog:r,eol:n}=ZK(e);YK(t,t.ownerDocument,e);let i=(0,mo.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r
-`)),r+i}function tJ(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Id=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,wO.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}=Rd(o),u=(0,mo.parseXmlRoot)(l,"<Activity/>");a.stages=jK(u),a.bag={xaml:(0,mo.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,jt.newId)(),name:t.name,uniquename:tJ(t),primaryentity:t.entityLogicalName,xaml:eJ(t),category:Dd.WorkflowCategory.BusinessProcessFlow,type:Dd.WorkflowTypeCode.Definition,businessprocesstype:Dd.BusinessProcessType.BusinessFlow,scope:Dd.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:FK};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 cn.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(yO):[yO({id:(0,jt.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,jt.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=c0(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,jt.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,er.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,er.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=c0(l),p=typeof d.id=="string"?d.id.trim():"";p===""?r.push((0,er.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(p.toLowerCase())?r.push((0,er.issue)(`${c}/id`,"stage-id-duplicate",`two stages share the id '${l.id}' (also at /stages/${a.get(p.toLowerCase())})`)):a.set(p.toLowerCase(),u),typeof l.entityLogicalName=="string"&&l.entityLogicalName!==""&&o.add(l.entityLogicalName);let f=Array.isArray(l.steps)?l.steps:[];f.length===0&&r.push((0,er.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),f.length>30&&r.push((0,er.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${f.length}`));let m=new Map;f.forEach((h,g)=>{let y=`${c}/steps/${g}`,w=typeof c0(h).id=="string"?h.id.trim():"";w===""?r.push((0,er.issue)(`${y}/id`,"step-id-required","a step needs an id")):m.has(w.toLowerCase())?r.push((0,er.issue)(`${y}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):m.set(w.toLowerCase(),g)}),l.branch&&!vO(i,l.branch.nextStageId)&&r.push((0,er.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${l.branch.nextStageId}' does not match any stage id`)),typeof l.nextStageId=="string"&&l.nextStageId!==""&&!vO(i,l.nextStageId)&&r.push((0,er.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${l.nextStageId}' does not match any stage id`))}),o.size>5&&r.push((0,er.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=rJ(i);return s>=0&&r.push((0,er.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};Va.BpfAdapter=Id;function rJ(e){let t=new Map(e.map(r=>[r.id,r]));for(let r=0;r<e.length;r+=1){let n=new Set,i=e[r];for(;i&&typeof i.nextStageId=="string"&&i.nextStageId!=="";){if(n.has(i.id))return r;n.add(i.id),i=t.get(i.nextStageId)}}return-1}function vO(e,t){return e.some(r=>r.id===t)}function yO(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(bO):[bO({id:(0,jt.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,jt.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 bO(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,jt.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 y0(e,t,r,n){return`${d0}<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="${lO}" /></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="${lO}" /></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 nJ(){return{adapter:new Id,api:kK.bpfApi,languageSensitive:!0}}Va.bpfRegistration=nJ});var WO=b(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});Od.buildRegistrations=void 0;var iJ=cT(),oJ=IT(),aJ=tP(),sJ=yP(),lJ=MP(),uJ=rR(),cJ=bR(),dJ=QR(),pJ=zO();function fJ(e){let t=new Map;return t.set("form",(0,iJ.formRegistration)(e)),t.set("view",(0,oJ.viewRegistration)()),t.set("businessRule",(0,aJ.businessRuleRegistration)()),t.set("app",(0,sJ.appRegistration)(e)),t.set("command",(0,lJ.commandRegistration)()),t.set("chart",(0,uJ.chartRegistration)()),t.set("dashboard",(0,cJ.dashboardRegistration)(e)),t.set("genPage",(0,dJ.genPageRegistration)()),t.set("bpf",(0,pJ.bpfRegistration)()),t}Od.buildRegistrations=fJ});var e1=b(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.removeRowSummary=Fe.configureRowSummary=Fe.buildGptDynamicPrompt=Fe.setAppAiFeatures=Fe.getAiReadiness=Fe.saveSettingValue=Fe.retrieveSetting=Fe.AI_GATE=void 0;var Fr=be(),qe=ae(),jO=lt(),qn=re();Fe.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var QO={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},mJ=new Set(Object.entries(Fe.AI_GATE).filter(([e,t])=>QO[e]===t).map(([e])=>e)),hJ={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function b0(e){return hJ[e]}var xd=1e6;function gJ(e,t){let r=b0(t),n=()=>{throw new qn.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${xd} (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>xd?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(xd).length||Number(s)>xd?n():s}}return n()}function vJ(e,t){let r=b0(t);return r?e===r.enabled:e!=="0"}async function yJ(e,t){var r,n,i;let o=`/appmodules${(0,qe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,a=await e.get(o);return a.status>=200&&a.status<300?(i=((n=(r=a.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0])===null||i===void 0?void 0:i.appmoduleid:void 0}async function bJ(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 qn.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 qn.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 qn.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 qn.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var HO=new WeakMap;async function wJ(e,t){var r,n,i;let o=HO.get(e);if(o||(o=new Map,HO.set(e,o)),o.has(t))return o.get(t);let a=`/settingdefinitions${(0,qe.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,s=await e.get(a),l=s.status>=200&&s.status<300?(i=((n=(r=s.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0])===null||i===void 0?void 0:i.settingdefinitionid:void 0;return l&&o.set(t,l),l}async function AJ(e,t,r){var n,i;let o=await wJ(e,r);if(!t||!o)return;let a=`/appsettings${(0,qe.odataQuery)([["$select","value"],["$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=(i=(n=s.body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[];return l.length>0?{exists:!0,value:l[0].value}:{exists:!1}}var EJ=4,CJ=500,KO=20,JO=3e4;function SJ(e){if(e===void 0)return EJ;if(!Number.isFinite(e))throw new qn.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${KO}; got ${e}.`);return Math.min(KO,Math.max(1,Math.floor(e)))}function NJ(e){if(e===void 0)return CJ;if(!Number.isFinite(e))throw new qn.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${JO}; got ${e}.`);return Math.min(JO,Math.max(0,Math.floor(e)))}async function DJ(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(f=>setTimeout(f,a*d));let p;try{let f=await t();f?(p=await AJ(e,f,n),p===void 0&&(u="the app-scope override row could not be read (insufficient access or unresolvable ids)")):u=`the app '${r}' could not be resolved to an appmoduleid \u2014 a newly created app is not readable until it is published, so either publish it first or pass \`appModuleId\` in the options to verify without the lookup`}catch(f){p=void 0,u=f.message}c=p!==void 0,l=p?.exists;try{s=(await Ld(e,n,{appUniqueName:r})).value}catch{}if(p?.exists&&p.value===i)return{result:"proven",effectiveValue:p.value,appOverrideExists:!0}}return c?{result:"absent",effectiveValue:s,appOverrideExists:l}:{result:"unverifiable",effectiveValue:s,appOverrideExists:void 0,reason:u}}function XO(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?b0(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function Ld(e,t,r={}){var n,i;let o=[`SettingName='${(0,qe.odataPathLiteral)(t)}'`];r.appUniqueName&&o.push(`AppUniqueName='${(0,qe.odataPathLiteral)(r.appUniqueName)}'`);let a=`/RetrieveSetting(${o.join(",")})`,l=(i=(n=(0,Fr.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.SettingDetail)!==null&&i!==void 0?i:{};return{value:l.Value,dataType:l.DataType}}Fe.retrieveSetting=Ld;async function YO(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,Fr.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Fe.saveSettingValue=YO;async function _J(e,t={}){let r={};for(let[n,i]of Object.entries(Fe.AI_GATE)){let{value:o,dataType:a}=await Ld(e,i,t);r[n]={enabled:XO(o,a,n),setting:i,value:o}}return r}Fe.getAiReadiness=_J;async function IJ(e,t,r,n={}){var i,o;if(!t||!t.trim())throw new qn.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let a=SJ(n.verifyAttempts),s=NJ(n.verifyDelayMs),l=[];for(let[h,g]of Object.entries(r)){if(g===void 0)continue;let y=QO[h];y&&l.push({feature:h,setting:y,requestedValue:gJ(g,h)})}let u=[],c=n.appModuleId?(0,qe.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(c){let h=await bJ(e,t);if(h&&(0,qe.normalizeGuid)(h,"appModuleId")!==c)throw new qn.InvalidArgumentError(`setAppAiFeatures: appModuleId '${c}' does not belong to app '${t}' (which resolves to '${h}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let d,p=async()=>c||(d||(d=await yJ(e,t)),d),f=new Map,m=async h=>{if(mJ.has(h))return;let g=Fe.AI_GATE[h];if(g){if(!f.has(g))try{let{value:y,dataType:w}=await Ld(e,g);f.set(g,{enabled:XO(y,w,h),setting:g,value:y})}catch{f.set(g,void 0)}return f.get(g)}};for(let{feature:h,setting:g,requestedValue:y}of l)try{await YO(e,g,y,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let w=await DJ(e,p,t,g,y,a,s),C={feature:h,setting:g,requestedValue:y,effectiveValue:w.effectiveValue,appOverrideExists:w.appOverrideExists};if(w.result==="proven")u.push({...C,status:"applied"});else if(w.result==="absent"){let S=vJ(y,h)?await m(h):void 0;S&&!S.enabled?u.push({...C,status:"skipped",reason:`the write was issued and no app-scope override holding '${y}' was observed for '${g}' after ${a} attempt(s); the org readiness gate '${S.setting}' reads '${S.value}', so an environment admin must enable it before this app can turn the feature on`}):u.push({...C,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${y}' was observed for '${g}' after ${a} attempt(s) \u2014 it reads '${(i=w.effectiveValue)!==null&&i!==void 0?i:""}' for this app (Dataverse can accept an app-scope write without storing it)`})}else u.push({...C,status:"unverified",reason:`the write was issued but could not be confirmed: ${(o=w.reason)!==null&&o!==void 0?o:"the app-scope override row could not be read"}. The value may or may not be in force \u2014 verify manually before relying on it.`})}catch(w){u.push({feature:h,setting:g,requestedValue:y,status:"failed",reason:w.message})}return{applied:u.filter(h=>h.status==="applied").map(h=>h.feature),skipped:u.filter(h=>h.status==="skipped").map(h=>h.feature),notPersisted:u.filter(h=>h.status==="notPersisted").map(h=>h.feature),unverified:u.filter(h=>h.status==="unverified").map(h=>h.feature),failed:u.filter(h=>h.status==="failed").map(h=>h.feature),outcomes:u}}Fe.setAppAiFeatures=IJ;var TJ="GptPowerPrompt",PJ='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function ZO(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:""}}Fe.buildGptDynamicPrompt=ZO;async function RJ(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,qe.odataPathLiteral)(t)}')${(0,qe.odataQuery)([["$select","MetadataId"]])}`;return(n=(r=(0,Fr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.MetadataId)!==null&&n!==void 0?n:""}async function OJ(e,t,r={}){var n,i,o,a,s;let l=`ais_RowSummary_${t.entityLogicalName}`,u=`/aiskillconfigs${(0,qe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(l)}'`],["$top",1]])}`,c=((i=(n=(0,Fr.ensureSuccess)(await e.get(u),e.apiUrl(u)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[])[0];if(c)return{modelId:c._aimodel_value,aiSkillConfigId:c.aiskillconfigid};let d=`/msdyn_aitemplates${(0,qe.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${TJ}'`],["$top",1]])}`,p=((s=(a=(o=(0,Fr.ensureSuccess)(await e.get(d),e.apiUrl(d)).body)===null||o===void 0?void 0:o.value)===null||a===void 0?void 0:a[0])!==null&&s!==void 0?s:{}).msdyn_aitemplateid,f=(0,jO.newId)(),m=(0,jO.newId)(),h=JSON.stringify(ZO(t)),g={ModelId:f,RunConfigurationId:m,ModelName:`${t.entityLogicalName} row summary`,TemplateId:p,CustomConfiguration:h,Source:PJ,RunConfiguration:""};(0,Fr.ensureSuccess)(await e.post("/AIModelPublish",g),e.apiUrl("/AIModelPublish"));try{let y=await RJ(e,t.entityLogicalName),w={uniquename:l,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${y})`,"[email protected]":`/msdyn_aimodels(${f})`,aiskill:"RowSummary"},C=(0,Fr.ensureSuccess)(await e.post("/aiskillconfigs",w),e.apiUrl("/aiskillconfigs")),S=(0,Fr.requireCreatedId)(C,"aiskillconfigid","row-summary skill");return{modelId:f,aiSkillConfigId:S}}catch(y){try{await e.delete(`/msdyn_aimodels(${f})`)}catch{}throw y}}Fe.configureRowSummary=OJ;async function xJ(e,t){var r,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=((n=(r=(0,Fr.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!a)return;let s=(0,qe.normalizeGuid)(a.aiskillconfigid,"aiskillconfigid"),l=a._aimodel_value?(0,qe.normalizeGuid)(a._aimodel_value,"_aimodel_value"):void 0,u=`/aiskillconfigs(${s})`;if((0,Fr.ensureSuccess)(await e.delete(u),e.apiUrl(u)),l){let c=`/msdyn_aimodels(${l})`;(0,Fr.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}Fe.removeRowSummary=xJ});var n1=b(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.findArtifact=Ga.resolveArtifact=void 0;var dt=ae(),Vn=vu(),LJ=Nu(),kJ=Rt(),FJ=be(),t1=re();async function r1(e,t,r){let n="/uxagentprojects"+(0,dt.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,dt.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,kJ.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function MJ(e,t,r){var n,i,o,a,s,l,u,c,d,p,f,m,h;switch(t){case"app":{let g=(0,LJ.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,dt.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),w=(i=(0,FJ.ensureSuccess)(await e.get(g),e.apiUrl(g)).body)===null||i===void 0?void 0:i.value,C=w&&w[0];return C?[{id:String(C.appmoduleid),name:String(C.name),appModuleIdUnique:String(C.appmoduleidunique)}]:[]}case"dashboard":return(await(0,Vn.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,dt.odataLiteral)((o=r.name)!==null&&o!==void 0?o:"")}' and type eq 0`,top:10})||[]).map(y=>({id:String(y.formid),name:String(y.name)}));case"command":{let g=await(0,Vn.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,dt.odataLiteral)((a=r.entity)!==null&&a!==void 0?a:"")}'`,top:1});return g&&g.length?[{id:String(r.entity),entity:String(r.entity)}]:[]}case"form":return(await(0,Vn.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,dt.odataLiteral)((s=r.name)!==null&&s!==void 0?s:"")}' and objecttypecode eq '${(0,dt.odataLiteral)((l=r.entity)!==null&&l!==void 0?l:"")}'`,top:10})||[]).map(y=>({id:String(y.formid),name:String(y.name)}));case"chart":return(await(0,Vn.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,dt.odataLiteral)((u=r.name)!==null&&u!==void 0?u:"")}' and primaryentitytypecode eq '${(0,dt.odataLiteral)((c=r.entity)!==null&&c!==void 0?c:"")}'`,top:10})||[]).map(y=>({id:String(y.savedqueryvisualizationid),name:String(y.name)}));case"view":return(await(0,Vn.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,dt.odataLiteral)((d=r.name)!==null&&d!==void 0?d:"")}' and returnedtypecode eq '${(0,dt.odataLiteral)((p=r.entity)!==null&&p!==void 0?p:"")}'`,top:10})||[]).map(y=>({id:String(y.savedqueryid),name:String(y.name)}));case"webResource":return(await(0,Vn.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,dt.odataLiteral)((f=r.name)!==null&&f!==void 0?f:"")}'`,top:1})||[]).map(y=>({id:String(y.webresourceid),name:String(y.name)}));case"solution":return(await(0,Vn.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,dt.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(y=>({id:String(y.solutionid),name:String(y.uniquename)}));case"genPage":return r1(e,(h=r.name)!==null&&h!==void 0?h:"");default:return[]}}Ga.resolveArtifact=MJ;async function BJ(e,t,r){var n,i,o,a,s,l,u;let c=(0,dt.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),d=(0,dt.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){let g=await(0,Vn.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,dt.odataLiteral)((o=r.entity)!==null&&o!==void 0?o:"")}'`,top:1});return g&&g.length?String(r.entity):null}if(t==="genPage"){let g=await r1(e,(a=r.name)!==null&&a!==void 0?a:"",2);if(g.length>1)throw new t1.AmbiguousArtifactError(t,(s=r.name)!==null&&s!==void 0?s:"",g.length);return g.length===1?g[0].id:null}let p=$J(t,c,d,r),f=t!=="app",m=await(0,Vn.queryRecords)(e,p.set,{select:[p.idField],filter:p.filter,top:f?2:1});if(f&&m&&m.length>1)throw new t1.AmbiguousArtifactError(t,(u=(l=r.name)!==null&&l!==void 0?l:r.uniqueName)!==null&&u!==void 0?u:"",m.length);let h=m&&m[0]&&m[0][p.idField];return h!=null?String(h):null}Ga.findArtifact=BJ;function $J(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,dt.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 o1=b(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});Fd.seedRecordGraph=void 0;var i1=vu(),UJ=Vl(),kd=ae(),qJ=re();async function VJ(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:(p=>(0,UJ.resolveEntitySetName)(e,p)),c={},d=p=>{var f;return(f=c[p])!==null&&f!==void 0?f:l[p]};for(let p of t){let f=p.entityLogical.toLowerCase(),m=(o=p.matchOn)===null||o===void 0?void 0:o.toLowerCase(),h=[];for(let O of p.records){let k={...O.body};for(let F of(a=O.binds)!==null&&a!==void 0?a:[]){let P=F.parentEntity.toLowerCase(),q=(s=d(P))===null||s===void 0?void 0:s[F.parentIndex];if(!q)throw new qJ.InvalidArgumentError(`Cannot resolve bind '${F.navProperty}' on a '${f}' record: parent '${F.parentEntity}'[${F.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let V=(0,kd.assertODataName)(await u(P),`entity set for parent '${F.parentEntity}'`),Ve=(0,kd.normalizeGuid)(q,`parent id for bind '${F.navProperty}'`);k[`${F.navProperty}@odata.bind`]=`/${V}(${Ve})`}h.push(k)}let g=m?h.map(O=>{let k=O[m];return k!=null&&k!==""?String(k):null}):h.map(()=>null),y=new Map;if(m){let O=(0,kd.assertODataName)(m,"RecordGraph matchOn key"),k=[...new Set(g.filter(F=>F!==null))];if(k.length){let F=k.map(q=>`${O} eq '${(0,kd.odataLiteral)(q)}'`).join(" or "),P=await(0,i1.queryRecords)(e,f,{select:[O,`${f}id`],filter:F,top:5e3});for(let q of P??[]){let V=q[O];V!=null&&y.set(String(V).toLowerCase(),String(q[`${f}id`]))}}}let w=[],C=new Map,S=h.map((O,k)=>{let F=g[k];if(F&&y.has(F.toLowerCase()))return null;if(F){let P=F.toLowerCase(),q=C.get(P);if(q!==void 0)return q;let V=w.push(O)-1;return C.set(P,V),V}return w.push(O)-1}),T=w.length?await(0,i1.createRecordsBulk)(e,f,w):[];c[f]=h.map((O,k)=>{let F=g[k];return F&&y.has(F.toLowerCase())?y.get(F.toLowerCase()):T[S[k]]})}return{createdIds:c}}Fd.seedRecordGraph=VJ});var h1=b(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.getEntityPrivileges=bt.addEntityPrivilegesToRole=bt.deleteSecurityRole=bt.createPersonaRole=bt.createSecurityRole=bt.SDK_ROLE_MARKER=void 0;var Mr=be(),nt=ae(),tr=re(),Md={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},A0={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},a1={user:1,businessUnit:2,parentChild:3,organization:4},w0={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};bt.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function GJ(e){return Object.prototype.hasOwnProperty.call(Md,e)?Md[e]:void 0}function zJ(e){return Object.prototype.hasOwnProperty.call(A0,e)}var s1=new WeakMap,l1=new WeakMap;async function d1(e,t){var r,n;(0,nt.assertODataName)(t,"entity logical name");let i=s1.get(e);i||(i=new Map,s1.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,nt.odataPathLiteral)(t)}')${(0,nt.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,Mr.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 tr.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function WJ(e){var t,r,n;let i=l1.get(e);if(i)return i;let o=`/businessunits${(0,nt.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,Mr.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 tr.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,nt.normalizeGuid)(l,"businessUnitId");return l1.set(e,u),u}async function p1(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new tr.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let o=(r=i.scope)!==null&&r!==void 0?r:"user";if(!zJ(o))throw new tr.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await d1(e,i.entity);for(let s of i.access){let l=GJ(s);if(!l)throw new tr.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=a.find(m=>m.PrivilegeType===l);if(!u)throw new tr.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=w0[o];if(u[c]===!1)throw new tr.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,nt.normalizeGuid)(u.PrivilegeId,"PrivilegeId"),p=n.get(d);if(!p){n.set(d,{privilegeName:u.Name,privilegeType:l,scope:o,entities:new Set([i.entity])});continue}if(p.scope===o){p.entities.add(i.entity);continue}if(!(p.entities.size===1&&p.entities.has(i.entity))){let m=[...p.entities].sort().join(", ");throw new tr.InvalidArgumentError(`Entities '${m}' and '${i.entity}' share the Dataverse privilege '${u.Name}' but request different scopes; a role holds one depth per privilege. Use the same scope for all entities that share this privilege, or split them.`)}p.scope=a1[o]>a1[p.scope]?o:p.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 jJ(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(a=>({Depth:A0[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,Mr.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function u1(e,t,r,n,i){var o,a;let s=`/${t}(${r})/${n}${(0,nt.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((a=(o=(0,Mr.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 HJ(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,nt.normalizeGuid)(l,"teamId");if(!await u1(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,Mr.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,nt.normalizeGuid)(l,"userId");if(!await u1(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,Mr.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}return{teams:o,users:a}}async function c1(e,t,r){var n,i;let o=`/roles${(0,nt.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,nt.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,Mr.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 p;return d.ismanaged!==!0&&((p=d.description)!==null&&p!==void 0?p:"")===bt.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new tr.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 tr.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,nt.normalizeGuid)(c,"roleId"):void 0}function KJ(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,nt.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,nt.normalizeGuid)(n,"userId"))}}function f1(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function m1(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new tr.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,nt.normalizeGuid)(t.businessUnitId,"businessUnitId"):await WJ(e),a=await p1(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=KJ(t.assignTo),l=await c1(e,i,o),u=l!==void 0;if(!l){let d="/roles",p={name:i,description:bt.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let f=(0,Mr.ensureSuccess)(await e.post(d,p),e.apiUrl(d));l=(0,nt.normalizeGuid)((0,Mr.requireCreatedId)(f,"roleid","role"),"roleId")}catch(f){let m;try{m=await c1(e,i,o)}catch{m=void 0}if(!m)throw f;l=m}}await jJ(e,l,a,u);let c=await HJ(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:f1(a),assignedTeams:c.teams,assignedUsers:c.users}}bt.createSecurityRole=m1;async function JJ(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new tr.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 m1(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}bt.createPersonaRole=JJ;async function QJ(e,t){let n=`/roles(${(0,nt.normalizeGuid)(t,"roleId")})`;(0,Mr.ensureSuccess)(await e.delete(n),e.apiUrl(n))}bt.deleteSecurityRole=QJ;async function XJ(e,t,r){let n=(0,nt.normalizeGuid)(t,"roleId");if(r.length===0)throw new tr.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await p1(e,r),o={Privileges:i.map(s=>({Depth:A0[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,Mr.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),f1(i)}bt.addEntityPrivilegesToRole=XJ;var YJ=new Map(Object.keys(Md).map(e=>[Md[e],e]));async function ZJ(e,t){return(await d1(e,t)).map(n=>{let i=Object.keys(w0).filter(a=>n[w0[a]]!==!1),o=YJ.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...o?{access:o}:{},scopes:i}})}bt.getEntityPrivileges=ZJ});var N1=b(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.createMakerSdk=rr.MakerSdk=rr.PUSH_NOT_ATTEMPTED_CODE=rr.ALREADY_EXISTS_CODE=void 0;var g1=ap(),v1=nr(),ne=re(),Ar=wo(),eQ=Qv(),C1=ry(),bl=ly(),tQ=lp(),rQ=Iy(),E0=Ty(),nQ=Gy(),it=Vl(),y1=mf(),Gn=vu(),Bd=Dw(),za=Au(),iQ=Cu(),Tt=Mw(),oQ=bf(),aQ=Rf(),b1=wf(),sQ=WO(),$d=lt(),lQ=Li(),fn=wg(),zn=dp(),uQ=3e5,Er=be(),Wn=ae(),Wa=e1(),w1=n1(),cQ=o1(),dQ=Fh(),wl=h1(),S1=Symbol("cds-maker-sdk.committedWrite");function pQ(e){return typeof e=="object"&&e!==null&&(e[S1]=!0),e}function fQ(e){return typeof e=="object"&&e!==null&&e[S1]===!0}var mQ=new Set(["entity","appmodule","dashboard","uxagentproject"]);function hQ(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,Wn.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 gQ(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 C1.WorkspaceManager(vQ,e.instanceUrl,(0,tQ.assertStorageContract)(t))}rr.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";rr.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var vQ="<injected workspaceStorage>",Ud=class{constructor(t){var r,n;this.artifactLocks=new Map,this.observedGenerations=new Map,this.baselineObserved=new Map,this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:lQ.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:uQ,this.compiler={load:(0,oQ.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=gQ(t),this.versions=new bl.VersionManager(this.workspace),this.dataverse=new rQ.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName),this.registrations=(0,sQ.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){var i,o,a;let s=this.requireRegistration(t,"fetchArtifact"),{raw:l,etag:u,memberEtags:c,siblingEtags:d}=await s.api.get(this.dataverse,r),p=s.adapter.fromApiResponse(l);if(!n?.overwrite&&await this.versions.isDirty(t,r)){let m=(o=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.etag)!==null&&o!==void 0?o:null;if(m&&u&&m!==u)throw new ne.LocalEditsWouldBeLostError(t,r,m,u);let h=await this.workspace.readArtifact(t,r);if(h){let g=await this.versions.getMeta(t,r);if(g&&!g.etag&&u){if(!(0,zn.deepEqual)(g.snapshot,p))throw new ne.LocalEditsWouldBeLostError(t,r,m,u);await this.versions.storeMeta(t,r,{...g,etag:u,fetchedAt:(0,Er.nowIso)()})}return(0,fn.cloneJson)(h)}}await this.workspace.writeArtifact(t,r,p);let f=await this.versions.getMeta(t,r);return await this.versions.storeMeta(t,r,{etag:u,languageCode:this.languageCode,projectionVersion:bl.PROJECTION_VERSION,fetchedAt:(0,Er.nowIso)(),snapshot:(0,fn.cloneJson)(p),...c?{memberEtags:c}:{},...d?{siblingEtags:d}:{},...f?.refreshGeneration?{refreshGeneration:f.refreshGeneration,observedGeneration:(a=f.observedGeneration)!==null&&a!==void 0?a:0}:{}}),(0,fn.cloneJson)(p)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){var r;let n=await(0,Tt.fetchSolutionComponents)(this.dataverse,t),i=[],o=[];for(let a of n)try{let s=await this.resolveComponentType(a);if(!s){o.push({componentId:a.objectId,componentType:a.componentType,workflowCategory:a.workflowCategory,reason:"unsupported"});continue}let l=await this.fetchArtifact(s,a.objectId);i.push({type:s,id:a.objectId,name:typeof l.name=="string"?l.name:(r=a.displayName)!==null&&r!==void 0?r:a.objectId,entityLogicalName:typeof l.entityLogicalName=="string"?l.entityLogicalName:void 0,lastFetched:(0,Er.nowIso)(),isDirty:!1})}catch(s){o.push({componentId:a.objectId,componentType:a.componentType,workflowCategory:a.workflowCategory,reason:"failed",error:Ii(s)})}return await this.workspace.updateManifest({lastSyncAt:(0,Er.nowIso)()}),{summaries:i,skipped:o}}async fetchEntityMetadata(t){let r=await(0,E0.fetchEntityMetadataFromApi)(this.dataverse,t);return await this.workspace.writeEntityMetadata(t,r),r}generateGenPageRuntimeTypes(t,r){return(0,nQ.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,E0.findTables)(this.dataverse,t,r)}findColumns(t,r,n){return(0,E0.findColumns)(this.dataverse,t,r,n)}createTable(t){return(0,it.createTable)(this.dataverse,t)}createColumn(t,r){return(0,it.createColumn)(this.dataverse,t,r)}createColumns(t,r){return(0,it.createColumns)(this.dataverse,t,r)}updateColumn(t,r,n){return(0,it.updateColumn)(this.dataverse,t,r,n)}deleteColumn(t,r){return(0,it.deleteColumn)(this.dataverse,t,r)}setFormSecurityRoles(t,r){return(0,y1.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,y1.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,it.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,it.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return(0,it.createCustomerColumn)(this.dataverse,t,r)}insertStatusValue(t,r){return(0,it.insertStatusValue)(this.dataverse,t,r)}updateTable(t,r){return(0,it.updateTable)(this.dataverse,t,r)}async setEntityIcon(t,r){if(await(0,it.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,Wn.xmlText)(t)}</entity></entities></importexportxml>`;(0,Er.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,it.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,it.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){return(0,it.createRelationship)(this.dataverse,t)}deleteRelationship(t){return(0,it.deleteRelationship)(this.dataverse,t)}createGlobalOptionSet(t){return(0,it.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,it.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return(0,it.deleteTable)(this.dataverse,t)}createSecurityRole(t){return(0,wl.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,wl.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,wl.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,wl.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,wl.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,Gn.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,Gn.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,Gn.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,Gn.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,Gn.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,Gn.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,Gn.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,cQ.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,w1.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,w1.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){let n=await(0,aQ.deleteAppCascade)(this.dataverse,t,r),i=(0,Wn.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,Gn.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,Gn.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,Bd.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,Bd.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,Bd.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,Bd.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,za.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,za.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new ne.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:iQ.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,za.setAppSetting)(this.dataverse,t,za.HEADER_AND_NAVIGATION_REFRESH,r?za.APP_SETTING_ON:za.APP_SETTING_OFF)}getSolution(t){return(0,Tt.getSolution)(this.dataverse,t)}createPublisher(t){return(0,Tt.createPublisher)(this.dataverse,t)}createSolution(t){return(0,Tt.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,Tt.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,Tt.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,Tt.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,Tt.exportSolution)(this.dataverse,t)}importSolution(t){return(0,Tt.importSolution)(this.dataverse,t)}deleteSolution(t){return(0,Tt.deleteSolution)(this.dataverse,t)}async getArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let n=await this.getArtifactUnlocked(t,r);return await this.acknowledgeRefresh(t,r),n})}async getArtifactUnlocked(t,r){return(0,fn.cloneJson)(await this.readRaw(t,r))}async acknowledgeRefresh(t,r){var n,i,o;let a=this.artifactKey(t,r),s=await this.versions.getMeta(t,r);this.baselineObserved.has(a)||this.baselineObserved.set(a,(n=s?.observedGeneration)!==null&&n!==void 0?n:0);let l=(i=s?.refreshGeneration)!==null&&i!==void 0?i:0;s&&l!==((o=s.observedGeneration)!==null&&o!==void 0?o:0)&&await this.versions.storeMeta(t,r,{...s,observedGeneration:l}),this.observedGenerations.set(a,l)}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,C1.canonicalArtifactId)(r)}`}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 ne.StaleArtifactError(t,r,n,"pushed");if(await this.revalidateIfStale(t,r)==="refreshed-changed")throw new ne.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 ne.ArtifactNotFoundError(t,r);return n}async revalidateIfStale(t,r){let n=await this.versions.getMeta(t,r);if(!n)return"skipped";let i=n.fetchedAt?Date.parse(n.fetchedAt):NaN,o=Date.now()-i;if(!Number.isNaN(i)&&this.cacheStalenessMs>0&&o<=this.cacheStalenessMs)return"fresh";if(await this.versions.isDirty(t,r))return"skipped";let a=await this.workspace.readArtifact(t,r);await this.fetchArtifactUnlocked(t,r);let s=await this.workspace.readArtifact(t,r);return(0,zn.deepEqual)(a,s)?"refreshed-unchanged":"refreshed-changed"}async queryTree(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.getArtifactUnlocked(t,r),o=Ar.JsonPointer.resolve(i,n);if(o===void 0)throw new ne.PathNotFoundError(t,r,n);return n===""&&await this.acknowledgeRefresh(t,r),o})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,eQ.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.workspace.readEntityMetadata(t);if(!r)throw new ne.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 ne.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=Ar.JsonPointer.resolve(a,n);if(s===void 0)throw new ne.PathNotFoundError(t,r,n);let l=jn(s)&&jn(i)?{...s,...i}:i;return Ar.JsonPointer.set(a,n,(0,fn.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=Ar.JsonPointer.resolve(s,n);if(l===void 0)throw new ne.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!jn(l)||!jn(i))throw new ne.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 ne.ValidationError(t,r,n,"position is not supported for an object parent");let d={};for(let p of Object.keys(i)){if(p==="id")throw new ne.ValidationError(t,r,n,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let f=(0,fn.cloneJson)(i[p]),m=(0,$d.isValueMapKey)(p)||(0,$d.pointerTouchesValueMap)(n);d[p]=m?f:Array.isArray(f)?f.map(h=>jn(h)?this.assignMissingIds(t,h):h):jn(f)?this.assignMissingIds(t,f):f}for(let p of Object.keys(d))Ar.JsonPointer.set(s,Ar.JsonPointer.append(n,p),d[p]);return this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)}let u=(0,$d.pointerTouchesValueMap)(n)?(0,fn.cloneJson)(i):this.assignMissingIds(t,(0,fn.cloneJson)(i)),c=wQ(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=Ar.JsonPointer.resolve(l,n);if(u===void 0)throw new ne.PathNotFoundError(t,r,n);let c=Ar.JsonPointer.resolve(l,i);if(c===void 0)throw new ne.PathNotFoundError(t,r,i);if(!Array.isArray(c))throw new ne.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new ne.ValidationError(t,r,i,"cannot move an element into its own subtree");Ar.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),E1(c);let p=Ar.JsonPointer.resolve(l,A1(n));return Array.isArray(p)&&p!==c&&E1(p),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(Ar.JsonPointer.resolve(o,n)===void 0)throw new ne.PathNotFoundError(t,r,n);return Ar.JsonPointer.remove(o,n),this.assertStructurallyValid(t,r,o,A1(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 ne.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,Wa.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,Wa.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,Wa.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,Wa.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,Wa.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,Wa.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,dQ.findDefaultViews)(this.dataverse,t,{excludeViewIds:n.excludeViewIds}),o=n.publish===!1,a=[],s=[],l=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,v1.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&&fQ(c)&&a.push(u),o?(0,ne.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 ne.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 ne.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,o,async()=>(await this.workspace.writeArtifact(t,o,i),(0,fn.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()=>{await this.requireRegistration(t,"deleteRemoteArtifact").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 f of t){let m=this.artifactKey(f.type,f.id);o.has(m)||o.set(m,{type:f.type,id:f.id})}let a=[];for(let[f,m]of o)a.push(await this.withArtifactLock(m.type,m.id,()=>this.preparePublish(f,m.type,m.id)));let s=new Set(o.keys()),l=[],u=new Set;for(let f of a){let m=((n=f.scope)===null||n===void 0?void 0:n.envelope)==="entity"?(i=f.scope.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;f.scope&&m&&!u.has(m)&&(u.add(m),l.push(...await this.captureSiblings(f.scope,s)))}let c=hQ(a),d;if(c)try{await(0,v1.publishXml)(this.dataverse,c)}catch(f){d=Ii(f)}let p=new Map;for(let f of a)p.set(f.key,await this.withArtifactLock(f.type,f.id,()=>this.settlePublish(f,d,r)));for(let f of l)await this.withArtifactLock(f.type,f.id,()=>this.adoptBracket(f));return t.map(f=>({...p.get(this.artifactKey(f.type,f.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||!mQ.has(s.envelope))throw new ne.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,zn.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:Ii(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){var i;try{let o=(i=await this.versions.getMeta(r,n))===null||i===void 0?void 0:i.etag;if(!o||!t.api.readToken)return;let{raw:a,etag:s}=await t.api.get(this.dataverse,n);return s!==o||await t.api.readToken(this.dataverse,n)!==o?void 0:{type:r,id:n,reg:t,heldEtag:o,content:this.bracketContent(t,a)}}catch{return}}async captureSiblings(t,r){var n,i;let o=t.envelope==="entity"?(n=t.entityLogicalName)===null||n===void 0?void 0:n.toLowerCase():void 0;if(!o)return[];let a=[],s;try{s=await this.workspace.listArtifacts()}catch{return[]}for(let l of s){let u=this.registrations.get(l.type);if(r.has(this.artifactKey(l.type,l.id))||u?.rebaselineAfterPublish!=="bracket"||!u.publishScope)continue;try{let d=await this.workspace.readArtifact(l.type,l.id),p=d?u.publishScope(l.id,d):void 0;if(p?.envelope!=="entity"||((i=p.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase())!==o)continue}catch{continue}let c=await this.captureBracket(u,l.type,l.id);c&&a.push(c)}return a}async adoptBracket(t){try{let r=await this.versions.getMeta(t.type,t.id);if(!r||r.etag!==t.heldEtag)return;let{raw:n,etag:i}=await t.reg.api.get(this.dataverse,t.id);if(!i||i===t.heldEtag||!(0,zn.deepEqual)(this.bracketContent(t.reg,n),t.content))return;await this.versions.storeMeta(t.type,t.id,{...r,etag:i,fetchedAt:(0,Er.nowIso)()})}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 (${Ii(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,zn.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}=await t.api.get(this.dataverse,n),u=t.adapter.fromApiResponse(o),c=d=>{var p,f,m;return(m=(f=(p=t.adapter).baselineContent)===null||f===void 0?void 0:f.call(p,d))!==null&&m!==void 0?m:d};if(!a||!(0,zn.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:a,fetchedAt:(0,Er.nowIso)(),...s?{memberEtags:s}:{},...l?{siblingEtags:l}:{}})}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,Wn.normalizeGuid)(r,"id")})${(0,Wn.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:{},p=n;if(!p)return{kind:"unverifiable",reason:"there is no local copy of the app to compare the published projection with"};let f=[];return((o=p.name)!==null&&o!==void 0?o:"")!==((a=d.name)!==null&&a!==void 0?a:"")&&f.push("name"),((s=p.description)!==null&&s!==void 0?s:"")!==((l=d.description)!==null&&l!==void 0?l:"")&&f.push("description"),f.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${f.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:Ii(u).message}}}async verifyPublishedContent(t,r,n,i){var o,a,s;try{let l=p=>{var f,m,h;return(h=(m=(f=t.adapter).baselineContent)===null||m===void 0?void 0:m.call(f,p))!==null&&h!==void 0?h:p},u=l(i),c=(o=await this.versions.getMeta(r,n))===null||o===void 0?void 0:o.snapshot;if(c===void 0||!(0,zn.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,zn.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:Ii(l).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async prepareArtifactUnlocked(t,r){var n,i;let o=this.requireRegistration(t,"pushArtifact"),a=await this.readLocal(t,r),s=(i=(n=o.adapter).normalize)===null||i===void 0?void 0:i.call(n,a);s&&s!==a&&(await this.workspace.writeArtifact(t,r,s),a=s);let l=await this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,l,o),this.assertProjectionMatches(t,r,l);let u=await this.buildMetadataContext(o.adapter,a),c=await o.adapter.toApiPayload(a,l?.snapshot,u);return await this.assertSemanticallyComplete(o,t,r,a,l===null,l?.everActivated),{type:t,id:r,reg:o,json:a,meta:l,payload:c}}async assertSemanticallyComplete(t,r,n,i,o,a){var s;let l=t.adapter.issuesBlockingPush;if(!l)return;let u=i.entityLogicalName,c=u?await this.workspace.readEntityMetadata(u):null,d=((s=c?.attributes)!==null&&s!==void 0?s:[]).map(f=>({logicalName:f.logicalName,displayName:f.displayName,attributeType:f.attributeType,isCustomAttribute:f.isCustomAttribute,...f.maxLength!==void 0?{maxLength:f.maxLength}:{},...f.options?{options:f.options.map(m=>({value:m.value,label:m.label}))}:{},...f.targets?{targets:f.targets}:{}})),p=l.call(t.adapter,i,d,{isCreate:o,everActivated:a});if(p.length>0)throw new ne.ValidationError(r,n,p)}async pushArtifactUnlocked(t,r){return this.executePrepared(await this.prepareArtifactUnlocked(t,r))}async executePrepared(t){var r,n,i,o,a,s,l,u,c;let{type:d,id:p,reg:f,json:m,meta:h,payload:g}=t,y=!1;try{let w=h?await f.api.update(this.dataverse,p,g,h.etag,h.memberEtags,h.siblingEtags):await this.createWithMintedId(f,d,p,g);y=!0;let C=p;h||(w.serverIdentity&&f.adapter.applyServerIdentity&&f.adapter.applyServerIdentity(m,w.serverIdentity),w.id&&w.id!==p&&(m.id=w.id,await this.workspace.deleteArtifact(d,p),C=w.id));let S=h&&w.readBack!==void 0?this.adoptReadBack(f,w.readBack):void 0,T=S?.artifact?{artifact:S.artifact,baseline:S.artifact}:f.adapter.committed?f.adapter.committed(m,g,{intentPending:w.intentPending===!0}):{artifact:m,baseline:m};(!h||T.artifact!==m)&&await this.workspace.writeArtifact(d,C,T.artifact);let O=S?.artifact!==void 0&&!(0,zn.deepEqual)(S.artifact,m),k=((r=h?.refreshGeneration)!==null&&r!==void 0?r:0)+(O?1:0),F=[...(n=w.warnings)!==null&&n!==void 0?n:[],...S?.warning?[S.warning]:[],...S?.artifact!==void 0&&!this.adoptedAsSent(f,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,...k>0?{refreshGeneration:k,observedGeneration:(i=h?.observedGeneration)!==null&&i!==void 0?i:0}:{},languageCode:this.languageCode,projectionVersion:bl.PROJECTION_VERSION,fetchedAt:(0,Er.nowIso)(),snapshot:(0,fn.cloneJson)(T.baseline),...w.memberEtags?{memberEtags:w.memberEtags}:{},...w.siblingEtags?{siblingEtags:w.siblingEtags}:{}}),{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 q=(P=f.publishScope)===null||P===void 0?void 0:P.call(f,C,m);return q?{publishScope:q}:{}})():{},...O?{refreshed:!0}:{},...F.length>0?{warnings:F}:{}}}catch(w){let C=(0,ne.readPartialTokens)(w);if(C&&h){let S={...(a=h.memberEtags)!==null&&a!==void 0?a:{},...(s=C.memberEtags)!==null&&s!==void 0?s:{}},T={...(l=h.siblingEtags)!==null&&l!==void 0?l:{},...(u=C.siblingEtags)!==null&&u!==void 0?u:{}};await this.versions.storeMeta(d,p,{...h,...Object.keys(S).length>0?{memberEtags:S}:{},...Object.keys(T).length>0?{siblingEtags:T}:{}})}if(w instanceof ne.SdkError&&w.code===rr.ALREADY_EXISTS_CODE)return{type:d,id:p,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof ne.SdkError&&w.code===g1.WFOM_API_UNAVAILABLE_CODE)return{type:d,id:p,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof ne.SdkError&&w.code===g1.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:d,id:p,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof ne.SdkError&&w.code===Er.VERSION_CONFLICT_CODE)return{type:d,id:p,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,b1.isFailureAfterPrimaryWrite)(w)?w:new ne.VersionConflictError(d,p,(c=h?.etag)!==null&&c!==void 0?c:null,null,w.message)};throw y?pQ(w):w}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new ne.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!==bl.PROJECTION_VERSION)throw new ne.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 ${bl.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){try{return await t.api.create(this.dataverse,i,n)}catch(o){throw!(o instanceof ne.SdkError)||o.code!==Er.VERSION_CONFLICT_CODE||(0,b1.isFailureAfterPrimaryWrite)(o)?o:new ne.SdkError(rr.ALREADY_EXISTS_CODE,`Cannot create ${r} '${n}': a record already exists at that id, so an earlier push of this artifact committed before its local version metadata was saved. No duplicate was created. Run fetchArtifact('${r}', '${n}', { 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.`)}}async buildMetadataContext(t,r){var n,i,o;let a=(i=(n=t.metadataNeeds)===null||n===void 0?void 0:n.call(t,r))!==null&&i!==void 0?i:[],s=new Set(a.map(m=>m.entityLogicalName).filter(m=>!!m)),l=new Set(a.filter(m=>m.needsColumnDetail).map(m=>m.entityLogicalName)),u=new Map;for(let m of s){let h=await this.workspace.readEntityMetadata(m);if(h&&l.has(m)&&(h.columnDetailComplete!==!0||h.attributes.some(g=>typeof g.attributeTypeName!="string"))&&(h=null),!h)try{await this.fetchEntityMetadata(m),h=await this.workspace.readEntityMetadata(m)}catch{}h&&u.set(m,h)}let c=this.languageCode,p=a.some(m=>{var h;if(!m.needsLabel||!m.fieldName)return!1;let g=(h=u.get(m.entityLogicalName))===null||h===void 0?void 0:h.attributes.find(y=>y.logicalName===m.fieldName);return g?.localizedDisplayName!==void 0&&!g.localizedDisplayName[c]})?await this.readBaseLanguage():void 0,f=!((o=t.needsBaseLanguage)===null||o===void 0)&&o.call(t,r)?await this.readBaseLanguage():void 0;return{resolveField:(m,h)=>{let g=u.get(m),y=g?.attributes.find(w=>w.logicalName===h);return y?{displayName:bQ(y,c,p),attributeType:y.attributeType}:void 0},resolveEntity:m=>u.get(m),loadTypeScript:()=>this.compiler.load(),...f!==void 0?{baseLanguageCode:f}:{}}}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;for(let i=0;i<t.length;i+=1){let o=t[i];try{await this.withArtifactLock(o.type,o.id,()=>this.prepareArtifactUnlocked(o.type,o.id))}catch(a){r.set(i,{type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Ii(a)})}}if(r.size>0)return t.map((i,o)=>{var a;return(a=r.get(o))!==null&&a!==void 0?a:{type:i.type,id:i.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new ne.SdkError(rr.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${r.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let n=[];for(let i of t)try{n.push(await this.pushArtifact(i.type,i.id))}catch(o){n.push({type:i.type,id:i.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Ii(o)})}return n}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.workspace.readEntityMetadata(a))try{await this.fetchEntityMetadata(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,$d.assignMissingIds)(r)}async resolveComponentType(t){if(t.genPage)return"genPage";switch(t.componentType){case Tt.SolutionComponentType.SavedQuery:return"view";case Tt.SolutionComponentType.SavedQueryVisualization:return"chart";case Tt.SolutionComponentType.AppModule:return"app";case Tt.SolutionComponentType.Workflow:return t.workflowCategory===2?"businessRule":t.workflowCategory===4&&await this.isBusinessFlowWorkflow(t.objectId)?"bpf":void 0;case Tt.SolutionComponentType.SystemForm:return await this.isDashboardForm(t.objectId)?"dashboard":"form";default:return}}async isDashboardForm(t){let n=`/systemforms(${(0,Wn.normalizeGuid)(t,"formId")})${(0,Wn.odataQuery)([["$select","type"]])}`,i=(0,Er.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)),o=Number(i.body.type);return o===0||o===10}async isBusinessFlowWorkflow(t){let n=`/workflows(${(0,Wn.normalizeGuid)(t,"workflowId")})${(0,Wn.odataQuery)([["$select","businessprocesstype"]])}`,i=(0,Er.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n));return Number(i.body.businessprocesstype)===0}requireRegistration(t,r){let n=this.registrations.get(t);if(!n)throw new ne.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};rr.MakerSdk=Ud;function yQ(e){return new Ud(e)}rr.createMakerSdk=yQ;function Ii(e){return e instanceof Error?e:new Error(String(e))}function bQ(e,t,r){let n=e.localizedDisplayName;return n?.[t]||(r===void 0?void 0:n?.[r])||e.displayName}function jn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function A1(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function E1(e){e.length===0||!e.every(t=>jn(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function wQ(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=>jn(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>jn(n)&&n.id===t.after);return r<0?e.length:r+1}});var D1=b(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});qd.ARTIFACT_TYPES=void 0;qd.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var I1=b(_1=>{"use strict";Object.defineProperty(_1,"__esModule",{value:!0})});var P1=b(T1=>{"use strict";Object.defineProperty(T1,"__esModule",{value:!0})});var O1=b(R1=>{"use strict";Object.defineProperty(R1,"__esModule",{value:!0})});var L1=b(x1=>{"use strict";Object.defineProperty(x1,"__esModule",{value:!0})});var F1=b(k1=>{"use strict";Object.defineProperty(k1,"__esModule",{value:!0})});var B1=b(M1=>{"use strict";Object.defineProperty(M1,"__esModule",{value:!0})});var U1=b($1=>{"use strict";Object.defineProperty($1,"__esModule",{value:!0})});var V1=b(q1=>{"use strict";Object.defineProperty(q1,"__esModule",{value:!0})});var z1=b(G1=>{"use strict";Object.defineProperty(G1,"__esModule",{value:!0})});var j1=b(W1=>{"use strict";Object.defineProperty(W1,"__esModule",{value:!0})});var K1=b(H1=>{"use strict";Object.defineProperty(H1,"__esModule",{value:!0})});var Q1=b(J1=>{"use strict";Object.defineProperty(J1,"__esModule",{value:!0})});var Y1=b(X1=>{"use strict";Object.defineProperty(X1,"__esModule",{value:!0})});var ex=b(Z1=>{"use strict";Object.defineProperty(Z1,"__esModule",{value:!0})});var rx=b(tx=>{"use strict";Object.defineProperty(tx,"__esModule",{value:!0})});var ix=b(nx=>{"use strict";Object.defineProperty(nx,"__esModule",{value:!0})});var ax=b(ox=>{"use strict";Object.defineProperty(ox,"__esModule",{value:!0})});var lx=b(sx=>{"use strict";Object.defineProperty(sx,"__esModule",{value:!0})});var cx=b(ux=>{"use strict";Object.defineProperty(ux,"__esModule",{value:!0})});var px=b(dx=>{"use strict";Object.defineProperty(dx,"__esModule",{value:!0})});var fx=b(ce=>{"use strict";var AQ=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]})),Pe=ce&&ce.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&AQ(t,e,r)};Object.defineProperty(ce,"__esModule",{value:!0});ce.createMakerSdk=void 0;var EQ=N1();Object.defineProperty(ce,"createMakerSdk",{enumerable:!0,get:function(){return EQ.createMakerSdk}});Pe(D1(),ce);Pe(I1(),ce);Pe(P1(),ce);Pe(O1(),ce);Pe(L1(),ce);Pe(F1(),ce);Pe(B1(),ce);Pe(U1(),ce);Pe(V1(),ce);Pe(z1(),ce);Pe(j1(),ce);Pe(K1(),ce);Pe(Q1(),ce);Pe(Y1(),ce);Pe(Cu(),ce);Pe(ex(),ce);Pe(rx(),ce);Pe(ix(),ce);Pe(ax(),ce);Pe(lx(),ce);Pe(cx(),ce);Pe(px(),ce);Pe(re(),ce)});var S0=b(mn=>{"use strict";var CQ=mn&&mn.__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]})),SQ=mn&&mn.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),gx=mn&&mn.__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)&&CQ(t,e,r);return SQ(t,e),t};Object.defineProperty(mn,"__esModule",{value:!0});mn.NodeFileSystemStorage=void 0;var Ke=gx(require("fs")),wt=gx(require("path")),mx=re(),hx=up();async function vx(e){let t;try{t=await Ke.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await Ke.promises.unlink(e)}catch{await Ke.promises.rmdir(e)}return}if(!t.isDirectory()){await Ke.promises.unlink(e);return}for(let r of await Ke.promises.readdir(e))await vx(wt.join(e,r));await Ke.promises.rmdir(e)}var C0=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(wt.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!Ke.existsSync(r);){n.unshift(wt.basename(r));let i=wt.dirname(r);if(i===r)return wt.resolve(t);r=i}return wt.resolve(Ke.realpathSync(r),...n)}assertWithinRoot(t,r){let n=wt.resolve(this.root),i=wt.resolve(t);if(i!==n&&!i.startsWith(n+wt.sep))throw new mx.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(n),a=r?this.realPathThroughNearestAncestor(i):wt.resolve(this.realPathThroughNearestAncestor(wt.dirname(i)),wt.basename(i));if(a!==o&&!a.startsWith(o+wt.sep))throw new mx.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!Ke.existsSync(r))return null;try{return await(0,hx.retryTransientIoAsync)(()=>Ke.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=wt.dirname(n);await Ke.promises.mkdir(i,{recursive:!0});let o=wt.join(i,`.${wt.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await Ke.promises.writeFile(o,r,"utf8"),await(0,hx.retryTransientIoAsync)(()=>Ke.promises.rename(o,n))}catch(a){try{Ke.existsSync(o)&&await Ke.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let r=this.pathFor(t);Ke.existsSync(r)&&await Ke.promises.unlink(r)}async deleteByPrefix(t){await vx(this.pathFor(t,!1))}async ensureContainer(t){await Ke.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return Ke.existsSync(this.pathFor(t))}};mn.NodeFileSystemStorage=C0});var yx=b(Ht=>{"use strict";var NQ=Ht&&Ht.__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]})),DQ=Ht&&Ht.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),_Q=Ht&&Ht.__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)&&NQ(t,e,r);return DQ(t,e),t};Object.defineProperty(Ht,"__esModule",{value:!0});Ht.loadNodeTypeScript=Ht.createNodeWorkspaceStorage=Ht.NodeFileSystemStorage=void 0;var IQ=S0(),TQ=S0();Object.defineProperty(Ht,"NodeFileSystemStorage",{enumerable:!0,get:function(){return TQ.NodeFileSystemStorage}});function PQ(e){return new IQ.NodeFileSystemStorage(e)}Ht.createNodeWorkspaceStorage=PQ;async function RQ(){return await Promise.resolve().then(()=>_Q(require("typescript")))}Ht.loadNodeTypeScript=RQ});var Hn={};module.exports=$r(Hn);Jn(Hn,de(fx()),module.exports);Jn(Hn,de(yx()),module.exports);
+`),a=e.apiUrl("/$batch"),s=i.map((p,m)=>String(m+1)),l;try{l=await(0,le.resendWhile)(p=>yV(p,s),()=>e.postBatch(o,r),le.DEADLOCK_BACKOFF_MS)}catch(p){return{kind:"unknown",error:p}}let u=SE(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 be.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,vE.parseChangeSetStatuses)(l.body,s);if(d===void 0)return{kind:"unknown",error:new be.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let f=d.find(p=>p<200||p>=300);return f!==void 0?{kind:"refused",error:new be.ConnectionError(a,f,`atomic delete of ${c} was rolled back: the change set reported HTTP ${f}`)}:d.length!==i.length?{kind:"unknown",error:new be.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 _c(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,le.readEtag)(r)}catch{return null}}async function mE(e,t){let r=`/appmodules(${t})?$select=appmoduleid`,n=await e.get(r);if(n.status!==404)return(0,le.ensureSuccess)(n,e.apiUrl(r)),(0,le.readEtag)(n)}async function zm(e,t,r,n){if(!n)return null;let i=await _c(e,t);if(!i)return null;try{let o=await e.get(Tc(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=ll(o);return!a||!Pc(a.sitemapid,t)||a.sitemapnameunique!==n||a.sitemapxml!==r.sitemapxml||a.sitemapname!==r.sitemapname?null:i}catch{return null}}function DE(e){return e>=400&&e<500&&e!==408&&e!==429}function hE(e,t,r){if(!e)throw new be.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 _E(e,t,r){let n=`/appmodules(${t})`,i=r.draft?void 0:hE(r.appEtag,t,"app");if(!r.sitemapId){if(r.draft){(0,le.ensureSuccess)(await(0,le.resendAppSearchIndexRace)(()=>e.delete(n)),e.apiUrl(n));return}await vV(e,n,i);return}if(!e.supportsAtomicBatch)throw new be.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 gV(e,[{path:n,etag:i},{path:`/sitemaps(${r.sitemapId})`,etag:hE(r.sitemapEtag,t,"sitemap")}])}async function vV(e,t,r){(0,le.ensureSuccess)(await(0,le.resendAppSearchIndexRace)(()=>e.delete(t,{headers:{"If-Match":r}})),e.apiUrl(t))}async function gE(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,Q4.collectGenPageIds)(t))]}catch(i){throw new be.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 (${ti(i)}).`)}if(r.length===0)return;let n=await(0,Y4.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new be.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 bV(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 yE(e,t,r){var n;let i=(0,he.normalizeGuid)(t,"id"),o=r==="tokens-first",a=o?await mE(e,i):null,s=Km(Hm,i),l=(0,le.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=(n=ll(l))!==null&&n!==void 0?n:{};if(!u.appmoduleid)throw new be.SdkError("APP_NOT_FOUND",`App '${i}' was not found (checked the unpublished-aware projection, which includes drafts).`);let c=await bE(e,u.uniquename),d=c?(0,he.normalizeGuid)(c,"sitemapId"):void 0,f=null;if(d){o&&(f=await _c(e,d));let m=Tc(d,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),h=(0,le.ensureSuccess)(await e.get(m),e.apiUrl(m)),g=ll(h),v=w=>{throw new be.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 v("the by-id read returned no row");if(g.sitemapnameunique!==u.uniquename)throw new be.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(!Pc(g.sitemapid,d))return v(`the by-id read returned a row carrying sitemapid '${String(g.sitemapid)}'`);if(typeof g.sitemapxml!="string")return v("the by-id read returned no sitemapxml");u.$sitemap=g,o||(f=await _c(e,d))}o||(a=await mE(e,i));let p=a??tV(u);return{raw:u,etag:f,...u.appmoduleid?{siblingEtags:{[(0,he.normalizeGuid)(u.appmoduleid,"appmoduleid")]:p}}:{}}}En.appApi={get(e,t){return yE(e,t,"tokens-first")},readContentThenToken(e,t){return yE(e,t,"content-first")},async list(e,t){let r=Km(Hm);return(await(0,Ta.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 gE(e,n.sitemapxml);let i=await dE(e,n,n.appModuleId),o=n.iconWebResourceId?void 0:await nV(e),a=n.iconWebResourceId||o?.id;if(!a)throw new be.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||rV(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,le.ensureSuccess)(await(0,le.resendDeadlockVictim)(()=>e.post(c,(0,le.withClientMintedId)(u,"appmoduleid",r))),e.apiUrl(c)),f=(0,le.resolveCreatedId)(d,"appmoduleid","app module",r),p=null,m=null,h=[];s&&h.push(s);let g={kind:"notRequested"},v=n.sitemapId?(0,he.normalizeGuid)(n.sitemapId,"sitemapId"):(0,jm.newId)(),w=!1,C={sitemapxml:n.sitemapxml,sitemapname:n.sitemapname};try{let k="/sitemaps",R=(0,le.echoWrite)("sitemapid"),T=await e.post(`${k}${R.query}`,{sitemapid:v,sitemapnameunique:l,...C},R.options);w=DE(T.status);let I=(0,le.ensureSuccess)(T,e.apiUrl(k));m=(0,le.readEtag)(I),p=m??await zm(e,v,C,l);let P=await uE(e,n,i);h.push(...P.warnings);let F=P.components;F.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:v}),await fE(e,f,F);let z=Dc(e,f);await pE(e,f,P.tables,z),i&&await uV(e,f,i,z);let Ie=await iV(e,f);Ie&&h.push(Ie),n.appSettings&&Object.keys(n.appSettings).length>0&&h.push(...await(0,X4.applyAppSettings)(e,f,n.appSettings)),n.published!==!1&&(await(0,oE.publishAppModule)(e,f),g={kind:"submitted"})}catch(k){let R=await dV(e,f,{sitemapId:v,sitemapNameUnique:l,serverRefusedSitemap:w,sitemapWriteToken:m});throw(0,Z4.failedAfterPrimaryWrite)(fV(k,R,{appId:f,sitemapId:v,uniqueName:l}))}let E=null;if(g.kind==="submitted")try{let k=await e.get(`/appmodules(${f})?$select=appmoduleid`);k.status>=200&&k.status<300&&(E=(0,le.readEtag)(k))}catch{}return{id:f,etag:p,serverIdentity:{sitemapId:v},siblingEtags:{[f]:E},publish:g,...h.length>0?{warnings:h}:{}}},async update(e,t,r,n,i,o){var a,s,l,u,c,d,f,p,m;let h=r,g=(0,he.normalizeGuid)(t,"id");if(await gE(e,h.sitemapxml),!h.sitemapId)throw new be.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 v=(0,he.normalizeGuid)(h.sitemapId,"sitemapId");if(!(0,le.isVersionToken)(n))throw new be.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 dE(e,h,g),C=await uE(e,h,w),E=`/appmodules(${g})`,k=(a=o?.[g])!==null&&a!==void 0?a:null,R=!0,T;try{let vt=Km(Hm,g),Un=await e.get(vt);if(Un.status>=200&&Un.status<300){let Yo=(s=ll(Un))!==null&&s!==void 0?s:{};T=typeof Yo.uniquename=="string"&&Yo.uniquename?Yo.uniquename:void 0,R=String((l=Yo.name)!==null&&l!==void 0?l:"")!==String((u=h.appModuleName)!==null&&u!==void 0?u:"")||String((c=Yo.description)!==null&&c!==void 0?c:"")!==String((d=h.appModuleDescription)!==null&&d!==void 0?d:"")||h.appModuleAiDescription!==void 0&&String((f=Yo.aiappdescription)!==null&&f!==void 0?f:"")!==String(h.appModuleAiDescription)}}catch{}let I=k;if(R){if(!(0,le.isVersionToken)(k))throw new be.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${g}': ${k?`the concurrency token held for its appmodule header ('${k}') 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 vt=(0,le.echoWrite)("appmoduleid",{"If-Match":k}),Un=await e.patch(`${E}${vt.query}`,{name:h.appModuleName,description:h.appModuleDescription,...h.appModuleAiDescription!==void 0?{aiappdescription:h.appModuleAiDescription}:{}},vt.options);if(bV(Un))throw new be.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,le.ensureSuccess)(Un,e.apiUrl(E)),I=(0,le.readEtag)(Un)}let P={sitemapxml:h.sitemapxml,sitemapname:h.sitemapname},F=T||h.appModuleUniqueName||void 0,z=(0,le.echoWrite)("sitemapid",{"If-Match":n}),Ie=`/sitemaps(${v})`,yt;try{yt=(0,le.ensureSuccess)(await e.patch(`${Ie}${z.query}`,{...P},z.options),e.apiUrl(Ie))}catch(vt){throw(0,be.withPartialTokens)(vt,{siblingEtags:{[g]:I}})}let Te=[...C.warnings],Qe=Dc(e,g);try{await fE(e,g,C.components),await pE(e,g,C.tables,Qe)}catch(vt){Te.push(`App '${g}': one or more components were not pinned (${vt.message}). Navigation may reference content not included in the app; re-push to retry.`)}w&&Te.push(...await cV(e,g,w,Qe));let ce={kind:"notRequested"},nt=I,to=(p=(0,le.readEtag)(yt))!==null&&p!==void 0?p:await zm(e,v,P,F);if(h.published===!0){try{await(0,oE.publishAppModule)(e,g),ce={kind:"submitted"}}catch(vt){ce={kind:"failed",error:vt},Te.push(`App '${g}': saved, but publishing failed (${vt.message}). The app remains unpublished; re-push to retry.`)}if(ce.kind==="submitted"){nt=null;try{let vt=await e.get(`/appmodules(${g})?$select=appmoduleid`);vt.status>=200&&vt.status<300&&(nt=(0,le.readEtag)(vt)),to=(m=await zm(e,v,P,F))!==null&&m!==void 0?m:to}catch{}}}return{id:g,etag:to,siblingEtags:{[g]:nt},publish:ce,...Te.length>0?{warnings:Te}:{}}},async delete(e,t){let r=(0,he.normalizeGuid)(t,"id");await _E(e,r,await EE(e,r))}}});var Ym=b(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.deleteAppCascade=Pa.collectGenPageIds=void 0;var wV=Oc(),AV=X(),Xm=ae(),CV=ya();function IE(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),i=new CV.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml").documentElement;if(!i||t.length>0)throw new AV.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,Xm.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}Pa.collectGenPageIds=IE;async function EV(e,t,r){let n=(0,Xm.normalizeGuid)(t,"appModuleId");(0,Xm.normalizeGuid)(r,"appModuleIdUnique");let i=[],o=[],a=[];await(0,wV.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&a.push(...IE(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}}Pa.deleteAppCascade=EV});var TE={};Ir(TE,{Guid:()=>$});var $,Xe=L(()=>{"use strict";$=class e{guidString;guid;static get EmptyGuid(){return new e("00000000-0000-0000-0000-000000000000")}static NewGuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var r=Math.random()*16|0,n=t=="x"?r:r&3|8;return n.toString(16)})}constructor(t,r=!1){this.guidString=t;let n=new RegExp("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");(r||n.test(t))&&(this.guid=t)}ToString(){return this.guid}}});var U,Pt=L(()=>{"use strict";ze();U=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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),r&&(n=n.replace(/"/g,"&quot;").replace(/'/g,"&apos;"))),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(!O.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 O.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 PE={};Ir(PE,{ScriptUtilities:()=>O});var O,ze=L(()=>{"use strict";Xe();Pt();O=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return U.IsNullOrEmpty(t.ToString())?!0:$.EmptyGuid.ToString()===t.ToString()}static IsNullOrUndefinedNested(t,r){return r.split(".").every(i=>typeof t!="object"||t==null||!(i in t)||t[i]==null?!1:(t=t[i],!0))}static ParseXml(t){return new DOMParser().parseFromString(t,"text/xml")}static IsWellFormedXml(t){return!e.ParseXml(t).querySelector("parsererror")}static getNamedItemValue(t,r){let n=t.getNamedItem(r);return e.IsNullOrUndefined(n)?null:n.value}static getBooleanValue(t,r){let n=e.getNamedItemValue(t,r);return e.IsNullOrUndefined(n)?null:U.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 Rc,kc,Ao,xc,Zm,Lc,eh=L(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(Rc||(Rc={}));kc=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},Ao=class extends kc{key;oldValue;newValue;constructor(t,r,n,i){super(Rc.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)}},xc=class extends kc{property;oldValue;newValue;constructor(t,r,n,i){super(Rc.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)}},Zm=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()})}},Lc=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 Zm(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 OE={};Ir(OE,{ChartGridMode:()=>Mr,ColumnLayoutWidths:()=>IV,ComponentCategory:()=>Mc,ComponentType:()=>th,ControlLayoutTypes:()=>lh,DisplayConditionsInfo:()=>DV,ElementNames:()=>A,ElementProperties:()=>y,ElementType:()=>nh,EntityAttributeProperty:()=>ih,EventType:()=>ul,FormActivationState:()=>sh,FormCanvasServiceScope:()=>UV,FormDesignerSideBarTab:()=>rh,FormPresentation:()=>oh,FormState:()=>Fc,FormType:()=>Ze,HeaderDensityType:()=>Fi,LookUpTable:()=>Sn,MORE_TAB_PREFIX:()=>PV,NavBarChildElementType:()=>ah,PREVIEW_ID_HEADER_FLYOUT:()=>xV,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>FV,PREVIEW_ID_NAVIGATION_AREA:()=>RV,PREVIEW_ID_QUICKCREATE_ROOT:()=>$V,PREVIEW_ID_TAB:()=>MV,PREVIEW_ID_TAB_LIST:()=>LV,PREVIEW_ID_TAB_PANEL:()=>kV,PropertyModelKeys:()=>dh,PropertyModelSectionKeys:()=>TV,RELATED_TAB_ID:()=>fh,RELATED_TAB_PREFIX:()=>OV,SectionDefaultProperties:()=>_V,SectionLayoutTypes:()=>Fe,TabContentType:()=>uh,TabDefaultProperties:()=>Mi,TabLayoutTypes:()=>Le,TelemetryPropertyNames:()=>BV,UnboundControlPropertyKeys:()=>ch,compositeAddressFields:()=>NV,compositeFieldNames:()=>Cr,compositeFields:()=>SV});var Ze,th,rh,A,y,nh,Cr,SV,NV,ih,Sn,Fc,Fi,oh,DV,ah,sh,Le,_V,Mi,Fe,lh,uh,IV,ch,dh,TV,ul,Mr,fh,PV,OV,RV,kV,xV,LV,FV,MV,$V,BV,Mc,UV,ie=L(()=>{"use strict";(function(e){e[e.Dashboard=0]="Dashboard",e[e.AppointmentBook=1]="AppointmentBook",e[e.Main=2]="Main",e[e.MiniCampaignBO=3]="MiniCampaignBO",e[e.Preview=4]="Preview",e[e.MobileExpress=5]="MobileExpress",e[e.QuickViewForm=6]="QuickViewForm",e[e.QuickCreate=7]="QuickCreate",e[e.Dialog=8]="Dialog",e[e.TaskFlowForm=9]="TaskFlowForm",e[e.InteractionCentricDashboard=10]="InteractionCentricDashboard",e[e.Card=11]="Card",e[e.MainInteractiveExperience=12]="MainInteractiveExperience",e[e.Other=100]="Other",e[e.MainBackup=101]="MainBackup",e[e.AppointmentBookBackup=102]="AppointmentBookBackup",e[e.PowerBIDashboard=103]="PowerBIDashboard"})(Ze||(Ze={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(th||(th={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(rh||(rh={}));(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"})(A||(A={}));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"})(nh||(nh={}));Cr={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},SV=[Cr.fullname,Cr.yomifullname,Cr.address1_composite,Cr.address2_composite,Cr.address3_composite,Cr.billto,Cr.shipto],NV=[Cr.address1_composite,Cr.address2_composite,Cr.address3_composite,Cr.billto,Cr.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(ih||(ih={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(Sn||(Sn={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Fc||(Fc={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(Fi||(Fi={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(oh||(oh={}));DV={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(ah||(ah={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(sh||(sh={}));(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"})(Le||(Le={}));_V={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},Mi={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"})(Fe||(Fe={}));(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"})(lh||(lh={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(uh||(uh={}));IV={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"})(ch||(ch={}));(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"})(dh||(dh={}));TV={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"})(ul||(ul={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(Mr||(Mr={}));fh="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",PV="more_tab_",OV="related_tab_",RV="preview_id_navigation_area",kV="tab-section",xV="headerFieldsFlyout",LV="tablist",FV="header_overflowButton",MV="tab",$V="quickCreateRoot",BV={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"})(Mc||(Mc={}));UV="CellCanvasServiceScope"});var RE={};Ir(RE,{Attribute:()=>$c,FormElementNode:()=>Z});var $c,Z,ft=L(()=>{"use strict";ze();Pt();eh();ie();Xe();$c=class{key;value;constructor(t,r){this.key=t,this.value=r}},Z=class e{nodeName;properties;childrenNodes;parentNode;nodeId;isTransient;constructor(t,r){this.nodeName=t,this.properties=[],this.childrenNodes=[],this.parentNode=r,this.isTransient=!1,this.nodeId=`nodeId-${$.NewGuid()}`}getProperty(t){for(let r of this.properties)if(r.key===t)return r.value;return null}getNodeId(){return this.nodeId}getNodeName(){return this.nodeName}setNodeName(t){this.trackObjectPropertyChange("nodeName",t)}get NodeName(){return this.getNodeName()}getAllProperties(){return this.properties}replaceAttributeValue(t,r){this.properties.find(n=>n===t)&&(t.value=r)}replaceObjectPropertyValue(t,r){this[t]=r}getAllChildren(){return this.childrenNodes}getParentNode(){return this.parentNode}visit(t){let r=!1;if(t){r=!!t(this);let n=this.childrenNodes;if(!r&&n)for(let i=0;!r&&i<n.length;i++)r=n[i].visit(t)}return r}findAll(t){let r=[];return t&&this.visit(n=>{t(n)&&r.push(n)}),r}findFirst(t){let r=null;return t&&this.visit(n=>{if(t(n))return r=n,!0}),r}raiseMetadataChange(t){let r=this.getAncestor(A.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new $c(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 Ao(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 Ao(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 Ao(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 xc(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 Ao(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){O.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(O.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:U.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=O.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 A.formCell:let t=this.getAncestor(A.formSection);return t||(t=this.getAncestor(A.formHeader),t)||(t=this.getAncestor(A.formFooter),t)?t:null;case A.formSection:return this.getAncestor(A.formTab);case A.formTab:return this.getAncestor(A.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(A.form);return t?t.changeTracker():null}}});var kE={};Ir(kE,{ControlClassId:()=>N,ControlNamePrefixes:()=>Bc,getControlDisplayNames:()=>qV});function qV(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,Bc,Co=L(()=>{"use strict";(function(e){e.AccessPrivilegeControl="F93A31B2-99AC-4084-8EC2-D4027C31369A",e.AccessTeamTablePickerControl="3f4e2a56-f102-4b4d-ab9c-f1574ca5bfda",e.ACIControl="C8BFBBEF-6851-4401-A0CC-7450062FE085",e.ActivitiesContainerControl="C72511AB-84E5-4FB7-A543-25B4FC01E83E",e.ActivitiesWallControl="6636847D-B74D-4994-B55A-A6FAF97ECEA2",e.AppliedFiltersControl="9C310A73-A360-42C5-8943-47A06F1B51EA",e.ArticleContentControl="F02EF977-2564-4B9A-B2F0-DF083D8A019B",e.BooleanControl="67FAC785-CD58-4F9F-ABB3-4B7DDC6ED5ED",e.ButtonControl="00AD73DA-BD4D-49C6-88A8-2F4F4CAD4A20",e.CheckboxControl="B0C6723A-8503-4FD7-BB28-C8A06AC933C2",e.CompositionLinkControl="DB1284EF-9FFC-4E99-B382-0CC082FE2364",e.ConnectionControl="3246F906-1F71-45F7-B11F-D7BE0F9D04C9",e.ConnectionRoleObjectTypeListControl="821ACF1A-7E46-4A0C-965D-FE14A57D78C7",e.CoverageChoiceControl="4168A05C-D857-46AF-8457-5BB47EB04EA1",e.DashboardControl="D2561F53-B292-42D9-B222-478E40FFE29F",e.DynamicPropertyListControl="6896F004-B17A-4202-861E-8B7EA2080E0B",e.EditFilterControl="1479835F-F852-4679-B864-C6892A2844C9",e.ErrorStatusControl="F4C16ECA-CA81-4E39-9448-834B8378721E",e.GlobalFilterControl="FFF0E632-9D7B-4F21-BBC1-05D1567AD144",e.HiddenInputControl="5546E6CD-394C-4BEE-94A8-4425E17EF6C6",e.KBViewerControl="A62B6FA9-169E-406C-B1AA-EAB828CB6026",e.LabelControl="39354E4A-5015-4D74-8031-EA9EB73A1322",e.MailMergeLanguagePickerControl="B634828E-C390-444A-AFE6-E07315D9D970",e.MapLinkControl="91DC0675-C8B9-4421-B1E0-261CEBF02BAC",e.OrgInsightsControl="76b9e25e-695e-4fef-ac69-f05cfa96739c",e.ChoiceLookupControl="2305e33a-bad3-4022-9e15-1856cf218333",e.PowerBIControl="8C54228C-1B25-4909-A12A-F2B968BB0D62",e.ProcessControl="06E9F7AF-1F54-4681-8EEC-1E21A1CEB465",e.RelatedInformationControl="163B90A6-EB64-49D2-9DF8-3C84A4F0A0F8",e.RelationshipRoleChoiceControl="5F986642-5961-4D9F-AB5E-643D71E231E9",e.ReportControl="A28F441B-916C-4865-87FD-0C5D53BD59C9",e.StreamsControl="EE9078C8-6946-4E2C-B8F8-35E65F4BE6A8",e.WebResourceSilverlightControl="080677DB-86EC-4544-AC42-F927E74B491F",e.CurrencyControl="533B9E00-756B-4312-95A0-DC888637AC78",e.CustomControl="F9A8A302-114E-466A-B582-6771B2AE0D92",e.DateTimeControl="5B773807-9FB2-42DB-97C3-7A91EFF8ADFF",e.DecimalControl="C3EFE0C3-0EC6-42BE-8349-CBD9079DFD8E",e.DurationControl="AA987274-CE4E-4271-A803-66164311A958",e.EmailAddressControl="ADA2203E-B4CD-49BE-9DDF-234642B43B52",e.EmailBodyControl="6F3FB987-393B-4D2D-859F-9D0F0349B6AD",e.EmailEngagementActionsControl="F454228D-1D25-4319-E12F-D27968BC0234",e.EmailRecipientActivityControl="26E9760F-7454-40DE-BB07-F6DCCCB82040",e.FileControl="0A7FF475-B016-4687-9CE5-042BFDBD6519",e.FloatingNumberControl="0D2C745A-E5A8-4C8F-BA63-C6D3BB604660",e.IframeControl="FD2A7985-3187-444E-908D-6624B21F69C0",e.ImageControl="7E548B0D-209C-477B-9DCD-F0F44472381D",e.LanguageControl="671A9387-CA5A-4D1E-8AB7-06E39DDCF6B5",e.LookupControl="270BD3DB-D9AF-4782-9025-509E298DEC0A",e.MapsControl="62B0DF79-0464-470F-8AF7-4483CFEA0C7D",e.ChoicesControl="4AA28AB7-9C13-4F57-A73D-AD894D048B5F",e.IntegerControl="C6D124CA-7EDA-4A60-AEA9-7FB8D318B68F",e.PartyListControl="CBFB742C-14E7-4A17-96BB-1A13F7F64AA2",e.PhoneNumberControl="8C10015A-B339-4982-9474-A95FE05631A5",e.ChoiceControl="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE",e.ChoiceStatusControl="5D68B988-0661-4DB2-BC3E-17598AD3BE6C",e.QuickViewControl="5C5600E0-1D6E-4205-A272-BE80DA87FD42",e.QuickFormControl="69AF7DCA-2E3B-4EE7-9201-0DA731DD2413",e.RegardingControl="F3015350-44A2-4AA0-97B5-00166532B5E9",e.SearchWidgetControl="E616A57F-20E0-4534-8662-A101B5DDF4E0",e.SocialInsightsControl="86B9E25E-695E-4FEF-AC69-F05CFA96739C",e.SubgridControl="E7A81278-8635-4D9E-8D4D-59480B391C5B",e.TextAreaControl="E0DECE4B-6FC8-4A8F-A065-082708572369",e.TextboxControl="4273EDBD-AC1D-40D3-9FB2-095C621B552D",e.TickerControl="1E1FC551-F7A8-43AF-AC34-A8DC35C7B6D4",e.TimerControl="9C5CA0A1-AB4D-4781-BE7E-8DFBE867B87E",e.TimelineControl="06375649-C143-495E-A496-C962E5B4488E",e.TimezoneControl="7C624A0B-F59E-493D-9583-638D34759266",e.UrlControl="71716B6C-711E-476C-8AB8-5D11542BFB47",e.WebResourceHTMLControl="9FDF5F91-88B1-47F4-AD53-C11EFC01A01D",e.WebResourceImageControl="587CDF98-C1D5-4BDE-8473-14A0BC7644A7",e.ReferencePanelSearchWidgetControl="7CCD1494-1F7A-4E3A-8BDE-F32069DAEB9F",e.ReferencePanelSubgridControl="02D4264B-47E2-4B4C-AA95-F439F3F4D458",e.ReferencePanelQuickViewControl="B68B05F0-A46D-43F8-843B-917920AF806A",e.KBEditorControl="F94DB24F-263D-44A7-B38E-A35E9854812B",e.LinkControl="DFDF1CDE-837B-4AC9-98CF-AC74361FD89D"})(N||(N={}));Bc={[N.WebResourceHTMLControl]:"WebResource",[N.WebResourceImageControl]:"WebResource",[N.IframeControl]:"IFRAME",[N.SearchWidgetControl]:"Search widget",[N.SubgridControl]:"Subgrid",[N.TimelineControl]:"Timeline",[N.QuickViewControl]:"QuickviewControl"}});var Eo=b((Kre,LE)=>{var cl=new Proxy(function(){return cl},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:cl},apply:function(){return cl},construct:function(){return{}}}),xE=function(){return cl};Object.setPrototypeOf(xE,cl);LE.exports=xE});var Bt,ri,FE,ME,Oa=L(()=>{"use strict";Bt="cds-designer-models",ri="FormCustomControl",FE="FormCell",ME="Form"});var So,ph=L(()=>{"use strict";js();ie();So=class e{static lockedFieldCount=new $t;static dependencyFieldCount=new $t;static getNecessaryLookUpTable(t){switch(t){case Sn.DependencyFieldTable:return e.dependencyFieldCount;case Sn.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case Sn.DependencyFieldTable:e.dependencyFieldCount=new $t;case Sn.LockedFieldTable:e.lockedFieldCount=new $t}}}});var Uc,$E=L(()=>{"use strict";Xe();ze();ie();ft();Uc=class extends Z{constructor(t){super(A.controlDescription,t)}get forControl(){let t=this.getProperty(y.ForControl);return O.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new $(t))}set forControl(t){this.setProperty(y.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(A.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!O.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!O.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)O.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 ni(){return Nn||(Nn=window._makerConfig,Nn&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(Nn={...Nn,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),Nn?.region==="prod"&&(Nn={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/"}}},...Nn}),Nn||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var Nn,qc=L(()=>{"use strict";});function BE(e,t,r){if(!e)return Vc.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),Vc.add("")),!1;if(e){if(e=e.toLowerCase(),Vc.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}}),Vc.add(e),!1}return!0}function VV(e){return BE(e,mh,"Location dictionary")?mh[e.toLowerCase()]:"us"}function GV(){let e=ni().location.toLowerCase();return BE(e,mh,"Current location dictionary")?e:"us"}var Vc,mh,sne,UE=L(()=>{"use strict";qc();Vc=new Set,mh={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"};sne=VV(GV())});var H,une,qE=L(()=>{"use strict";H={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"},une={[H.USWest]:{geoName:"us",regionShortName:"wus"},[H.USCentral]:{geoName:"us",regionShortName:"cus"},[H.USEast]:{geoName:"us",regionShortName:"eus"},[H.USEast2]:{geoName:"us",regionShortName:"eus2"},[H.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[H.USWest2]:{geoName:"us",regionShortName:"wus2"},[H.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[H.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[H.UKSouth]:{geoName:"uk",regionShortName:"suk"},[H.UKWest]:{geoName:"uk",regionShortName:"wuk"},[H.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[H.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[H.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[H.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[H.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[H.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[H.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[H.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[H.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[H.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[H.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[H.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[H.AsiaEast]:{geoName:"as",regionShortName:"eas"},[H.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[H.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[H.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[H.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[H.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[H.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[H.UAENorth]:{geoName:"ae",regionShortName:"nae"},[H.UAECentral]:{geoName:"ae",regionShortName:"cae"},[H.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[H.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[H.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[H.NorwayEast]:{geoName:"no",regionShortName:"eno"},[H.NorwayWest]:{geoName:"no",regionShortName:"wno"},[H.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[H.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[H.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[H.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[H.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[H.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[H.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[H.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[H.GovernmentUSDodCentral]:{regionShortName:"udc"},[H.GovernmentUSDodEast]:{regionShortName:"ude"},[H.ChinaEast]:{regionShortName:"cne"},[H.ChinaEast2]:{regionShortName:"cne2"},[H.ChinaEast3]:{regionShortName:"cne3"},[H.ChinaNorth]:{regionShortName:"cnn"},[H.ChinaNorth2]:{regionShortName:"cnn2"},[H.ChinaNorth3]:{regionShortName:"cnn3"},[H.UssecEast]:{geoName:"us",regionShortName:"erx"},[H.UssecWest]:{geoName:"us",regionShortName:"wrx"},[H.UsnatEast]:{geoName:"us",regionShortName:"eex"},[H.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var VE=L(()=>{"use strict";qc();});var dl=L(()=>{"use strict";qc();UE();qE();VE();});function fl(e,t){return GE?GE.isOverridden(e,t):{overridden:!1}}var GE,pl=L(()=>{"use strict";});var hh=L(()=>{"use strict";dl();pl();});function WV(e,t){let{region:r}=ni();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=fl(e.packageName,t);if(s.overridden)return typeof s.value=="string"?zV(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 zV(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function jV(e){let t=e.packageName;if(Gc.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=>yh(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=>!zc(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function ml(e){jV(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:WV(e,r)}}),Gc.set(e.packageName,e),Object.defineProperties({},t)}function gh(e,t){return Gc.has(e)?!!Gc.get(e).settings[t]:!1}var Gc,Wc=L(()=>{"use strict";dl();pl();vh();hl();Gc=new Map});function WE(e,t){let{region:r}=ni();return()=>{let n=fl(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 HV(e){let t=e.packageName;if(jc.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=>gh(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=>!zc(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function bh(e){HV(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:WE(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:WE(e,o.toString())}}),Object.defineProperties(r,i),n.clear()}},jc.set(e.packageName,e),Object.defineProperties(r,t)}function yh(e,t){return jc.has(e)?!!jc.get(e).features[t]:!1}var jc,vh=L(()=>{"use strict";dl();hl();pl();Wc();jc=new Map});var jE=b((xne,zE)=>{"use strict";zE.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 JE=b(wh=>{"use strict";var KV=Object.prototype.hasOwnProperty,JV;function HE(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function KE(e){try{return encodeURIComponent(e)}catch{return null}}function QV(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=HE(n[1]),o=HE(n[2]);i===null||o===null||i in r||(r[i]=o)}return r}function YV(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(KV.call(e,i)){if(n=e[i],!n&&(n===null||n===JV||isNaN(n))&&(n=""),i=KE(i),n=KE(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}wh.stringify=YV;wh.parse=QV});var Eh=b((Fne,tS)=>{"use strict";var YE=jE(),Hc=JE(),XE=/[\n\r\t]/g,XV=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,ZV=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,eG=/^[a-zA-Z]:/,tG=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function Ch(e){return(e||"").toString().replace(tG,"")}var Ah=[["#","hash"],["?","query"],function(t,r){return Dn(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]],QE={hash:1,query:1};function ZE(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 _n(unescape(e.pathname),{});else if(i==="string"){n=new _n(e,{});for(o in QE)delete n[o]}else if(i==="object"){for(o in e)o in QE||(n[o]=e[o]);n.slashes===void 0&&(n.slashes=XV.test(e.href))}return n}function Dn(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function eS(e,t){e=Ch(e),e=e.replace(XE,""),t=t||{};var r=ZV.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)):Dn(n)?s=r[4]:n?i&&(s=s.slice(2)):a>=2&&Dn(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||Dn(n),slashesCount:a,rest:s}}function rG(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 _n(e,t,r){if(e=Ch(e),e=e.replace(XE,""),!(this instanceof _n))return new _n(e,t,r);var n,i,o,a,s,l,u=Ah.slice(),c=typeof t,d=this,f=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=Hc.parse),t=ZE(t),i=eS(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||eG.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!Dn(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=rG(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&Dn(d.protocol)&&(d.pathname="/"+d.pathname),YE(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:"&&Dn(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function nG(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||Hc.parse)(t)),n[e]=t;break;case"port":n[e]=t,YE(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<Ah.length;a++){var s=Ah[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:"&&Dn(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function iG(e){(!e||typeof e!="function")&&(e=Hc.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||Dn(r.protocol)?"//":"");return r.username?(o+=r.username,r.password&&(o+=":"+r.password),o+="@"):r.password?(o+=":"+r.password,o+="@"):r.protocol!=="file:"&&Dn(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}_n.prototype={set:nG,toString:iG};_n.extractProtocol=eS;_n.location=ZE;_n.trimLeft=Ch;_n.qs=Hc;tS.exports=_n});var oG,rS=L(()=>{"use strict";oG=ye(Eh());});function Sh(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 Kc=L(()=>{"use strict";});var Nh,Dh,_h=L(()=>{"use strict";Kc();Nh=class{features=new Map;register(t,r){let n=Sh(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()}},Dh=new Nh});var Ih=L(()=>{"use strict";});function zc(e){return aG.has(e)}var aG,hl=L(()=>{"use strict";hh();vh();Wc();pl();hh();rS();_h();Kc();Ih();aG=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var sG,nS=L(()=>{"use strict";hl();sG=ml({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 sS,Ph,Ra,No,Th,Jc,ka,ii,ke,iS,oS,aS,Zr=L(()=>{"use strict";sS={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},Ph={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"})(Ra||(Ra={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(No||(No={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(Th||(Th={}));Jc=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"})(ka||(ka={}));ii=class{static StartTag="<"},ke={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:No.Left,labelPosition:ka.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"})(iS||(iS={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(oS||(oS={}));(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"})(aS||(aS={}))});var Oh,lS=L(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(Oh||(Oh={}))});var dS,lG,uS,Oie,Rie,gl,cS,kie,xie,fS=L(()=>{"use strict";dS=ye(Eo());ze();Oa();nS();ba();Zr();po();ie();lG=ye(Ci());lS();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(uS||(uS={}));Oie={Read:Di.Read,Edit:Di.Edit,Both:Di.Both,Container:Di.Container},Rie={input:fo.Input,bound:fo.Bound,output:fo.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(gl||(gl={}));(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"})(cS||(cS={}));kie=new Set([M.Currency,M.Decimal,M.FP,M.Multiple,M.SingleLineEmail,M.SingleLinePhone,M.SingleLineText,M.SingleLineTextArea,M.SingleLineURL,M.SingleLineTickerSymbol,M.WholeNone,M.WholeDuration,M.WholeLanguage,M.WholeTimeZone,M.Enum,M.LookupSimple,M.LookupCustomer,M.LookupOwner,M.LookupPartyList,M.LookupRegarding,M.TwoOptions,M.Boolean,M.PowerBIReport,M.DateAndTimeDateAndTime,M.DateAndTimeDateOnly,M.OptionSet,M.MultiSelectOptionSet,M.CardForm]),xie={numbers:[M.WholeNone,M.FP,M.Decimal,M.Currency],text:[M.SingleLineText,M.SingleLineTextArea,M.Multiple],lookup:[M.LookupSimple,M.LookupCustomer,M.LookupOwner,M.LookupPartyList,M.LookupRegarding],dates:[M.DateAndTimeDateOnly,M.DateAndTimeDateAndTime],allFields:[M.TwoOptions,M.DateAndTimeDateOnly,M.DateAndTimeDateAndTime,M.FP,M.Decimal,M.WholeNone,M.WholeDuration,M.WholeTimeZone,M.WholeLanguage,M.LookupSimple,M.LookupCustomer,M.LookupOwner,M.LookupPartyList,M.LookupRegarding,M.Multiple,M.OptionSet,M.SingleLineText,M.SingleLineTextArea,M.SingleLineEmail,M.SingleLineURL,M.SingleLineTickerSymbol,M.SingleLinePhone]}});var en,Qc,pS=L(()=>{"use strict";en=ye(Eo());Xe();ze();Pt();Oa();po();fS();ba();ie();ft();Zr();Qc=class extends Z{constructor(t){super(A.customControl,t)}customControlId;get id(){let t=this.getProperty(y.id);return O.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new $(t.substr(1,t.length-2)):new $(t)}getParameters(){let t=new Map,r=this.getAllChildren();if(r&&r.length!==0&&r[0]){let n=r[0].getAllChildren();if(n!=null){for(let i of n)if(i&&i.getAllChildren().length>0){let o=i.getNodeName();t.get(o)?t.get(o).push(i):t.set(o,[i])}}}return t}getFormComponentValueByParameterName(t){let r=this.getParameters()?.get(_t.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===_t.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===_t.name)?.value,o={Name:i,Type:M.Grid,Columns:[]},l=this.getParameters().get(_t.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(ii.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:Qp.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===gl.dataset?o.get(_t.dataset)?.some(p=>this.getDatasetName(p)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:M.Grid}}):c.propertyType===gl.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,en.trackInfoTrace)(Bt,{eventName:`${ri}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,en.trackErrorTrace)(Bt,{eventName:`${ri}/parametersToJSON`,eventData:{message:"Custom Control Manifest Property Info not available"}},new Error(`Custom Control Manifest Property Info not available for custom control : ${this.name}.`));else(0,en.trackErrorTrace)(Bt,{eventName:`${ri}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,en.trackErrorTrace)(Bt,{eventName:`${ri}/parametersToJSON`,eventData:{message:"parameters to json failed"}},n)}return r}async parameterJSON(t,r,n,i){if(this.isDataSet(t)){let o=n,a=r.find(s=>s.key===_t.name)?.value;if(o)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${a}`);(0,en.trackErrorTrace)(Bt,{eventName:`${ri}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let o=n,a=r&&r.find(l=>l.key===y.Type),s=o&&!o.ofTypeGroup.every(l=>!Yu.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===Jn.FormComponent){let d=this.getFormComponentValueByParameterName(y.bindAttribute),f=await i.formModelService.loadLookupModel(d),p=f.lookupColumn,m=this.getLookupDataTypeFromAttributeMetadata(p);return{Name:t,Type:m,Usage:l,Static:u,Primary:c,EntityName:f.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(Jp.DefaultViewId),TargetEntityType:p.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(y.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(y.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(y.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(y.DependentAttributeType),AllowFilterOff:U.IsStrictTrue(this.getFormComponentValueByParameterName(y.AllowFilterOff)),DisableQuickFind:U.IsStrictTrue(this.getFormComponentValueByParameterName(y.DisableQuickFind)),EnableViewPicker:!U.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,en.trackErrorTrace)(Bt,{eventName:`${ri}/parameterJSON`,eventData:{message:"Missing custom control manifest lookup property info"}},l)}if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=this.getParameterValue(t),d=o.isPrimary;if(a){let p=a.value;return{Type:p,Static:u,Usage:l,Value:this.isNumberTypeProperty(o,p)&&Number(c)?Number(c):c,Primary:d}}if(o.ofType)return{Type:o.ofType,Static:u,Usage:l,Value:c,Primary:!0};if(o.ofTypeGroup)return{Static:u,Usage:l,Value:c,Primary:!0};let f=new Error(`No property type info for ${t}`);(0,en.trackErrorTrace)(Bt,{eventName:`${ri}/parameterJSON`,eventData:{message:"Missing property type info"}},f)}else{let l=new Error(`No property manifest info for ${t}`);(0,en.trackWarningTrace)(Bt,{eventName:`${ri}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case x.Customer:return M.LookupCustomer;case x.Owner:return M.LookupOwner;case x.PartyList:return M.LookupPartyList;default:return n===G.Regarding?M.LookupRegarding:M.LookupSimple}}isLookupType(t){return Yu.includes(t)}isNumberTypeProperty(t,r){return Xu.includes(r)||t.ofTypeGroup.some(n=>Xu.includes(n))}isDataSet(t){return _t.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var Q,Rh=L(()=>{"use strict";Q=class{static get CustomControl(){return"CustomControl"}static get ACIControl(){return"ACIControl"}static get ReferencePanelSearchWidget(){return"ReferencePanelSearchWidget"}static get SearchWidgetControl(){return"SearchWidgetControl"}static get SocialInsightControl(){return"SocialInsightControl"}static get NotesControl(){return"notescontrol"}static get TimerControl(){return"TimerControl"}static get MapsControl(){return"MapsControl"}static get IframeControl(){return"IframeControl"}static get WebResourceHtmlControl(){return"WebResourceHtmlControl"}static get QuickFormCollectionControl(){return"QuickFormCollectionControl"}static get QuickFormControl(){return"QuickFormControl"}static get GridControl(){return"GridControl"}static get SubGridControl(){return"SubGridControl"}static get WebResourceImageControl(){return"WebResourceImageControl"}static get TimeLineControl(){return"TimeLineControl"}static get LeadScoringControl(){return"LeadScoringControl"}}});var mS={};Ir(mS,{CustomControlUniqueId:()=>Do,DeprecatedControlClassIds:()=>V,FieldControlTypes:()=>je,mapFieldTypeToControl:()=>uG});function uG(e,t){switch(e){case x.TwoOptions:return N.BooleanControl;case x.Customer:case x.CustomerType:return N.LookupControl;case x.DateTime:return t===G.DateAndTime?N.DateTimeControl:N.DateTimeControl;case x.DecimalNumber:return N.DecimalControl;case x.FloatingPointNumber:return N.FloatingNumberControl;case x.WholeNumber:return t===G.Duration?N.DurationControl:t===G.Language?N.LanguageControl:t===G.TimeZone?N.TimezoneControl:N.IntegerControl;case x.CustomerType:case x.Lookup:case x.LookupType:return t===G.Regarding?N.RegardingControl:N.LookupControl;case x.MultipleLineofText:return t===G.Email?N.EmailBodyControl:N.TextAreaControl;case x.Currency:return N.CurrencyControl;case x.Owner:case x.OwnerType:return N.LookupControl;case x.PartyList:case x.PartyListType:return N.PartyListControl;case x.Status:case x.OptionSet:return N.ChoiceControl;case x.SingleLineofText:return t===G.Email?N.EmailAddressControl:t===G.Phone?N.PhoneNumberControl:t===G.Text?N.TextboxControl:t===G.TextArea?N.TextAreaControl:t===G.TickerSymbol?N.TickerControl:t===G.Url?N.UrlControl:t===G.PhoneticGuide?N.TextboxControl:N.TextboxControl;case x.MultiSelectOptionSet:return N.ChoicesControl;case x.Image:return N.ImageControl;case x.File:return N.FileControl;case x.State:return N.ChoiceControl;case x.Status:return N.ChoiceStatusControl;default:throw new Error(`Cannot get base control for ${e} field type`)}}var V,Do,je,yl=L(()=>{"use strict";Xe();js();ze();Pt();ba();Co();Rh();Zr();V=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"}};Do=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},je=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new $t;static initializeFieldControls(){let t=new $t,r=e.getControlName(x.SingleLineofText,G.Phone);t.add(r,new $(V.PhoneNumberControl));let n=e.getControlName(x.SingleLineofText,G.TextArea);t.add(n,new $(V.TextAreaControl));let i=e.getControlName(x.SingleLineofText,G.Text);t.add(i,new $(V.TextBoxControl));let o=e.getControlName(x.SingleLineofText,G.Email);t.add(o,new $(V.EmailAddressControl));let a=e.getControlName(x.SingleLineofText,G.Url);t.add(a,new $(V.UrlControl));let s=e.getControlName(x.SingleLineofText,G.TickerSymbol);t.add(s,new $(V.TickerControl));let l=e.getControlName(x.SingleLineofText,G.PhoneticGuide);t.add(l,new $(V.TextBoxControl));let u=e.getControlName(x.WholeNumber,G.Duration);t.add(u,new $(V.DurationControl));let c=e.getControlName(x.WholeNumber,G.Language);t.add(c,new $(V.LanguagePickerControl));let d=e.getControlName(x.WholeNumber,G.TimeZone);t.add(d,new $(V.TimeZonePicklistControl));let f=e.getControlName(x.WholeNumber,G.None);t.add(f,new $(V.IntegerControl));let p=e.getControlName(x.DateTime,G.DateOnly);t.add(p,new $(V.DateTimeControl));let m=e.getControlName(x.DateTime,G.DateAndTime);t.add(m,new $(V.DateTimeControl));let h=e.getControlName(x.LookupType,G.None);t.add(h,new $(V.LookupControl));let g=e.getControlName(x.CustomerType,G.None);t.add(g,new $(V.LookupControl));let v=e.getControlName(x.FloatingPointNumber,G.None);t.add(v,new $(V.FloatControl));let w=e.getControlName(x.DecimalNumber,G.None);t.add(w,new $(V.DecimalControl));let C=e.getControlName(x.Currency,G.None);t.add(C,new $(V.MoneyControl));let E=e.getControlName(x.MultipleLineofText,G.None);t.add(E,new $(V.TextAreaControl));let k=e.getControlName(x.MultipleLineofText,G.Text);t.add(k,new $(V.TextAreaControl));let R=e.getControlName(x.MultipleLineofText,G.TextArea);t.add(R,new $(V.TextAreaControl));let T=e.getControlName(x.MultipleLineofText,G.Email);t.add(T,new $(V.EmailBodyControl));let I=e.getControlName(x.OptionSet,G.None);t.add(I,new $(V.PicklistControl));let P=e.getControlName(x.TwoOptions,G.None);t.add(P,new $(V.RadioControl));let F=e.getControlName(x.Image,G.None);t.add(F,new $(V.WebResourceImageControl));let z=e.getControlName(x.Image,G.None);t.add(z,new $(V.WebResourceHtmlControl));let Ie=e.getControlName(x.TwoOptions,"Radio");t.add(Ie,new $(V.RadioControl));let yt=e.getControlName(x.TwoOptions,"CheckBox");t.add(yt,new $(V.CheckBoxControl));let Te=e.getControlName(x.TwoOptions,"List");t.add(Te,new $(V.PicklistControl));let Qe=e.getControlName(x.State,G.None);t.add(Qe,new $(V.PicklistControl));let ce=e.getControlName(x.Status,G.None);t.add(ce,new $(V.PicklistStatusControl));let nt=e.getControlName(x.OwnerType,G.None);t.add(nt,new $(V.LookupControl));let to=e.getControlName(x.PartyListType,G.None);t.add(to,new $(V.PartyListControl));let vt=e.getControlName(x.LookupType,G.Regarding);t.add(vt,new $(V.RegardingControl));let Un=e.getControlName(x.MultiSelectOptionSet,G.None);return t.add(Un,new $(V.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(!O.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=O.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return O.IsNullOrUndefined(t.control)||O.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===V.CustomControl}static initializeUnboundControls(){let t=new $t;return t.add(V.ACIControl,Q.ACIControl),t.add(V.IframeControl,Q.IframeControl),t.add(V.SearchWidgetControl,Q.SearchWidgetControl),t.add(V.MapsControl,Q.MapsControl),t.add(V.QuickFormCollectionControl,Q.QuickFormCollectionControl),t.add(V.GridControl,Q.SubGridControl),t.add(V.WebResourceImageControl,Q.WebResourceImageControl),t.add(V.WebResourceHtmlControl,Q.WebResourceHtmlControl),t.add(V.ReferencePanelSearchWidget,Q.SearchWidgetControl),t.add(V.ReferencePanelQuickFormCollectionControl,Q.QuickFormCollectionControl),t.add(V.ReferencePanelSubgridControl,Q.SubGridControl),t.add(V.TimerControl,Q.TimerControl),t.add(V.TimeLineControl,Q.NotesControl),t.add(V.TimeLineControlUC,Q.NotesControl),t.add(V.SocialInsightControl,Q.SocialInsightControl),t.add(Do.RelationshipAssistant,Q.CustomControl),t}static initializeReferencePanelControls(){let t=new $t;return t.add(V.IframeControl,Q.IframeControl),t.add(V.ReferencePanelSearchWidget,Q.SearchWidgetControl),t.add(V.ReferencePanelQuickFormCollectionControl,Q.QuickFormCollectionControl),t.add(V.ReferencePanelSubgridControl,Q.SubGridControl),t.add(V.WebResourceHtmlControl,Q.WebResourceHtmlControl),t.add(V.WebResourceImageControl,Q.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new va;return t.add(Ra.IFRAME,!0),t.add(Ra.SPACER,!0),t.add(Ra.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(O.IsNullOrUndefined(t)||O.IsNullOrUndefined(t.control)||O.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!O.IsNullOrUndefined(t)&&!O.IsNullOrUndefined(t.Name)&&t.Name.indexOf(ke.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return O.IsNullOrUndefined(t)||O.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=U.EmptyString;if(O.IsNullOrUndefined(t)||O.IsNullOrUndefined(t.control)||O.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return O.IsNullOrUndefined(t)||O.IsNullOrUndefined(t.guidString)?U.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===V.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===V.CustomControl&&!O.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case Q.IframeControl:case Q.ACIControl:case Q.SocialInsightControl:return 6;case Q.SubGridControl:case Q.CustomControl:return 4;case Q.WebResourceImageControl:return 15;case Q.WebResourceHtmlControl:return 15;case Q.MapsControl:return 8;case Q.SearchWidgetControl:return 10;case Q.NotesControl:case Q.TimeLineControl:return 15;case Q.TimerControl:return 2;default:}}static isLookUpControl(t){return!O.IsNullOrUndefined(t)&&t.ClassId.guidString===V.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!O.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!O.IsNullOrUndefined(t)&&(t.guidString===Do.RelationshipAssistant||t.guidString===Do.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!O.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!O.IsNullOrUndefined(t)&&t.guidString===Do.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(O.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===V.CustomControl&&!O.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var Yc,hS=L(()=>{"use strict";Yc=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 _o,xa,gS,yS,$i,vS,bS,kh=L(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(_o||(_o={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(xa||(xa={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(gS||(gS={}));(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"})(yS||(yS={}));(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"})($i||($i={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(vS||(vS={}));(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"})(bS||(bS={}))});var La,wS=L(()=>{"use strict";hl();La=bh({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 AS(e){return{...e,extractConfig:t=>cG(t,Object.keys(e.fallback))}}function cG(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var xh=L(()=>{"use strict";});var Lh=b((soe,ES)=>{var vl=new Proxy(function(){return vl},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:vl},apply:function(){return vl},construct:function(){return{}}}),CS=function(){return vl};Object.setPrototypeOf(CS,vl);ES.exports=CS});var DS=b((loe,NS)=>{var bl=new Proxy(function(){return bl},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:bl},apply:function(){return bl},construct:function(){return{}}}),SS=function(){return bl};Object.setPrototypeOf(SS,bl);NS.exports=SS});var Fh=b((uoe,IS)=>{var wl=new Proxy(function(){return wl},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:wl},apply:function(){return wl},construct:function(){return{}}}),_S=function(){return wl};Object.setPrototypeOf(_S,wl);IS.exports=_S});var PS=b((coe,TS)=>{function dG(){this.__data__=[],this.size=0}TS.exports=dG});var Fa=b((doe,OS)=>{function fG(e,t){return e===t||e!==e&&t!==t}OS.exports=fG});var Al=b((foe,RS)=>{var pG=Fa();function mG(e,t){for(var r=e.length;r--;)if(pG(e[r][0],t))return r;return-1}RS.exports=mG});var xS=b((poe,kS)=>{var hG=Al(),gG=Array.prototype,yG=gG.splice;function vG(e){var t=this.__data__,r=hG(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():yG.call(t,r,1),--this.size,!0}kS.exports=vG});var FS=b((moe,LS)=>{var bG=Al();function wG(e){var t=this.__data__,r=bG(t,e);return r<0?void 0:t[r][1]}LS.exports=wG});var $S=b((hoe,MS)=>{var AG=Al();function CG(e){return AG(this.__data__,e)>-1}MS.exports=CG});var US=b((goe,BS)=>{var EG=Al();function SG(e,t){var r=this.__data__,n=EG(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}BS.exports=SG});var Cl=b((yoe,qS)=>{var NG=PS(),DG=xS(),_G=FS(),IG=$S(),TG=US();function Ma(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])}}Ma.prototype.clear=NG;Ma.prototype.delete=DG;Ma.prototype.get=_G;Ma.prototype.has=IG;Ma.prototype.set=TG;qS.exports=Ma});var GS=b((voe,VS)=>{var PG=Cl();function OG(){this.__data__=new PG,this.size=0}VS.exports=OG});var zS=b((boe,WS)=>{function RG(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}WS.exports=RG});var HS=b((woe,jS)=>{function kG(e){return this.__data__.get(e)}jS.exports=kG});var JS=b((Aoe,KS)=>{function xG(e){return this.__data__.has(e)}KS.exports=xG});var Mh=b((Coe,QS)=>{var LG=typeof global=="object"&&global&&global.Object===Object&&global;QS.exports=LG});var tn=b((Eoe,YS)=>{var FG=Mh(),MG=typeof self=="object"&&self&&self.Object===Object&&self,$G=FG||MG||Function("return this")();YS.exports=$G});var El=b((Soe,XS)=>{var BG=tn(),UG=BG.Symbol;XS.exports=UG});var rN=b((Noe,tN)=>{var ZS=El(),eN=Object.prototype,qG=eN.hasOwnProperty,VG=eN.toString,Sl=ZS?ZS.toStringTag:void 0;function GG(e){var t=qG.call(e,Sl),r=e[Sl];try{e[Sl]=void 0;var n=!0}catch{}var i=VG.call(e);return n&&(t?e[Sl]=r:delete e[Sl]),i}tN.exports=GG});var iN=b((Doe,nN)=>{var WG=Object.prototype,zG=WG.toString;function jG(e){return zG.call(e)}nN.exports=jG});var Io=b((_oe,sN)=>{var oN=El(),HG=rN(),KG=iN(),JG="[object Null]",QG="[object Undefined]",aN=oN?oN.toStringTag:void 0;function YG(e){return e==null?e===void 0?QG:JG:aN&&aN in Object(e)?HG(e):KG(e)}sN.exports=YG});var oi=b((Ioe,lN)=>{function XG(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}lN.exports=XG});var Xc=b((Toe,uN)=>{var ZG=Io(),e9=oi(),t9="[object AsyncFunction]",r9="[object Function]",n9="[object GeneratorFunction]",i9="[object Proxy]";function o9(e){if(!e9(e))return!1;var t=ZG(e);return t==r9||t==n9||t==t9||t==i9}uN.exports=o9});var dN=b((Poe,cN)=>{var a9=tn(),s9=a9["__core-js_shared__"];cN.exports=s9});var mN=b((Ooe,pN)=>{var $h=dN(),fN=(function(){var e=/[^.]+$/.exec($h&&$h.keys&&$h.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function l9(e){return!!fN&&fN in e}pN.exports=l9});var Bh=b((Roe,hN)=>{var u9=Function.prototype,c9=u9.toString;function d9(e){if(e!=null){try{return c9.call(e)}catch{}try{return e+""}catch{}}return""}hN.exports=d9});var yN=b((koe,gN)=>{var f9=Xc(),p9=mN(),m9=oi(),h9=Bh(),g9=/[\\^$.*+?()[\]{}|]/g,y9=/^\[object .+?Constructor\]$/,v9=Function.prototype,b9=Object.prototype,w9=v9.toString,A9=b9.hasOwnProperty,C9=RegExp("^"+w9.call(A9).replace(g9,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function E9(e){if(!m9(e)||p9(e))return!1;var t=f9(e)?C9:y9;return t.test(h9(e))}gN.exports=E9});var bN=b((xoe,vN)=>{function S9(e,t){return e?.[t]}vN.exports=S9});var Bi=b((Loe,wN)=>{var N9=yN(),D9=bN();function _9(e,t){var r=D9(e,t);return N9(r)?r:void 0}wN.exports=_9});var Zc=b((Foe,AN)=>{var I9=Bi(),T9=tn(),P9=I9(T9,"Map");AN.exports=P9});var Nl=b((Moe,CN)=>{var O9=Bi(),R9=O9(Object,"create");CN.exports=R9});var NN=b(($oe,SN)=>{var EN=Nl();function k9(){this.__data__=EN?EN(null):{},this.size=0}SN.exports=k9});var _N=b((Boe,DN)=>{function x9(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}DN.exports=x9});var TN=b((Uoe,IN)=>{var L9=Nl(),F9="__lodash_hash_undefined__",M9=Object.prototype,$9=M9.hasOwnProperty;function B9(e){var t=this.__data__;if(L9){var r=t[e];return r===F9?void 0:r}return $9.call(t,e)?t[e]:void 0}IN.exports=B9});var ON=b((qoe,PN)=>{var U9=Nl(),q9=Object.prototype,V9=q9.hasOwnProperty;function G9(e){var t=this.__data__;return U9?t[e]!==void 0:V9.call(t,e)}PN.exports=G9});var kN=b((Voe,RN)=>{var W9=Nl(),z9="__lodash_hash_undefined__";function j9(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=W9&&t===void 0?z9:t,this}RN.exports=j9});var LN=b((Goe,xN)=>{var H9=NN(),K9=_N(),J9=TN(),Q9=ON(),Y9=kN();function $a(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])}}$a.prototype.clear=H9;$a.prototype.delete=K9;$a.prototype.get=J9;$a.prototype.has=Q9;$a.prototype.set=Y9;xN.exports=$a});var $N=b((Woe,MN)=>{var FN=LN(),X9=Cl(),Z9=Zc();function e5(){this.size=0,this.__data__={hash:new FN,map:new(Z9||X9),string:new FN}}MN.exports=e5});var UN=b((zoe,BN)=>{function t5(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}BN.exports=t5});var Dl=b((joe,qN)=>{var r5=UN();function n5(e,t){var r=e.__data__;return r5(t)?r[typeof t=="string"?"string":"hash"]:r.map}qN.exports=n5});var GN=b((Hoe,VN)=>{var i5=Dl();function o5(e){var t=i5(this,e).delete(e);return this.size-=t?1:0,t}VN.exports=o5});var zN=b((Koe,WN)=>{var a5=Dl();function s5(e){return a5(this,e).get(e)}WN.exports=s5});var HN=b((Joe,jN)=>{var l5=Dl();function u5(e){return l5(this,e).has(e)}jN.exports=u5});var JN=b((Qoe,KN)=>{var c5=Dl();function d5(e,t){var r=c5(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}KN.exports=d5});var ed=b((Yoe,QN)=>{var f5=$N(),p5=GN(),m5=zN(),h5=HN(),g5=JN();function Ba(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])}}Ba.prototype.clear=f5;Ba.prototype.delete=p5;Ba.prototype.get=m5;Ba.prototype.has=h5;Ba.prototype.set=g5;QN.exports=Ba});var XN=b((Xoe,YN)=>{var y5=Cl(),v5=Zc(),b5=ed(),w5=200;function A5(e,t){var r=this.__data__;if(r instanceof y5){var n=r.__data__;if(!v5||n.length<w5-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new b5(n)}return r.set(e,t),this.size=r.size,this}YN.exports=A5});var Uh=b((Zoe,ZN)=>{var C5=Cl(),E5=GS(),S5=zS(),N5=HS(),D5=JS(),_5=XN();function Ua(e){var t=this.__data__=new C5(e);this.size=t.size}Ua.prototype.clear=E5;Ua.prototype.delete=S5;Ua.prototype.get=N5;Ua.prototype.has=D5;Ua.prototype.set=_5;ZN.exports=Ua});var tD=b((eae,eD)=>{var I5="__lodash_hash_undefined__";function T5(e){return this.__data__.set(e,I5),this}eD.exports=T5});var nD=b((tae,rD)=>{function P5(e){return this.__data__.has(e)}rD.exports=P5});var oD=b((rae,iD)=>{var O5=ed(),R5=tD(),k5=nD();function td(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new O5;++t<r;)this.add(e[t])}td.prototype.add=td.prototype.push=R5;td.prototype.has=k5;iD.exports=td});var sD=b((nae,aD)=>{function x5(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}aD.exports=x5});var uD=b((iae,lD)=>{function L5(e,t){return e.has(t)}lD.exports=L5});var qh=b((oae,cD)=>{var F5=oD(),M5=sD(),$5=uD(),B5=1,U5=2;function q5(e,t,r,n,i,o){var a=r&B5,s=e.length,l=t.length;if(s!=l&&!(a&&l>s))return!1;var u=o.get(e),c=o.get(t);if(u&&c)return u==t&&c==e;var d=-1,f=!0,p=r&U5?new F5:void 0;for(o.set(e,t),o.set(t,e);++d<s;){var m=e[d],h=t[d];if(n)var g=a?n(h,m,d,t,e,o):n(m,h,d,e,t,o);if(g!==void 0){if(g)continue;f=!1;break}if(p){if(!M5(t,function(v,w){if(!$5(p,w)&&(m===v||i(m,v,r,n,o)))return p.push(w)})){f=!1;break}}else if(!(m===h||i(m,h,r,n,o))){f=!1;break}}return o.delete(e),o.delete(t),f}cD.exports=q5});var Vh=b((aae,dD)=>{var V5=tn(),G5=V5.Uint8Array;dD.exports=G5});var pD=b((sae,fD)=>{function W5(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}fD.exports=W5});var hD=b((lae,mD)=>{function z5(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}mD.exports=z5});var wD=b((uae,bD)=>{var gD=El(),yD=Vh(),j5=Fa(),H5=qh(),K5=pD(),J5=hD(),Q5=1,Y5=2,X5="[object Boolean]",Z5="[object Date]",e8="[object Error]",t8="[object Map]",r8="[object Number]",n8="[object RegExp]",i8="[object Set]",o8="[object String]",a8="[object Symbol]",s8="[object ArrayBuffer]",l8="[object DataView]",vD=gD?gD.prototype:void 0,Gh=vD?vD.valueOf:void 0;function u8(e,t,r,n,i,o,a){switch(r){case l8:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case s8:return!(e.byteLength!=t.byteLength||!o(new yD(e),new yD(t)));case X5:case Z5:case r8:return j5(+e,+t);case e8:return e.name==t.name&&e.message==t.message;case n8:case o8:return e==t+"";case t8:var s=K5;case i8:var l=n&Q5;if(s||(s=J5),e.size!=t.size&&!l)return!1;var u=a.get(e);if(u)return u==t;n|=Y5,a.set(e,t);var c=H5(s(e),s(t),n,i,o,a);return a.delete(e),c;case a8:if(Gh)return Gh.call(e)==Gh.call(t)}return!1}bD.exports=u8});var CD=b((cae,AD)=>{function c8(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}AD.exports=c8});var Ui=b((dae,ED)=>{var d8=Array.isArray;ED.exports=d8});var ND=b((fae,SD)=>{var f8=CD(),p8=Ui();function m8(e,t,r){var n=t(e);return p8(e)?n:f8(n,r(e))}SD.exports=m8});var _D=b((pae,DD)=>{function h8(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}DD.exports=h8});var TD=b((mae,ID)=>{function g8(){return[]}ID.exports=g8});var RD=b((hae,OD)=>{var y8=_D(),v8=TD(),b8=Object.prototype,w8=b8.propertyIsEnumerable,PD=Object.getOwnPropertySymbols,A8=PD?function(e){return e==null?[]:(e=Object(e),y8(PD(e),function(t){return w8.call(e,t)}))}:v8;OD.exports=A8});var xD=b((gae,kD)=>{function C8(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}kD.exports=C8});var qi=b((yae,LD)=>{function E8(e){return e!=null&&typeof e=="object"}LD.exports=E8});var MD=b((vae,FD)=>{var S8=Io(),N8=qi(),D8="[object Arguments]";function _8(e){return N8(e)&&S8(e)==D8}FD.exports=_8});var Wh=b((bae,UD)=>{var $D=MD(),I8=qi(),BD=Object.prototype,T8=BD.hasOwnProperty,P8=BD.propertyIsEnumerable,O8=$D((function(){return arguments})())?$D:function(e){return I8(e)&&T8.call(e,"callee")&&!P8.call(e,"callee")};UD.exports=O8});var VD=b((wae,qD)=>{function R8(){return!1}qD.exports=R8});var rd=b((_l,qa)=>{var k8=tn(),x8=VD(),zD=typeof _l=="object"&&_l&&!_l.nodeType&&_l,GD=zD&&typeof qa=="object"&&qa&&!qa.nodeType&&qa,L8=GD&&GD.exports===zD,WD=L8?k8.Buffer:void 0,F8=WD?WD.isBuffer:void 0,M8=F8||x8;qa.exports=M8});var nd=b((Aae,jD)=>{var $8=9007199254740991,B8=/^(?:0|[1-9]\d*)$/;function U8(e,t){var r=typeof e;return t=t??$8,!!t&&(r=="number"||r!="symbol"&&B8.test(e))&&e>-1&&e%1==0&&e<t}jD.exports=U8});var zh=b((Cae,HD)=>{var q8=9007199254740991;function V8(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=q8}HD.exports=V8});var JD=b((Eae,KD)=>{var G8=Io(),W8=zh(),z8=qi(),j8="[object Arguments]",H8="[object Array]",K8="[object Boolean]",J8="[object Date]",Q8="[object Error]",Y8="[object Function]",X8="[object Map]",Z8="[object Number]",eW="[object Object]",tW="[object RegExp]",rW="[object Set]",nW="[object String]",iW="[object WeakMap]",oW="[object ArrayBuffer]",aW="[object DataView]",sW="[object Float32Array]",lW="[object Float64Array]",uW="[object Int8Array]",cW="[object Int16Array]",dW="[object Int32Array]",fW="[object Uint8Array]",pW="[object Uint8ClampedArray]",mW="[object Uint16Array]",hW="[object Uint32Array]",Pe={};Pe[sW]=Pe[lW]=Pe[uW]=Pe[cW]=Pe[dW]=Pe[fW]=Pe[pW]=Pe[mW]=Pe[hW]=!0;Pe[j8]=Pe[H8]=Pe[oW]=Pe[K8]=Pe[aW]=Pe[J8]=Pe[Q8]=Pe[Y8]=Pe[X8]=Pe[Z8]=Pe[eW]=Pe[tW]=Pe[rW]=Pe[nW]=Pe[iW]=!1;function gW(e){return z8(e)&&W8(e.length)&&!!Pe[G8(e)]}KD.exports=gW});var YD=b((Sae,QD)=>{function yW(e){return function(t){return e(t)}}QD.exports=yW});var ZD=b((Il,Va)=>{var vW=Mh(),XD=typeof Il=="object"&&Il&&!Il.nodeType&&Il,Tl=XD&&typeof Va=="object"&&Va&&!Va.nodeType&&Va,bW=Tl&&Tl.exports===XD,jh=bW&&vW.process,wW=(function(){try{var e=Tl&&Tl.require&&Tl.require("util").types;return e||jh&&jh.binding&&jh.binding("util")}catch{}})();Va.exports=wW});var id=b((Nae,r_)=>{var AW=JD(),CW=YD(),e_=ZD(),t_=e_&&e_.isTypedArray,EW=t_?CW(t_):AW;r_.exports=EW});var Hh=b((Dae,n_)=>{var SW=xD(),NW=Wh(),DW=Ui(),_W=rd(),IW=nd(),TW=id(),PW=Object.prototype,OW=PW.hasOwnProperty;function RW(e,t){var r=DW(e),n=!r&&NW(e),i=!r&&!n&&_W(e),o=!r&&!n&&!i&&TW(e),a=r||n||i||o,s=a?SW(e.length,String):[],l=s.length;for(var u in e)(t||OW.call(e,u))&&!(a&&(u=="length"||i&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||IW(u,l)))&&s.push(u);return s}n_.exports=RW});var od=b((_ae,i_)=>{var kW=Object.prototype;function xW(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||kW;return e===r}i_.exports=xW});var Kh=b((Iae,o_)=>{function LW(e,t){return function(r){return e(t(r))}}o_.exports=LW});var s_=b((Tae,a_)=>{var FW=Kh(),MW=FW(Object.keys,Object);a_.exports=MW});var u_=b((Pae,l_)=>{var $W=od(),BW=s_(),UW=Object.prototype,qW=UW.hasOwnProperty;function VW(e){if(!$W(e))return BW(e);var t=[];for(var r in Object(e))qW.call(e,r)&&r!="constructor"&&t.push(r);return t}l_.exports=VW});var Pl=b((Oae,c_)=>{var GW=Xc(),WW=zh();function zW(e){return e!=null&&WW(e.length)&&!GW(e)}c_.exports=zW});var f_=b((Rae,d_)=>{var jW=Hh(),HW=u_(),KW=Pl();function JW(e){return KW(e)?jW(e):HW(e)}d_.exports=JW});var m_=b((kae,p_)=>{var QW=ND(),YW=RD(),XW=f_();function ZW(e){return QW(e,XW,YW)}p_.exports=ZW});var y_=b((xae,g_)=>{var h_=m_(),e6=1,t6=Object.prototype,r6=t6.hasOwnProperty;function n6(e,t,r,n,i,o){var a=r&e6,s=h_(e),l=s.length,u=h_(t),c=u.length;if(l!=c&&!a)return!1;for(var d=l;d--;){var f=s[d];if(!(a?f in t:r6.call(t,f)))return!1}var p=o.get(e),m=o.get(t);if(p&&m)return p==t&&m==e;var h=!0;o.set(e,t),o.set(t,e);for(var g=a;++d<l;){f=s[d];var v=e[f],w=t[f];if(n)var C=a?n(w,v,f,t,e,o):n(v,w,f,e,t,o);if(!(C===void 0?v===w||i(v,w,r,n,o):C)){h=!1;break}g||(g=f=="constructor")}if(h&&!g){var E=e.constructor,k=t.constructor;E!=k&&"constructor"in e&&"constructor"in t&&!(typeof E=="function"&&E instanceof E&&typeof k=="function"&&k instanceof k)&&(h=!1)}return o.delete(e),o.delete(t),h}g_.exports=n6});var b_=b((Lae,v_)=>{var i6=Bi(),o6=tn(),a6=i6(o6,"DataView");v_.exports=a6});var A_=b((Fae,w_)=>{var s6=Bi(),l6=tn(),u6=s6(l6,"Promise");w_.exports=u6});var E_=b((Mae,C_)=>{var c6=Bi(),d6=tn(),f6=c6(d6,"Set");C_.exports=f6});var N_=b(($ae,S_)=>{var p6=Bi(),m6=tn(),h6=p6(m6,"WeakMap");S_.exports=h6});var k_=b((Bae,R_)=>{var Jh=b_(),Qh=Zc(),Yh=A_(),Xh=E_(),Zh=N_(),O_=Io(),Ga=Bh(),D_="[object Map]",g6="[object Object]",__="[object Promise]",I_="[object Set]",T_="[object WeakMap]",P_="[object DataView]",y6=Ga(Jh),v6=Ga(Qh),b6=Ga(Yh),w6=Ga(Xh),A6=Ga(Zh),To=O_;(Jh&&To(new Jh(new ArrayBuffer(1)))!=P_||Qh&&To(new Qh)!=D_||Yh&&To(Yh.resolve())!=__||Xh&&To(new Xh)!=I_||Zh&&To(new Zh)!=T_)&&(To=function(e){var t=O_(e),r=t==g6?e.constructor:void 0,n=r?Ga(r):"";if(n)switch(n){case y6:return P_;case v6:return D_;case b6:return __;case w6:return I_;case A6:return T_}return t});R_.exports=To});var q_=b((Uae,U_)=>{var eg=Uh(),C6=qh(),E6=wD(),S6=y_(),x_=k_(),L_=Ui(),F_=rd(),N6=id(),D6=1,M_="[object Arguments]",$_="[object Array]",ad="[object Object]",_6=Object.prototype,B_=_6.hasOwnProperty;function I6(e,t,r,n,i,o){var a=L_(e),s=L_(t),l=a?$_:x_(e),u=s?$_:x_(t);l=l==M_?ad:l,u=u==M_?ad:u;var c=l==ad,d=u==ad,f=l==u;if(f&&F_(e)){if(!F_(t))return!1;a=!0,c=!1}if(f&&!c)return o||(o=new eg),a||N6(e)?C6(e,t,r,n,i,o):E6(e,t,l,r,n,i,o);if(!(r&D6)){var p=c&&B_.call(e,"__wrapped__"),m=d&&B_.call(t,"__wrapped__");if(p||m){var h=p?e.value():e,g=m?t.value():t;return o||(o=new eg),i(h,g,r,n,o)}}return f?(o||(o=new eg),S6(e,t,r,n,i,o)):!1}U_.exports=I6});var z_=b((qae,W_)=>{var T6=q_(),V_=qi();function G_(e,t,r,n,i){return e===t?!0:e==null||t==null||!V_(e)&&!V_(t)?e!==e&&t!==t:T6(e,t,r,n,G_,i)}W_.exports=G_});var H_=b((Vae,j_)=>{var P6=z_();function O6(e,t){return P6(e,t)}j_.exports=O6});var tg=b((Gae,K_)=>{var R6=Bi(),k6=(function(){try{var e=R6(Object,"defineProperty");return e({},"",{}),e}catch{}})();K_.exports=k6});var sd=b((Wae,Q_)=>{var J_=tg();function x6(e,t,r){t=="__proto__"&&J_?J_(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}Q_.exports=x6});var rg=b((zae,Y_)=>{var L6=sd(),F6=Fa();function M6(e,t,r){(r!==void 0&&!F6(e[t],r)||r===void 0&&!(t in e))&&L6(e,t,r)}Y_.exports=M6});var Z_=b((jae,X_)=>{function $6(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}}X_.exports=$6});var tI=b((Hae,eI)=>{var B6=Z_(),U6=B6();eI.exports=U6});var aI=b((Ol,Wa)=>{var q6=tn(),oI=typeof Ol=="object"&&Ol&&!Ol.nodeType&&Ol,rI=oI&&typeof Wa=="object"&&Wa&&!Wa.nodeType&&Wa,V6=rI&&rI.exports===oI,nI=V6?q6.Buffer:void 0,iI=nI?nI.allocUnsafe:void 0;function G6(e,t){if(t)return e.slice();var r=e.length,n=iI?iI(r):new e.constructor(r);return e.copy(n),n}Wa.exports=G6});var uI=b((Kae,lI)=>{var sI=Vh();function W6(e){var t=new e.constructor(e.byteLength);return new sI(t).set(new sI(e)),t}lI.exports=W6});var dI=b((Jae,cI)=>{var z6=uI();function j6(e,t){var r=t?z6(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}cI.exports=j6});var pI=b((Qae,fI)=>{function H6(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}fI.exports=H6});var gI=b((Yae,hI)=>{var K6=oi(),mI=Object.create,J6=(function(){function e(){}return function(t){if(!K6(t))return{};if(mI)return mI(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();hI.exports=J6});var ng=b((Xae,yI)=>{var Q6=Kh(),Y6=Q6(Object.getPrototypeOf,Object);yI.exports=Y6});var bI=b((Zae,vI)=>{var X6=gI(),Z6=ng(),ez=od();function tz(e){return typeof e.constructor=="function"&&!ez(e)?X6(Z6(e)):{}}vI.exports=tz});var AI=b((ese,wI)=>{var rz=Pl(),nz=qi();function iz(e){return nz(e)&&rz(e)}wI.exports=iz});var SI=b((tse,EI)=>{var oz=Io(),az=ng(),sz=qi(),lz="[object Object]",uz=Function.prototype,cz=Object.prototype,CI=uz.toString,dz=cz.hasOwnProperty,fz=CI.call(Object);function pz(e){if(!sz(e)||oz(e)!=lz)return!1;var t=az(e);if(t===null)return!0;var r=dz.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&CI.call(r)==fz}EI.exports=pz});var ig=b((rse,NI)=>{function mz(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}NI.exports=mz});var og=b((nse,DI)=>{var hz=sd(),gz=Fa(),yz=Object.prototype,vz=yz.hasOwnProperty;function bz(e,t,r){var n=e[t];(!(vz.call(e,t)&&gz(n,r))||r===void 0&&!(t in e))&&hz(e,t,r)}DI.exports=bz});var II=b((ise,_I)=>{var wz=og(),Az=sd();function Cz(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?Az(r,s,l):wz(r,s,l)}return r}_I.exports=Cz});var PI=b((ose,TI)=>{function Ez(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}TI.exports=Ez});var RI=b((ase,OI)=>{var Sz=oi(),Nz=od(),Dz=PI(),_z=Object.prototype,Iz=_z.hasOwnProperty;function Tz(e){if(!Sz(e))return Dz(e);var t=Nz(e),r=[];for(var n in e)n=="constructor"&&(t||!Iz.call(e,n))||r.push(n);return r}OI.exports=Tz});var ag=b((sse,kI)=>{var Pz=Hh(),Oz=RI(),Rz=Pl();function kz(e){return Rz(e)?Pz(e,!0):Oz(e)}kI.exports=kz});var LI=b((lse,xI)=>{var xz=II(),Lz=ag();function Fz(e){return xz(e,Lz(e))}xI.exports=Fz});var qI=b((use,UI)=>{var FI=rg(),Mz=aI(),$z=dI(),Bz=pI(),Uz=bI(),MI=Wh(),$I=Ui(),qz=AI(),Vz=rd(),Gz=Xc(),Wz=oi(),zz=SI(),jz=id(),BI=ig(),Hz=LI();function Kz(e,t,r,n,i,o,a){var s=BI(e,r),l=BI(t,r),u=a.get(l);if(u){FI(e,r,u);return}var c=o?o(s,l,r+"",e,t,a):void 0,d=c===void 0;if(d){var f=$I(l),p=!f&&Vz(l),m=!f&&!p&&jz(l);c=l,f||p||m?$I(s)?c=s:qz(s)?c=Bz(s):p?(d=!1,c=Mz(l,!0)):m?(d=!1,c=$z(l,!0)):c=[]:zz(l)||MI(l)?(c=s,MI(s)?c=Hz(s):(!Wz(s)||Gz(s))&&(c=Uz(l))):d=!1}d&&(a.set(l,c),i(c,l,n,o,a),a.delete(l)),FI(e,r,c)}UI.exports=Kz});var sg=b((cse,GI)=>{var Jz=Uh(),Qz=rg(),Yz=tI(),Xz=qI(),Zz=oi(),e7=ag(),t7=ig();function VI(e,t,r,n,i){e!==t&&Yz(t,function(o,a){if(i||(i=new Jz),Zz(o))Xz(e,t,a,r,VI,n,i);else{var s=n?n(t7(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),Qz(e,a,s)}},e7)}GI.exports=VI});var lg=b((dse,WI)=>{function r7(e){return e}WI.exports=r7});var jI=b((fse,zI)=>{function n7(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)}zI.exports=n7});var JI=b((pse,KI)=>{var i7=jI(),HI=Math.max;function o7(e,t,r){return t=HI(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,o=HI(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),i7(e,this,s)}}KI.exports=o7});var YI=b((mse,QI)=>{function a7(e){return function(){return e}}QI.exports=a7});var eT=b((hse,ZI)=>{var s7=YI(),XI=tg(),l7=lg(),u7=XI?function(e,t){return XI(e,"toString",{configurable:!0,enumerable:!1,value:s7(t),writable:!0})}:l7;ZI.exports=u7});var rT=b((gse,tT)=>{var c7=800,d7=16,f7=Date.now;function p7(e){var t=0,r=0;return function(){var n=f7(),i=d7-(n-r);if(r=n,i>0){if(++t>=c7)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}tT.exports=p7});var iT=b((yse,nT)=>{var m7=eT(),h7=rT(),g7=h7(m7);nT.exports=g7});var aT=b((vse,oT)=>{var y7=lg(),v7=JI(),b7=iT();function w7(e,t){return b7(v7(e,t,y7),e+"")}oT.exports=w7});var lT=b((bse,sT)=>{var A7=Fa(),C7=Pl(),E7=nd(),S7=oi();function N7(e,t,r){if(!S7(r))return!1;var n=typeof t;return(n=="number"?C7(r)&&E7(t,r.length):n=="string"&&t in r)?A7(r[t],e):!1}sT.exports=N7});var ug=b((wse,uT)=>{var D7=aT(),_7=lT();function I7(e){return D7(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&&_7(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})}uT.exports=I7});var dT=b((Ase,cT)=>{var T7=sg(),P7=ug(),O7=P7(function(e,t,r,n){T7(e,t,r,n)});cT.exports=O7});var $r,Rl=L(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})($r||($r={}))});function pT(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${fT.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 fT,R7,mT=L(()=>{"use strict";fT=ye(Fh()),R7=ye(Lh());});var cg,hT=L(()=>{"use strict";Wc();cg=ml({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 yT,vT,bT,wT,dg,k7,ld,gT,fg=L(()=>{"use strict";yT=ye(Lh()),vT=ye(DS()),bT=ye(Fh()),wT=ye(H_()),dg=ye(dT());Rl();mT();hT();k7=60*1e3,ld=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=$r.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"?cg.prodEcsEndpoint:cg.integrationEcsEndpoint}client=new vT.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=yT.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:[bT.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:pT(this.clientName,n,this.endpointType),...o}),this.client.requestUpdate(),this._status===$r.NotLoaded&&(this._status=$r.Initialized)}catch(s){this._status=$r.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*k7)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,dg.default)({},t.fallback,n,t.override,gT)};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,wT.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,dg.default)({},this.client.getConfig()?.config,this.clientConfigOverride,gT);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=$r.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})}},gT=(e,t)=>{if(Array.isArray(t))return t}});var CT=b((Pse,AT)=>{"use strict";var x7=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};AT.exports=x7});var pg=b((Ose,ST)=>{var kl=new Proxy(function(){return kl},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:kl},apply:function(){return kl},construct:function(){return{}}}),ET=function(){return kl};Object.setPrototypeOf(ET,kl);ST.exports=ET});var _T=b((Rse,DT)=>{var xl=new Proxy(function(){return xl},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:xl},apply:function(){return xl},construct:function(){return{}}}),NT=function(){return xl};Object.setPrototypeOf(NT,xl);DT.exports=NT});var xT=b((kse,kT)=>{"use strict";var mg=_T(),L7={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},F7={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},M7={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},OT={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},hg={};hg[mg.ForwardRef]=M7;hg[mg.Memo]=OT;function IT(e){return mg.isMemo(e)?OT:hg[e.$$typeof]||L7}var $7=Object.defineProperty,B7=Object.getOwnPropertyNames,TT=Object.getOwnPropertySymbols,U7=Object.getOwnPropertyDescriptor,q7=Object.getPrototypeOf,PT=Object.prototype;function RT(e,t,r){if(typeof t!="string"){if(PT){var n=q7(t);n&&n!==PT&&RT(e,n,r)}var i=B7(t);TT&&(i=i.concat(TT(t)));for(var o=IT(e),a=IT(t),s=0;s<i.length;++s){var l=i[s];if(!F7[l]&&!(r&&r[l])&&!(a&&a[l])&&!(o&&o[l])){var u=U7(t,l);try{$7(e,l,u)}catch{}}}}return e}kT.exports=RT});function FT(e,t,r){let[n,i]=(0,za.useState)(e.getConfig(t));return(0,za.useEffect)(()=>{if(!r?.subscribe&&e.status===$r.ConfigsLoaded)return;let o=e.subscribe(t,a=>{i(a),r?.subscribe||o.unsubscribe()});return o?.unsubscribe},[]),n}function MT(e){return function(t,r){return FT(e,t,r)}}function $T(e,t,r,n){let i=o=>{let a=FT(e,t,n),s={...o,...a};return za.default.createElement(r,{...s})};return(0,LT.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function BT(e,t,r,n){return t.reduce((i,o)=>$T(e,o,i,n),r)}function UT(e){return function(t,r,n){return $T(e,t,r,n)}}var LT,za,gg=L(()=>{"use strict";LT=ye(xT()),za=ye(pg());Rl();});var VT=b((Fse,qT)=>{var V7=sg(),G7=ug(),W7=G7(function(e,t,r){V7(e,t,r)});qT.exports=W7});var ud=b((Mse,GT)=>{var z7=Io(),j7=qi(),H7="[object Symbol]";function K7(e){return typeof e=="symbol"||j7(e)&&z7(e)==H7}GT.exports=K7});var zT=b(($se,WT)=>{var J7=Ui(),Q7=ud(),Y7=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,X7=/^\w*$/;function Z7(e,t){if(J7(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||Q7(e)?!0:X7.test(e)||!Y7.test(e)||t!=null&&e in Object(t)}WT.exports=Z7});var KT=b((Bse,HT)=>{var jT=ed(),ej="Expected a function";function yg(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(ej);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(yg.Cache||jT),r}yg.Cache=jT;HT.exports=yg});var QT=b((Use,JT)=>{var tj=KT(),rj=500;function nj(e){var t=tj(e,function(n){return r.size===rj&&r.clear(),n}),r=t.cache;return t}JT.exports=nj});var XT=b((qse,YT)=>{var ij=QT(),oj=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,aj=/\\(\\)?/g,sj=ij(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(oj,function(r,n,i,o){t.push(i?o.replace(aj,"$1"):n||r)}),t});YT.exports=sj});var e2=b((Vse,ZT)=>{function lj(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}ZT.exports=lj});var a2=b((Gse,o2)=>{var t2=El(),uj=e2(),cj=Ui(),dj=ud(),fj=1/0,r2=t2?t2.prototype:void 0,n2=r2?r2.toString:void 0;function i2(e){if(typeof e=="string")return e;if(cj(e))return uj(e,i2)+"";if(dj(e))return n2?n2.call(e):"";var t=e+"";return t=="0"&&1/e==-fj?"-0":t}o2.exports=i2});var l2=b((Wse,s2)=>{var pj=a2();function mj(e){return e==null?"":pj(e)}s2.exports=mj});var c2=b((zse,u2)=>{var hj=Ui(),gj=zT(),yj=XT(),vj=l2();function bj(e,t){return hj(e)?e:gj(e,t)?[e]:yj(vj(e))}u2.exports=bj});var f2=b((jse,d2)=>{var wj=ud(),Aj=1/0;function Cj(e){if(typeof e=="string"||wj(e))return e;var t=e+"";return t=="0"&&1/e==-Aj?"-0":t}d2.exports=Cj});var h2=b((Hse,m2)=>{var Ej=og(),Sj=c2(),Nj=nd(),p2=oi(),Dj=f2();function _j(e,t,r,n){if(!p2(e))return e;t=Sj(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var l=Dj(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=p2(c)?c:Nj(t[i+1])?[]:{})}Ej(s,l,u),s=s[l]}return e}m2.exports=_j});var y2=b((Kse,g2)=>{var Ij=h2();function Tj(e,t,r){return e==null?e:Ij(e,t,r)}g2.exports=Tj});function A2(e){let{query:t}=(0,w2.default)(window.location.href,!0);return Oj(e,t),e}function Oj(e,t){let r=Pj+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+C2,u={};if(o===r)u=s;else if(o.startsWith(l)){let c=o.substring(l.length);(0,b2.default)(u,c,s)}(0,v2.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var v2,b2,w2,C2,Pj,E2=L(()=>{"use strict";v2=ye(VT()),b2=ye(y2()),w2=ye(Eh());C2=".",Pj="ecs"+C2});function dd(e,t,r){let n=A2(new ld(e,t,r));function i(o){(0,cd.useEffect)(()=>{n.init(o)},[])}return{featuresClient:n,createFeature:kj(n),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>BT(n,o,a,s)}}function kj(e){let t=MT(e),r=UT(e);return function(i){let o=AS(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===$r.ConfigsLoaded,Dh.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>r(o,a,s),feature:o}}}var Rj,cd,vg=L(()=>{"use strict";Rj=ye(CT()),cd=ye(pg());xh();fg();Rl();gg();E2();_h();});var S2=L(()=>{"use strict";xh();fg();vg();Rl();gg();Kc();Ih();});function fd(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,ja.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,ja.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,ja.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var ja,bg=L(()=>{"use strict";ja=ye(Eo());});var mle,hle,gle,N2=L(()=>{"use strict";S2();bg();({featuresClient:mle,createFeature:hle,useFeaturesClientInitParams:gle}=dd("PowerApps-Shell-Test",fd("shell-features")))});var I2=b((vle,_2)=>{var Ll=new Proxy(function(){return Ll},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ll},apply:function(){return Ll},construct:function(){return{}}}),D2=function(){return Ll};Object.setPrototypeOf(D2,Ll);_2.exports=D2});var xj,Lj,T2=L(()=>{"use strict";dl();xj=ye(I2()),Lj=ye(Eo());});var P2=L(()=>{"use strict";N2();bg();T2();});var _le,Ha,Ile,O2=L(()=>{"use strict";P2();vg();({featuresClient:_le,createFeature:Ha,useFeaturesClientInitParams:Ile}=dd("PowerApps-MakerPortal",fd("powerapps-features")))});var R2,k2,Rle,kle,xle,Lle,wg=L(()=>{"use strict";wS();O2();({feature:R2}=Ha({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:La.enableAutoInsertionOfCellInRow}})),{feature:k2}=Ha({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:La.enableOneGridEvents}}),{feature:Rle}=Ha({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:La.disablePBIComponents}}),{feature:kle}=Ha({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:La.enableAgentResponse}}),{feature:xle,useFeature:Lle}=Ha({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:La.enableDelayedLocalizationForCustomControls}})});var F2=b((Mle,L2)=>{var Fl=new Proxy(function(){return Fl},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Fl},apply:function(){return Fl},construct:function(){return{}}}),x2=function(){return Fl};Object.setPrototypeOf(x2,Fl);L2.exports=x2});var Ot,Vi=L(()=>{"use strict";Xe();ze();Pt();yl();ie();ft();Ot=class extends Z{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(y.colspan);return O.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){O.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 $(t.substr(1,t.length-2)):new $(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 $(t.substr(1,t.length-2)):new $(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 Z(A.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){O.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(y.availableforphone,String(t))}get visible(){return this.getProcessedValue(y.visible)}set visible(t){O.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(y.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(y.showlabel)}set showlabel(t){O.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return O.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(A.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(A.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(A.formControl);if(t)return t.getParam(y.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(A.formControl);if(t)return t.getParam(y.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(A.formControl);return t?t.getParam(y.DefaultViewId):U.EmptyString}set defaultviewid(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(A.formControl);return t?t.getParam(y.DependentAttributeName):U.EmptyString}set dependentattributename(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(A.formControl);return t?t.getParam(y.DependentAttributeType):U.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(A.formControl);if(t)return t.getParam(y.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(A.formControl);if(t)return t.getParam(y.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(A.formControl);return t?t.getParam(y.FilterRelationshipName):U.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(A.formControl);return t?t.getParam(y.AvailableViewIds):U.EmptyString}set availableviewids(t){let r=this.getFirstChild(A.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(A.formControl);if(t&&t.ClassId){let r=je.getUniqueIdentifierForControl(t);return!O.IsNullOrUndefined(r)&&je.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(A.formControl);if(t){let n=je.getUniqueIdentifierForControl(t).guidString,i=n===V.GridControl||n===V.TimeLineControl||n===V.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===A.formSection||this.NodeName===A.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(A.formControl);if(t){let n=je.getUniqueIdentifierForControl(t).guidString,i=n===V.MapsControl||n===V.WebResourceHtmlControl||n===V.WebResourceImageControl||n===V.IframeControl||n===V.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(A.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(A.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var Ka,Ag=L(()=>{"use strict";Pt();ie();ft();Ka=class extends Z{constructor(t,r){super(A.dependency,t),U.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 M2,Ja,Cg=L(()=>{"use strict";ze();Ag();ie();ft();Vi();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(M2||(M2={}));Ja=class extends Ot{constructor(t,r){super(A.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(A.EventHandlers);return t&&t.length?t[0].getChildren(A.handler):[]}getAllDependencies(){let t=this.getChildren(A.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(A.formDependencies);if(O.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new Z(A.formDependencies,this)),r=this.getFirstChild(A.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new Ka(r,n.toString()))}}}});var rn,Ml=L(()=>{"use strict";Xe();js();ze();Co();ie();ft();Zr();rn=class extends Z{previewVersion;constructor(t){super(A.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 $(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 O.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new $(t))}set UniqueId(t){this.setProperty(y.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(y.isRequired)==="true"}set isRequired(t){O.IsNullOrUndefined(t)||this.setProperty(y.isRequired,String(t))}get disableMru(){return this.getParam(y.DisableMru)==="true"}set disableMru(t){O.IsNullOrUndefined(t)||this.setParameter(y.DisableMru,t)}get useMFDForCreate(){return this.getParam(y.UseMFDForCreate)==="true"}set useMFDForCreate(t){O.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(y.UseMFDForEdit)==="true"}set useMFDForEdit(t){O.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForEdit,t)}get disabled(){return this.getProperty(y.disabled)==="true"}set disabled(t){O.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 $t,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=(ii.StartTag+r).toString(),o=this.parametersNode;if(o){let a=o.findFirst(s=>s&&s.getNodeName()===t);if(a)if(n){this.deleteFirstGrandChildOfName(A.controlParameters,a);return}else{let s=a.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):a.addChild(new Z(i,a))}else n||(a=new Z(t,o),a.addChild(new Z(i,a)),o.addChild(a))}else if(!n){o=new Z("parameters",this);let a=new Z(t,o);a.addChild(new Z(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)===ii.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 $t;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()===Ze.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 Qa,Eg=L(()=>{"use strict";Pt();po();Ml();ie();ft();Qa=class extends rn{constructor(t){super(t)}get targetEntityType(){return this.getParam(y.targetEntityType)||U.EmptyString}set targetEntityType(t){this.setParameter(y.targetEntityType,t)}get viewId(){return U.StripBraces(this.getParam(y.viewId))||U.EmptyString}set viewId(t){this.setParameter(y.viewId,U.AddBraces(t))}get viewIds(){return this.getParam(y.viewIds)||U.EmptyString}set viewIds(t){this.setParameter(y.viewIds,t)}get relationshipName(){return this.getParam(y.RelationshipName)||U.EmptyString}set relationshipName(t){this.setParameter(y.RelationshipName,t)}get isUserView(){return U.IsStrictTrue(this.getParam(y.isUserView))}set isUserView(t){this.setParameter(y.isUserView,t.toString())}get enableViewPicker(){return U.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 U.IsStrictTrue(this.getParam(y.enableQuickFind))}set enableQuickFind(t){this.setParameter(y.enableQuickFind,t)}get teamTemplateId(){return U.StripBraces(this.getParam(y.teamTemplateId))||U.EmptyString}set teamTemplateId(t){this.setParameter(y.teamTemplateId,U.AddBraces(t))}get chartId(){return this.getParam(y.visualizationId)||U.EmptyString}set chartId(t){this.setParameter(y.visualizationId,t)}get enableChartPicker(){return U.IsStrictTrue(this.getParam(y.enableChartPicker))}set enableChartPicker(t){this.setParameter(y.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(y.chartGridMode)){case Mr.Chart:return Mr.Chart;case Mr.Grid:return Mr.Grid;default:return Mr.All}}set chartGridMode(t){this.setParameter(y.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=Mr.Chart:this.chartGridMode=this.enableChartPicker?Mr.All:Mr.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("<"+U.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 Z(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(_t.dataset)?n[i].getParameters().get(_t.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 Ya,Sg=L(()=>{"use strict";Pt();po();Ml();ie();Ya=class extends rn{constructor(t){super(t)}get defaultViewId(){return U.StripBraces(this.getParam(y.DefaultViewId))||U.EmptyString}set defaultViewId(t){this.setParameter(y.DefaultViewId,U.AddBraces(t))}get autoResolve(){return U.IsStrictTrue(this.getParam(y.AutoResolve))}set autoResolve(t){this.setParameter(y.AutoResolve,t)}get disableQuickFind(){return U.IsStrictTrue(this.getParam(y.DisableQuickFind))}set disableQuickFind(t){this.setParameter(y.DisableQuickFind,t)}get disableViewPicker(){return U.IsStrictTrue(this.getParam(y.DisableViewPicker))}set disableViewPicker(t){this.setParameter(y.DisableViewPicker,t)}get allowFilterOff(){return U.IsStrictTrue(this.getParam(y.AllowFilterOff))}set allowFilterOff(t){this.setParameter(y.AllowFilterOff,t)}get disableMru(){return U.IsStrictTrue(this.getParam(y.DisableMru))}set disableMru(t){this.setParameter(y.DisableMru,t)}get dependentAttributeName(){return this.getParam(y.DependentAttributeName)||U.EmptyString}set dependentAttributeName(t){this.setParameter(y.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(y.DependentAttributeType)||U.EmptyString}set dependentAttributeType(t){this.setParameter(y.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(y.FilterRelationshipName)||U.EmptyString}set filterRelationshipName(t){this.setParameter(y.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(y.AvailableViewIds)||U.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("<"+U.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(_t.value)?n[i].getParameters().get(_t.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 $2,Ng,nr,$l=L(()=>{"use strict";$2=ye(F2());Vi();ie();ze();Xe();Cg();Ml();yl();Rh();ph();Zr();Co();Oa();Eg();Sg();Dg();ba();Ng="_",nr=class e extends Ot{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(A.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,O.IsNullOrUndefined(this.getProperty(y.id))&&(this.id=new $($.NewGuid()))}addControl(t,r,n,i,o,a,s){n instanceof rn?this.addChild(n):n instanceof $&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,o,a,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!O.IsNullOrUndefined(this.control))return O.IsNullOrUndefined(this.control.dataFieldName)?O.IsNullOrUndefined(this.control.id)?!0:!So.dependencyFieldCount.containsKey(this.control.id):!So.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new Ja(this,ul.onLoad))}get dependencies(){let t=this.getChildren(A.formEvents);for(let r of t){let n=r.getChildren(A.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let o;if(i&&Bc[i])o=Bc[i].replace(/ /g,Ng)+Ng;else{o="Control_";let u=new Error("Control class id does not exist or is undefined");(0,$2.trackErrorTrace)(Bt,{eventName:`${FE}/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===Br.Grid?(l=new Qa(this),l.indicationOfSubgrid=!0):o===Br.Lookup?l=new Ya(this):l=new rn(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,!O.IsNullOrUndefined(s)&&(l.UniqueId=s),!a&&r)this.getUnboundControlProperties(l);else{let d=je.getUniqueIdentifierForControl(l);O.IsNullOrUndefined(d)||(je.getControlDataTypeByControlOrUniqueId(d)===Q.QuickFormCollectionControl||!je.isUnboundFormControlByIdentifier(d)?o!==Br.Grid&&a&&u!==N.IframeControl&&u!==N.SubgridControl&&u!==N.ReferencePanelSubgridControl&&(l.dataFieldName=a,e.prototype.setProperty.call(l,y.disabled,"false")):(this.rowspan=je.GetRowSpan(l),(je.getControlDataTypeByControlOrUniqueId(d)===Q.NotesControl||je.getControlDataTypeByControlOrUniqueId(d)===Q.TimeLineControl)&&(e.prototype.setProperty.call(l,y.disabled,"false"),l.id=Q.NotesControl)),(je.getUnboundControlNameFromIdentifier(n)===Q.SubGridControl||je.getUnboundControlNameFromIdentifier(n)===Q.NotesControl||je.getUnboundControlNameFromIdentifier(n)===Q.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(O.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()===A.dependency&&s?r.push(s):this.buildDependencyList(a,r)}}}get control(){return this.getFirstChild(A.formControl)}set rowspan(t){this.setProperty(y.rowspan,String(t))}get rowspan(){let t=this.getProperty(y.rowspan);return O.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(Ph.ONE_COLUMN),n=Number(Ph.FOUR_COLUMN);O.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(y.colspan,String(t))}get colspan(){let t=this.getProperty(y.colspan);return O.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(A.formRow)}getParentSection(){return this.getAncestor(A.formSection)}getParentTab(){return this.getAncestor(A.formTab)}getParentForm(){return this.getAncestor(A.form)}isInHeader(){let t=this.getAncestor(A.formHeader);return!O.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(A.formFooter);return!O.IsNullOrUndefined(t)}isEmpty(){return O.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(A.formHeader):this.isInFooter()?this.getAncestor(A.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 O.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 O.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case Fe.TWO_COLUMN:r="11";break;case Fe.THREE_COLUMN:r="111";break;case Fe.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(!O.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();O.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===_i.ApplicationRequired||a===_i.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?_i.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??_i.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()===A.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()===A.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)===Ng&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var Xa,_g=L(()=>{"use strict";Pt();ie();ft();Xa=class extends Z{isInternal;constructor(t,r,n,i){super(A.library,t),this.isInternal=!!i,U.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 Po,Ig=L(()=>{"use strict";ze();$l();ie();ft();Po=class extends Z{isRowAddedOnDragOver;constructor(t){super(A.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 O.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return O.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(A.formSection)}insertPaddingCellAtIndex(t){let r=new nr(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(A.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 Fj(e){switch(e){case No.Left:return _o.Left;case No.Right:return _o.Right;case No.Center:return _o.Center;default:return _o.Left}}function Mj(e){switch(e){case ka.Left:return xa.Left;case ka.Top:return xa.Top;default:return xa.Left}}function B2(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var $j,In,Bl=L(()=>{"use strict";kh();Xe();ze();Pt();wg();$l();ie();Zr();Vi();Ig();$j=115,In=class e extends Ot{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=Fe.ONE_COLUMN;break;case 11:t=Fe.TWO_COLUMN;break;case 111:t=Fe.THREE_COLUMN;break;case 1111:t=Fe.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=ke.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+ke.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(y.Name,r)}initializeDefaultProperties(t,r,n){if(n===Fe.REFERENCE_PANEL){this.addProperty(y.rowheight,"25");let i=`${ke.referencePanelNamePrefix}${$.NewGuid()}${ke.namePrefix}`;this.addProperty(y.Name,i)}else this.setUniqueName();if(this.addProperty(y.id,new $($.NewGuid()).guidString),this.addProperty(y.IsUserDefined,ke.IsUserDefined),this.addProperty(y.locklevel,ke.LockLevel),this.addProperty(y.showlabel,ke.ShowLabel),this.addProperty(y.showbar,ke.ShowBar),this.addProperty(y.layout,ke.Layout),this.addProperty(y.Fieldlabelalignment,ke.labelAlignment),this.addProperty(y.Fieldlabelposition,ke.labelPosition),O.IsNullOrUndefined(n))this.addProperty(y.columnName,ke.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(y.columnName,i)}this.addProperty(y.LabelWidth,ke.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case Fe.TWO_COLUMN:r="11";break;case Fe.THREE_COLUMN:r="111";break;case Fe.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 O.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(U.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new Po(null);if(this.addGrandChild(A.formRows,r),R2.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new nr(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===Fe.REFERENCE_PANEL&&(n=Fe.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(A.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(A.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(A.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(A.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(A.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(A.formRows);return t.length===0?[]:t[0].getChildren(A.formRow)}get columns(){let t=this.getProperty(y.columnName),r=O.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 B2(n)}return r}set columns(t){O.IsNullOrUndefined(t)||this.setProperty(y.columnName,String(t))}get rowHeight(){let t=this.getProperty(y.rowheight);return O.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(A.formColumn)}getParentTab(){return this.getAncestor(A.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(y.showlabel)==="true"}set showlabel(t){O.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}get fieldLabelAlignment(){let t=ke.labelAlignment,r=this.getProperty(y.Fieldlabelalignment);return O.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){O.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(y.Fieldlabelposition);return O.IsNullOrUndefined(t)?ke.labelPosition:t}set fieldLabelPosition(t){O.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(y.showbar)==="true"}set showbar(t){O.IsNullOrUndefined(t)||this.setProperty(y.showbar,String(t))}get labelwidth(){let t=+this.getProperty(y.LabelWidth);return t===0?$j:t}set labelwidth(t){O.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:Fj(this.fieldLabelAlignment),Position:Mj(this.fieldLabelPosition)},Columns:B2(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()===A.formSection){let i=n;i.Name&&!U.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!O.IsNullOrUndefined(this)&&!O.IsNullOrUndefined(this.Name)&&this.Name.indexOf(ke.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===A.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===A.formFooter||this.NodeName===A.formHeader}}});var Gi,pd=L(()=>{"use strict";ie();ft();Bl();Gi=class e extends Z{constructor(t){super(A.formColumn,t)}initializeDefaultProperties(t){this.addProperty(y.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(A.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new In(A.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(A.formSections,t,r)}initialize(t,r,n,i=Fe.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(A.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(A.formSection)}get width(){return this.getProperty(y.width)}set width(t){this.setProperty(y.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(A.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 md,U2=L(()=>{"use strict";Xe();ie();Zr();Bl();md=class extends In{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 $($.NewGuid()).guidString),this.addProperty(y.columnName,ke.columns),this.setDisplayName(r,t)}}});var hd,q2=L(()=>{"use strict";pd();ie();U2();hd=class extends Gi{addAndIntializeNavBarSection(t,r,n,i){let o=new md(A.formSection,null);return o.initializeNavArea(t,r,i),this.addGrandChildAtIndex(A.formSections,o,n),o}}});var ai,gd=L(()=>{"use strict";Xe();ze();Pt();pd();ie();ft();Vi();ai=class extends Ot{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(A.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(A.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=Le.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=Le.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=Le.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=Le.TWO_COLUMN_WIDER_RIGHT;break}t=Le.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=Le.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=Le.THREE_COLUMN_WIDER_MID;break}t=Le.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(y.Name,Mi.namePrefix+t.toString()),this.addProperty(y.id,new $($.NewGuid()).guidString),this.addProperty(y.IsUserDefined,Mi.IsUserDefined),this.addProperty(y.locklevel,Mi.LockLevel),this.addProperty(y.showlabel,Mi.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=Fe.ONE_COLUMN,o=!0,a){let s=this.getChildren(A.formColumns)[0],l=[];switch(t){case Le.ONE_COLUMN:l.push(100);break;case Le.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case Le.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case Le.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case Le.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case Le.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new Gi(s);c.initialize(u,r,n,i),this.addGrandChild(A.formColumns,c)}}initialize(t,r,n,i,o,a=Fe.ONE_COLUMN,s=!0,l){this.addChild(new Z(A.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,o,a,s,l)}get columns(){let t=this.getChildren(A.formColumns);return t.length!==1?[]:t[0].getChildren(A.formColumn)}get expanded(){return this.getProcessedValue(y.expanded)}set expanded(t){O.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(A.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(A.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(A.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()===A.formTab){let i=n;i.Name&&!U.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var Oo,Tg=L(()=>{"use strict";Xe();ie();ft();Zr();q2();gd();Oo=class extends ai{constructor(t,r,n){super(t,Le.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new $($.NewGuid())}initializeDefaultProps(){this.addChild(new Z(A.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(A.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<Jc.FIVE_COLUMN;t++){let r=new hd(this.getChildren(A.formColumns)[0]);r.initializeDefaultProperties(sS.FiveEqColumn),this.addGrandChild(A.formColumns,r)}}}});function Uj(e){switch(e){case Ze.Main:return $i.Main;case Ze.QuickCreate:return $i.QuickCreate;case Ze.QuickViewForm:return $i.Quick;case Ze.Dialog:return $i.Dialog;default:return $i.None}}function qj(e,t){if(t===Ze.Main){if(e)switch(e.toLowerCase()){case"low":return Fi.Low;case"highreadonlyvalues":return Fi.HighReadOnlyValues;default:return Fi.HighWithControls}return Fi.Low}}var vd,Bj,yd,V2=L(()=>{"use strict";hS();vd=ye(Eo());kh();ze();Pt();Oa();wg();ie();po();eh();Co();$l();ie();Vi();_g();Tg();gd();Bj="1920";yd=class e extends Ot{_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(A.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 Lc,this._metadataChangeEvent=new Yc}get FormLibraries(){let t=this.getFirstChild(A.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 nr).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 nr){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()===A.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let o=i.GetPropertyByParameter(n).replace("$webresource:",""),a=new Xa(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,vd.trackErrorTrace)(ME,{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 U.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 U.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 U.IsNullOrEmpty(this.getProperty(y.MaxWidth))?Bj: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===Ze.Main?this.setProperty(y.HeaderDensityType,t):this.formType!==Ze.Main&&this.headerDensityType&&this.removeProperty(y.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===Ze.Main||this.formType===Ze.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(A.formHeader);return t.length!==1?null:t[0]}set header(t){O.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(A.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(A.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return O.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(A.formFooter);return t.length!==1?null:t[0]}set footer(t){O.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new ai(null,t),o=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,o,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(A.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,o){let a=new ai(null,Le.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);a.initialize(Le.ONE_COLUMN,s,this.LanguageCode,r,n,o,!1),this.addGrandChildAtIndex(A.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===Mi.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(A.formTabs);return t.length!==1?[]:t[0].getChildren(A.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof Oo)return t}return null}get NavigationNode(){let t=this.getChildren(A.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(A.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(A.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(A.formTabs);if(!O.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(A.formFooter).length>0}get displayCondition(){let t=this.getChildren(A.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(A.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(A.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(A.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);O.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(A.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 nr))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 nr&&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,Jn.EditableGridControl)||k2.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,Jn.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===N.CustomControl&&this.cellHasCustomControlWithName(t,Jn.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()===A.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 Oo)){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,vd.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===Ze.Main?{HeaderDensity:qj(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:Uj(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 bd,Pg,G2=L(()=>{"use strict";Xe();ze();ie();ft();Vi();bd=class extends Ot{constructor(t){super(A.formDisplayConditions,t)}get Order(){let t=this.getProperty(y.Order);return O.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(A.formEveryOne)&&this.getChildren(A.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new Pg(this))}},Pg=class extends Z{constructor(t){super(A.formEveryOne,t)}}});var wd,W2=L(()=>{"use strict";ie();ft();wd=class extends Z{constructor(t,r){super(A.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 Za,Og=L(()=>{"use strict";ie();Bl();Za=class extends In{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(A.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 Ul,z2=L(()=>{"use strict";ie();Og();Ul=class extends Za{_customFooter;constructor(t,r){super(A.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 ql,j2=L(()=>{"use strict";ie();Og();ql=class extends Za{_customHeader;constructor(t,r){super(A.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 ir,Ro=L(()=>{"use strict";Xe();Pt();ie();Vi();ir=class e extends Ot{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(A.Titles);return t.length===0?[]:t[0].getChildren(A.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(A.Title,null);n.setProperty(y.text,t),n.setProperty(y.LCID,String(r)),this.addGrandChild(A.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 $(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||U.EmptyString,this.setProperty(y.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var Vl,H2=L(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(Vl||(Vl={}))});var Ad,K2=L(()=>{"use strict";ze();ie();Ro();H2();Ad=class extends ir{constructor(t){super(A.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 O.IsNullOrUndefined(r)?Vl.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):Vl.NavLinkIdConflict}getRelationShipItemsByArea(t){let r=this.AllRelationShipItems,n=[];for(let i of r)i.Area===t&&i.Show===!0&&n.push(i);return n}getNavBarRelationShipItemsByNavId(t){return this.AllRelationShipItems.filter(n=>n.Id===t)}getNavBarLinkItemById(t){let r=this.AllNavLinkItems.filter(n=>n.Id===t);return r.length>0?r:null}getAllActiveChildrenForGivenArea(t){let r=this.getAllChildren(),n=[];for(let i of r)i.Area===t&&i.Show&&n.push(i);return n}}});var Oe,Vj,J2,Dde,es,Rg=L(()=>{"use strict";Xe();ie();Ro();(function(e){e.Info="_NA_Info",e.Sales="_NA_SFA",e.Service="_NA_CS",e.Marketing="_NA_MA",e.InternetMarketing="_NA_IMA",e.ProcessCenter="_NA_PROC",e.Async="_NA_AO"})(Oe||(Oe={}));Vj=new Map([[Oe.Info,"Info"],[Oe.Sales,"Sales"],[Oe.Service,"Service"],[Oe.Marketing,"Marketing"],[Oe.ProcessCenter,"ProcessCenter"]]),J2=new Map([["Info",Oe.Info],["Sales",Oe.Sales],["Service",Oe.Service],["Marketing",Oe.Marketing],["ProcessCenter",Oe.ProcessCenter]]),Dde=new Map([[Oe.Info,9e3],[Oe.Sales,9200],[Oe.Service,9400],[Oe.Marketing,9600],[Oe.ProcessCenter,9800],[Oe.InternetMarketing,1e4],[Oe.Async,10200]]),es=class extends ir{constructor(t,r){super(A.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=Vj.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(A.formNavigation)}get AreaId(){return this.getProperty(y.Id)}set AreaId(t){this.setProperty(y.Id,t)}get id(){return new $(this.AreaId??"",!0)}set id(t){this.AreaId=t.guidString}async toJSON(t){return{Id:this.AreaId,Titles:[{LCID:t.langCode,Text:this.getTitle(t.langCode)}],PreviewId:this.AreaId}}}});var ts,kg=L(()=>{"use strict";ie();Ro();ts=class extends ir{constructor(t,r){super(A.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(A.formNavBarArea)}get ParentNavigation(){return this.getAncestor(A.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var Cd,Q2=L(()=>{"use strict";ze();ie();Ro();Cd=class extends ir{RelationshipNameUCIRuntime;constructor(t){super(A.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 O.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 Ed,Y2=L(()=>{"use strict";ie();Ro();Ed=class extends ir{constructor(t){super(A.formNavBarItem,t)}get Url(){return this.getProperty(y.url)}set Url(t){this.setProperty(y.url,t)}}});var Sd,X2=L(()=>{"use strict";Xe();ie();Rg();kg();Ro();Sd=class extends ir{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(A.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[Oe.Info,Oe.Sales,Oe.Service,Oe.Marketing,Oe.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let o=new Set(i.map(a=>J2.get(a.AreaId)));n=n.filter(a=>!o.has(a))}}else{let i=new ts(A.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let o=new es(A.formNavBarArea,this.navBarAreas);o.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(o)}),!0):!1}get navBar(){return this.getFirstChild(A.formNavBar)}get id(){return new $(fh,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(A.formNavBarAreas,r),this.addGrandChildAtIndex(A.formNavBarAreas,r,t))}async getNavBarAreasJSON(t){let r=[],n=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let o of this.navBarAreas.AllNavBarAreaItems)n.push(o.toJSON(t));r=await Promise.all(n)}return r}async getNavBarRelationshipItemsJSON(t){let r=[],n=[];if(this.navBar?.AllRelationShipItems){for(let i of this.navBar.AllRelationShipItems)n.push(i.toJSON(t));r=await Promise.all(n)}return r}async toJSON(t){let r=await this.getNavBarAreasJSON(t),n=await this.getNavBarRelationshipItemsJSON(t);return{NavBarAreas:{NavBarAreas:r},NavBarByRelationshipItems:n,NavBarItems:[],NavPaneIsvItems:{NavBarIsvItems:[]},ShowEmptyNavBarAreas:t.formModelService.showHiddenElements}}}});var Z2={};Ir(Z2,{ControlType:()=>Br,DeserializationService:()=>Fg,DeserializationServiceScope:()=>Lg,DeserializedFormElementNode:()=>or});var xg,or,Lg,Br,Fg,Dg=L(()=>{"use strict";xg=ye(Eo());Xe();ze();Pt();Oa();ph();Co();$E();pS();yl();V2();$l();pd();Ml();Ag();ie();ie();G2();ft();Zr();Cg();W2();z2();Eg();Sg();j2();_g();Ig();Bl();gd();K2();Rg();kg();Q2();Y2();X2();or=class extends Z{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},Lg="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(Br||(Br={}));Fg=class{lcid;constructor(t){this.lcid=t}deSerializeFormXml(t,r,n,i,o,a,s,l,u,c){if(!t)throw new Error("Formxml could not be parsed.");let d=t.getElementsByTagName("form");if(d.length!==1){let p="";throw d.length===0?p="FormXml has no form node.":p="FormXml has multiple form nodes.",(0,xg.trackErrorTrace)(Bt,{eventName:Lg,eventData:{error:p}}),new Error(p)}let f=this.createFormModel(d.item(0),r,n,i,o,a,s,l,u,c);return O.IsNullOrUndefined(f.displayCondition)&&s!==Ze.Dialog&&this.appendDefaultDisplayCondition(f),f}upsertFieldCount(t,r){let n=So.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(!O.IsNullOrUndefined(t)){let n=O.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,o,a,s,l,u,c){let d=new yd(r,n,i,o,a,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===Ze.Main&&(this.insertHeaderFooterElementProperties(A.formHeader,d,d.header),this.insertHeaderFooterElementProperties(A.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(O.IsNullOrUndefined(n)){let i=t===A.formHeader?new ql(r,!0):new Ul(r,!0);or.prototype.insertProperty.call(i,y.id,"{"+$.NewGuid()+"}"),or.prototype.insertProperty.call(i,y.Fieldlabelposition,"Top"),or.prototype.insertProperty.call(i,y.columnName,ke.MarginalControlColumns),or.prototype.insertProperty.call(i,y.LabelWidth,ke.LabelWidth),or.prototype.insertProperty.call(i,y.Fieldlabelalignment,"Left");let o=null,a=new Po(o);for(let s=0;s<i.maxColumns;s++){let l=new nr(a);or.prototype.insertProperty.call(l,y.id,"{"+$.NewGuid()+"}"),l.setDisplayName(U.EmptyString,this.lcid),or.prototype.insertProperty.call(l,y.showlabel,"false"),a.addCell(l)}i.appendRow(a),t===A.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 or(`<${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,xg.trackErrorTrace)(Bt,{eventName:Lg,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(or.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===A.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&&or.prototype.insertChild.call(t,o)}}createModelNode(t,r){switch(t.nodeName){case A.form:throw new Error("Form node shouldn't be created using this method");case A.formTab:return new ai(r);case A.formColumn:return new Gi(r);case A.formHeader:return new ql(r,!1);case A.formFooter:return new Ul(r,!1);case A.formSection:return new In(A.formSection,r);case A.formRow:return new Po(r);case A.formCell:return new nr(r);case A.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=Br.Grid;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.LookupControl}}`)o=Br.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=Br.Lookup)}return o===Br.Grid?new Qa(r):o===Br.Lookup?new Ya(r):new rn(r);case A.formEvent:return new Ja(r,U.EmptyString);case A.dependency:return this.populateDependencyTable(t),new Ka(r,U.EmptyString);case A.Handler:let a=[];return new wd(a,r);case A.formNavigation:return new Sd(t.nodeName,r);case A.formNavBarArea:return new es(t.nodeName,r);case A.formNavBarAreas:return new ts(t.nodeName,r);case A.formNavBar:return new Ad(r);case A.formNavBarByRelationshipItem:return new Cd(r);case A.formNavBarItem:return new Ed(r);case A.formDisplayConditions:return new bd(r);case A.library:return new Xa(r,U.EmptyString,U.EmptyString);case A.controlDescription:return new Uc(r);case A.customControl:return this.populateCustomControlConfigurationId(t),new Qc(r);default:return new or(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,Sn.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 $(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);je.CustomControlIdMap.upsert(l,o);break}}break}}}}});var eP={};Ir(eP,{SerializationService:()=>Mg,SerializationServiceScope:()=>Gj,SerializedFormElementNode:()=>rs});var Gj,rs,Mg,tP=L(()=>{"use strict";Pt();ft();Zr();Tg();Gj="SerializationService",rs=class extends Z{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},Mg=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=rs.prototype.fetchNodeName.call(t);if(r.charAt(0)===ii.StartTag)return U.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return U.EmptyString;let n=rs.prototype.enumerateProperties.call(t),i=rs.prototype.enumerateChildren.call(t);if(!(t instanceof Oo)){let o=`<${r}`;if(n.length!==0&&(o+=` ${this.getPropertiesString(n)}`),i.length===0)o+=" />";else{let a=U.EmptyString;for(let s of i)a+=this.serializeFormXmlNode(s);o+=`>${a}</${r}>`}return o}return U.EmptyString}getPropertiesString(t){let r=U.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${U.EscapeXml(n.value,!0)}"`}),r}}});var qg=b(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});ns.completeRecordAsStored=ns.completeLabelsAsStored=void 0;var $g=Ri(),Wj="E7A81278-8635-4D9E-8D4D-59480B391C5B",zj=new Set(["tab","section","cell"]);function nn(e){let t=[];for(let r=e.firstChild;r;r=r.nextSibling)r.nodeType===1&&t.push(r);return t}function Wi(e,t){return nn(e).find(r=>r.tagName===t)}function nP(e,t){return e.length===t.length&&e.every((r,n)=>r.tagName===t[n].tagName)}function Bg(e){let t=Wi(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===Wj:!1}function Ug(e,t){var r,n;let i=((r=Wi(e,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"";return i!==""&&i===(((n=Wi(t,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"")}function jj(e,t){if(Wi(e,"labels"))return;let r=nn(e),n=nn(t),i=n[0];if(!i||i.tagName!=="labels"||n.length!==r.length+1||!nP(r,n.slice(1)))return;let o=nn(i);if(!(o.length===0||o.some(s=>s.tagName!=="label"||!s.hasAttribute("description")||!s.hasAttribute("languagecode"))||!(e.tagName==="cell"&&Bg(e)&&Ug(e,t))&&o.some(s=>s.getAttribute("description")!=="")))return i}function Hj(e,t){let r=Kj(e.ownerDocument,t),n=nn(e)[0];n?e.insertBefore(r,n):e.appendChild(r)}function Kj(e,t){let r=e.createElement("labels");for(let n of nn(t))r.appendChild(iP(e,n));return r}function iP(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 rP(e,t){let r=Wi(e,"labels");return r?nn(r).find(n=>n.tagName==="label"&&n.getAttribute("languagecode")===String(t)):void 0}function Jj(e,t,r){if(e.tagName!=="cell"||!Bg(e)||!Ug(e,t))return!1;let n=rP(e,r),i=rP(t,r),o=i?.getAttribute("description")||"";return!n||!n.hasAttribute("description")||(n.getAttribute("description")||"")!==""||o===""?!1:(n.setAttribute("description",o),!0)}function Qj(e,t){if(e.tagName!=="cell"||!Bg(e)||!Ug(e,t))return;let r=Wi(e,"labels"),n=Wi(t,"labels");if(!r||!n)return;let i=nn(r),o=nn(n),a=f=>f.tagName==="label"&&f.hasAttribute("description")&&f.hasAttribute("languagecode");if(o.length<=i.length||!i.every(a)||!o.every(a))return;let s=new Map(i.map(f=>[f.getAttribute("languagecode")||"",f]));if(s.size!==i.length)return;let l=new Set,u=0,c=[],d=[];for(let f of o){let p=f.getAttribute("languagecode")||"";if(l.has(p))return;l.add(p);let m=s.get(p);if(!m){d.push(f);continue}if((m.getAttribute("description")||"")!==(f.getAttribute("description")||""))return;u+=1,c.push(...d.map(h=>({label:h,before:m}))),d=[]}return c.push(...d.map(f=>({label:f}))),u===i.length?c:void 0}function oP(e,t,r,n){if(e.tagName!==t.tagName)return;if(zj.has(e.tagName)){let a=jj(e,t);a&&(Hj(e,a),n.changed=!0),Jj(e,t,r)&&(n.changed=!0);let s=Qj(e,t),l=Wi(e,"labels");if(s&&l){for(let{label:u,before:c}of s){let d=iP(e.ownerDocument,u);c?l.insertBefore(d,c):l.appendChild(d)}n.changed=!0}}let i=nn(e),o=nn(t);nP(i,o)&&i.forEach((a,s)=>oP(a,o[s],r,n))}function aP(e,t,r){if(e===t)return e;let n,i;try{n=(0,$g.parseXmlRoot)(e,""),i=(0,$g.parseXmlRoot)(t,"")}catch{return e}let o={changed:!1};return oP(n,i,r,o),o.changed?(0,$g.serializeNode)(n):e}ns.completeLabelsAsStored=aP;function Yj(e,t,r){let n=e?.formxml,i=t?.formxml;if(typeof n!="string"||typeof i!="string")return e;let o=aP(n,i,r);return o===n?e:{...e,formxml:o}}ns.completeRecordAsStored=Yj});var DP=b(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.pcfReadIssues=oe.pcfBindingIssues=oe.commitPcfState=oe.mayCommitPcfState=oe.reconcilePcfDescriptions=oe.customControlNeeds=oe.mintPcfIdentity=oe.planPcfBinding=oe.projectPcfBindings=oe.supportsPcfFormType=oe.storedBindingOf=oe.hasCustomControl=oe.sameAsStored=oe.readPcfDescription=oe.newPcfDescription=oe.editorText=oe.nativeClassFor=oe.pcfEntryLayout=void 0;var Xj=(yl(),hr(mS)),Zj=X(),sP=lt(),q=fc(),eH=tm(),fe=kr(),ui=["web","phone","tablet"],Gl={web:"2",phone:"0",tablet:"1"},fP=new Map([["2","web"],["0","phone"],["1","tablet"]]),tH=["phone","web","tablet"];function Dd(e){let t=new Set(e),r=tH.filter(n=>!t.has(n));return{defaults:r.length===0?[null]:r,named:ui.filter(n=>t.has(n))}}oe.pcfEntryLayout=Dd;function Ut(e){return Array.isArray(e)?e:[]}function He(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Wl(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Gg(e){return{n:`<${e}`,a:[],c:[]}}function pP(e){return typeof e?.n=="string"&&e.n.startsWith("<")}function lP(e){let t=Ut(e.c);return t.length===1&&pP(t[0])&&(0,q.rawText)(e)!==""?(0,q.rawText)(e):void 0}function qr(e,t){return JSON.stringify(e)===JSON.stringify(t)}function mP(e){return`{${e.replace(/^\{|\}$/g,"").toUpperCase()}}`}function Wg(e){try{let t=(0,Xj.mapFieldTypeToControl)(e.attributeTypeName,e.format);return t?mP(String(t)):void 0}catch{return}}oe.nativeClassFor=Wg;var zg=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}]]),hP=new Set(["TwoOptions","Boolean"]),gP=new Set(["SingleLine.Text","SingleLine.TextArea","SingleLine.Email","SingleLine.Phone","SingleLine.URL","SingleLine.Ticker","Multiple"]),rH=new Map([...[...gP].map(e=>[e,100]),["SingleLine.TextArea",2e3],["Multiple",1048576]]),nH=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function yP(e){return nH.test(e)&&e!=="__proto__"}function jg(e){return e!==void 0&&(e==="Enum"||zg.has(e)||hP.has(e)||gP.has(e))}function vP(e){return typeof e=="number"?e:e!==""&&!Number.isNaN(Number(e))?Number(e):void 0}function zl(e,t){let r=e!==void 0?zg.get(e):void 0;if(r&&typeof t!="boolean"){let n=vP(t);if(n!==void 0)return n.toFixed(r.digits)}return typeof t=="boolean"?t?"true":"false":String(t)}oe.editorText=zl;function iH(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"&&Wl(r,a)?s=zl(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:[Gg(s)]})}return i}function bP(e,t,r,n,i){var o,a;let s=(o=n.formFactors)!==null&&o!==void 0?o:ui.filter(d=>Hg(i).has(d)),l=Dd(s),u=iH(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",Gl[d]]],c:[{n:"parameters",a:[],c:[{n:"datafieldname",a:[],c:[Gg(t)]}]}]})),...l.named.map(d=>({n:"customControl",a:[["name",n.name],["formFactor",Gl[d]]],c:[{n:"parameters",a:[],c:c(u)}]}))]}}oe.newPcfDescription=bP;function Hg(e){return new Set(ui.filter(t=>e.availableOn[t]))}function Nd(e){var t;let r=Ut(e.c);if(r.length!==1||((t=r[0])===null||t===void 0?void 0:t.n)!=="parameters"||Ut(r[0].a).length>0)return;let n=Ut(r[0].c);return n.every(i=>He(i)&&!pP(i))?n:void 0}function ko(e){let t=Ut(e?.c);if(t.length===0||!t.every(m=>He(m)&&m.n==="customControl"))return;let r=t.findIndex(m=>(0,q.rawAttr)(m,"name")!==void 0);if(r<=0)return;let n=t.slice(r),i=(0,q.rawAttr)(n[0],"name"),o=[];for(let m of n){let h=Ut(m.a),g=h.length===2?fP.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=Dd(o);if(!qr(a.named,o)||i==="")return;let s=Nd(n[0]);if(!s||!n.every(m=>qr(Nd(m),s)))return;let l=t.slice(0,r);if(l.length!==a.defaults.length)return;let u=(0,q.rawAttr)(l[0],"id"),c;for(let m=0;m<l.length;m+=1){let h=a.defaults[m],g=h===null?[["id",u??""]]:[["id",u??""],["formFactor",Gl[h]]],v=Nd(l[m]),w=v?.length===1&&v[0].n==="datafieldname"&&Ut(v[0].a).length===0?lP(v[0]):void 0;if(!u||!qr(Ut(l[m].a),g)||w===void 0||c!==void 0&&w!==c)return;c=w}let d={},f={},p;for(let m of s){let h=Ut(m.a),g=lP(m),v=h.map(w=>w[0]);if(g===void 0||!yP(m.n)||Wl(d,m.n)||m.n===p)return;if((0,q.rawAttr)(m,"static")===void 0){if(p!==void 0||g!==c||!(v.length===0||qr(v,["type"])))return;p=m.n;continue}if((0,q.rawAttr)(m,"static")!=="true"||!(qr(v,["static"])||qr(v,["type","static"])))return;d[m.n]=g,f[m.n]=(0,q.rawAttr)(m,"type")}if(!(p===void 0||c===void 0||u===void 0))return{binding:{name:i,...Object.keys(d).length>0?{parameters:d}:{},...o.length===ui.length?{}:{formFactors:o}},fieldName:c,nativeClass:u,parameterTypes:f,boundProperty:p}}oe.readPcfDescription=ko;function wP(e,t,r){return e===t?!0:typeof e!="string"&&(t===String(e)||t===zl(r,e))}function AP(e){let t=e.formFactors;return t===void 0?[...ui]:Array.isArray(t)?ui.filter(r=>t.includes(r)):[]}function Vg(e,t){var r,n,i;if(e.name!==t.binding.name||!qr(AP(e),(r=t.binding.formFactors)!==null&&r!==void 0?r:ui))return!1;let o=(n=e.parameters)!==null&&n!==void 0?n:{},a=(i=t.binding.parameters)!==null&&i!==void 0?i:{},s=Object.keys(o);return s.length!==Object.keys(a).length?!1:s.every(l=>Wl(a,l)&&wP(o[l],a[l],t.parameterTypes[l]))}oe.sameAsStored=Vg;function et(e){return He(e)&&e.customControl!==void 0}oe.hasCustomControl=et;function li(e,t){var r;return t?Ut((r=(0,q.descriptionsRegion)(e))===null||r===void 0?void 0:r.node.c).filter(n=>n?.n==="controlDescription"&&(0,q.normGuid)((0,q.rawAttr)(n,"forControl"))===t):[]}function Kg(e,t){let r=li(e.bag,(0,q.controlUniqueId)(t));return r.length===1?ko(r[0]):void 0}oe.storedBindingOf=Kg;function Jg(e){let t=(0,q.effectiveFormType)(e);return t==="Main"||t==="QuickCreate"}oe.supportsPcfFormType=Jg;function oH(e){if(!Jg(e))return;let t=(0,q.controlUniqueIds)(e);for(let{cell:r}of(0,q.typedCellSites)(e)){let n=r.control;if(!He(n)||!n.fieldName||!si(n.classId)||t.get((0,q.controlUniqueId)(n))!==1)continue;let i=Kg(e,n);i&&i.fieldName===n.fieldName&&(n.customControl=JSON.parse(JSON.stringify(i.binding)))}}oe.projectPcfBindings=oH;function si(e){return typeof e=="string"&&e.replace(/^\{|\}$/g,"").toUpperCase()===q.CUSTOM_CONTROL_CLASS_ID}var Ur=(e,t)=>({kind:"refused",rule:e,message:t});function aH(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)&&!si(e)}function uP(e,t,r){var n,i;let o=ko(r);if(!o)return Ur("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 Ur("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 Ur("pcf-binding-control-swap",`the binding uses "${o.binding.name}": to use another control, remove customControl, push, then add it`);let a=He(t.parameters)?t.parameters:{},s=(n=o.binding.parameters)!==null&&n!==void 0?n:{},l=Object.keys(a).sort();if(!qr(l,Object.keys(s).sort()))return Ur("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=>!wP(a[g],s[g],o.parameterTypes[g])),c=u.find(g=>zl(o.parameterTypes[g],a[g]).trim()==="");if(c!==void 0)return Ur("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=AP(t),f=(i=o.binding.formFactors)!==null&&i!==void 0?i:[...ui],p=d.filter(g=>!f.includes(g)),m=f.filter(g=>!d.includes(g));if(u.length===0&&p.length===0&&m.length===0)return{kind:"unchanged"};let h=u.find(g=>!jg(o.parameterTypes[g]));if(h!==void 0){let g=o.parameterTypes[h];return Ur("pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which the property editor does not write: remove the binding, push, then add it`)}return(p.length>0||m.length>0)&&!aH(o.nativeClass)?Ur("pcf-binding-edit-fallback",`the factors the control leaves fall back to "${o.nativeClass}", which is not a native control class: remove the binding, push, then add it`):{kind:"edit",description:r,stored:o,changed:u,factors:d,added:p,removed:m}}function sH(e,t){return t&&(0,q.typedCellSites)(e).find(({cell:n})=>et(n.control)&&(0,q.controlUniqueId)(n.control)===t)?{descriptions:li(e.bag,t)}:void 0}function CP(e,t){let r=new Map,n=lH(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:dH(u),uid:(0,q.controlUniqueId)(c),bound:et(c)});for(let{cell:u}of(0,q.typedCellSites)(e)){let c=u.control;He(c)&&typeof c.id=="string"&&c.id&&a(c.id).now.push({...s(u,c),control:c})}for(let{cell:u}of(0,q.typedCellSites)(t)){let c=u.control;if(!He(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(I=>I.bound&&I.uid!==""&&!n.has(I.uid));if(f.length===0||d.length===0)continue;let p=[...c],m=I=>{let P=p.findIndex(I);return P<0?void 0:p.splice(P,1)[0]},g=d.filter(I=>!I.bound||I.uid===""?!0:m(P=>P.bound&&P.uid===I.uid)!==void 0?!1:!i.has(I.uid)).filter(I=>{let P=I.cell?l(c,I.cell):void 0;return!P||!l(d,I.cell)||!p.includes(P)?!0:(p.splice(p.indexOf(P),1),f.includes(P)&&I.uid!==P.uid&&cP(I.control)&&r.set(I.control,dP(P.uid)),!1)}),v=[],w=(I,P)=>{let F=I.uid===""?void 0:m(z=>z.uid===I.uid&&(!P||z.bound===I.bound));return F&&f.includes(F)&&v.push(F),F!==void 0},E=g.filter(I=>!w(I,!0)).filter(I=>!w(I,!1)&&cP(I.control)),k=f.filter(I=>p.includes(I));if(E.length===0||k.length===0&&v.length===0)continue;let R=[...k,...v],T=k.length===1&&E.length===1&&p.length===1?dP(k[0].uid):`the controls with id "${u}" cannot all be matched to those last synced \u2014 their cells do not tell them apart \u2014 and ${R.map(I=>`{${I.uid}}`).join(", ")} no longer ${R.length===1?"names":"name"} a control: which control held ${R.length===1?"that binding":"those bindings"} is ambiguous. Re-fetch the form; to drop a bound control, remove its customControl and push before removing the control`;for(let I of E)r.set(I.control,T)}return r}function lH(e){let t=(0,q.controlUniqueIds)(e),r=new Map;for(let{cell:i}of(0,q.typedCellSites)(e)){let o=He(i.control)?(0,q.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||et(a)||o>1)&&n.add(i)}return n}function cP(e){return et(e)||e.genPage===void 0&&si((0,q.effectiveClassId)(e))}function uH(e,t){let r=o=>(0,q.typedCellSites)(o).flatMap(({cell:a,pointer:s})=>{let l=a.control;if(!He(l)||et(l)||l.genPage!==void 0||!si((0,q.effectiveClassId)(l)))return[];let u=(0,q.controlUniqueId)(l);return u===""||li(o.bag,u).length===0?[{control:l,pointer:`${s}/control`}]:[]}),n=o=>`${String(o.id)}\0${(0,q.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 cH="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 dP(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 dH(e){let t=typeof e.id=="string"?e.id.trim():"";return(0,q.normGuid)(t)||t.toLowerCase()}function jl(e,t,r,n){let i=t.customControl,o=(0,q.controlUniqueId)(t),a=li(e.bag,o),s=r?CP(e,r).get(t):void 0;if(s!==void 0)return Ur("pcf-binding-unique-id",s);let l=r?sH(r,o):void 0;if(l){let c=l.descriptions,d=c.length===1?ko(c[0]):void 0;if(d&&d.fieldName!==t.fieldName)return Ur("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&&qr(c[0],a[0]))return uP(t,i,a[0]);let f=a.length===1?ko(a[0]):void 0;return d&&f&&f.fieldName===t.fieldName&&Vg(i,d)&&Vg(i,f)?{kind:"unchanged"}:Ur("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 Ur("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");let u=uP(t,i,a[0]);return n&&(u.kind==="edit"||u.kind==="unchanged")?u.kind==="unchanged"?u:Ur("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}oe.planPcfBinding=jl;function EP(e){return e.kind==="edit"&&(e.changed.length>0||e.added.length>0)}function fH(e){let t=n=>et(n.control)&&(!n.control.id||!n.id||(0,q.authoredUniqueId)(n.control)===void 0);if(!(0,q.typedCellSites)(e).some(({cell:n})=>t(n)))return e;let r=JSON.parse(JSON.stringify(e));for(let{cell:n}of(0,q.typedCellSites)(r)){if(!t(n))continue;let i=n.control;i.id||(i.id=(0,sP.newId)()),n.id||(n.id=(0,sP.newId)()),(0,q.authoredUniqueId)(i)===void 0&&(0,q.setUniqueId)(i)}return r}oe.mintPcfIdentity=fH;function pH(e,t){let r=new Set,n=new Set;for(let{cell:i}of(0,q.typedCellSites)(e)){let o=i.control;if(!et(o)||!He(o.customControl))continue;let a=o.customControl.name;if(typeof a!="string"||a===""||typeof o.fieldName!="string"||!o.fieldName)continue;let s=jl(e,o,t,!0);s.kind==="new"?(r.add(a),n.add(o.fieldName)):EP(s)&&r.add(a)}return{controls:[...r],columns:[...n],...n.size>0&&(0,q.effectiveFormType)(e)==="QuickCreate"?{requireCreateEligibility:!0}:{}}}oe.customControlNeeds=pH;function mH(e,t,r){var n,i,o,a,s,l;let u=e.bag,c=new Map;for(let{cell:f,pointer:p}of(0,q.typedCellSites)(e)){let m=f.control;if(!et(m)||!He(m.customControl))continue;let h=(0,q.controlUniqueId)(m);h&&li(u,h).length>0&&c.set(m,{plan:jl(e,m,t,!0),pointer:`${p}/control/customControl`})}let d=(0,q.descriptionsRegion)(u);if(d&&t){let f=(0,q.controlUniqueIds)(e),p=new Set,m=new Map;for(let{cell:h}of(0,q.typedCellSites)(e)){let g=He(h.control)?(0,q.controlUniqueId)(h.control):"";g&&!m.has(g)&&m.set(g,h.control)}for(let{cell:h}of(0,q.typedCellSites)(t)){let g=h.control;if(!et(g))continue;let v=(0,q.controlUniqueId)(g),w=li(t.bag,v),C=li(u,v);if(w.length!==1||C.length!==1||!qr(w[0],C[0])||!ko(C[0]))continue;let E=m.get(v);if(E&&!et(E)){if(((n=f.get(v))!==null&&n!==void 0?n:0)>1)continue;let k=(o=(i=ko(C[0]))===null||i===void 0?void 0:i.nativeClass)!==null&&o!==void 0?o:"";E.classId=k.replace(/^\{|\}$/g,"").toUpperCase(),hH(E,"uniqueid"),p.add(v)}else!E&&!f.has(v)&&p.add(v)}p.size>0&&(d.node.c=Ut(d.node.c).filter(h=>!(h?.n==="controlDescription"&&p.has((0,q.normGuid)((0,q.rawAttr)(h,"forControl"))))))}for(let{cell:f}of(0,q.typedCellSites)(e)){let p=f.control;if(!et(p)||!He(p.customControl))continue;si(p.classId)||(p.classId=q.CUSTOM_CONTROL_CLASS_ID);let m=(0,q.controlUniqueId)(p);if(!m){if((0,q.authoredUniqueId)(p)!==void 0)continue;m=(0,q.setUniqueId)(p)}let h=c.get(p);if(h){if(h.plan.kind==="refused")throw new Zj.ValidationError("form",e.id,[(0,fe.issue)(h.pointer,h.plan.rule,h.plan.message)]);h.plan.kind==="edit"&&gH(h.plan,p.customControl);continue}let g=r?.control(p.customControl.name),v=r?.column(e.entityLogicalName,p.fieldName),w=v?.kind==="found"?Wg(v.value):void 0;if(g?.kind!=="found"||!w)continue;d||(d={i:(0,q.embedAppendIndex)(u),node:{n:"controlDescriptions",a:[],c:[]}},u.c.push(d));let C=((l=(s=Ut((a=p.bag)===null||a===void 0?void 0:a.a).find(k=>k[0]==="uniqueid"))===null||s===void 0?void 0:s[1])!==null&&l!==void 0?l:"").trim(),E=C.startsWith("{")?C:`{${m}}`;d.node.c.push(bP(E,p.fieldName,w,p.customControl,g.value))}}oe.reconcilePcfDescriptions=mH;function hH(e,t){He(e.bag)&&(e.bag.a=Ut(e.bag.a).filter(r=>r[0]!==t))}function gH(e,t){var r,n;let i=Ut(e.description.c),o=i.findIndex(g=>(0,q.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 v of(n=Nd(g))!==null&&n!==void 0?n:[])e.changed.includes(v.n)&&(v.c=[Gg(zl(e.stored.parameterTypes[v.n],l[v.n]))]);if(e.added.length===0&&e.removed.length===0)return;let u=g=>JSON.parse(JSON.stringify(g)),c=g=>{var v;let w=(0,q.rawAttr)(g,"formFactor");return w===void 0?null:(v=fP.get(w))!==null&&v!==void 0?v:null},d=(0,q.rawAttr)(a[0],"id"),f=(0,q.rawAttr)(s[0],"name"),p=Dd(e.factors),m=p.defaults.map(g=>{let v=a.find(C=>c(C)===g);if(v)return v;let w=u(a[0]);return w.a=g===null?[["id",d]]:[["id",d],["formFactor",Gl[g]]],w}),h=p.named.map(g=>{let v=s.find(C=>c(C)===g);if(v)return v;let w=u(s[0]);return w.a=[["name",f],["formFactor",Gl[g]]],w});e.description.c=[...m,...h]}function yH(e){return(0,q.typedCellSites)(e).some(({cell:t})=>et(t.control))}oe.mayCommitPcfState=yH;function vH(e,t){var r;let n=JSON.parse(JSON.stringify(e)),i=!1;for(let{cell:o}of(0,q.typedCellSites)(n)){let a=o.control;if(!et(a))continue;let s=Kg(n,a);if(!s||s.fieldName!==a.fieldName)continue;let l=t(q.CUSTOM_CONTROL_CLASS_ID),u=Ut((r=a.bag)===null||r===void 0?void 0:r.a).find(c=>c[0]==="classid");(!si(a.classId)||a.type!==l||u!==void 0&&!si(u[1])||!qr(a.customControl,s.binding))&&(si(a.classId)||(a.classId=q.CUSTOM_CONTROL_CLASS_ID),a.type=l,u&&!si(u[1])&&(u[1]=mP(q.CUSTOM_CONTROL_CLASS_ID)),a.customControl=JSON.parse(JSON.stringify(s.binding)),i=!0)}return i?n:e}oe.commitPcfState=vH;var bH=new Set(["name","parameters","formFactors"]);function wH(e,t,r){let n=[],i=(0,q.controlUniqueIds)(e);for(let{cell:o,pointer:a}of(0,q.typedCellSites)(e)){let s=o.control;et(s)&&CH(e,s,`${a}/control`,i,n,t,r?.atPush===!0)}return t&&EH(e,t,n),n}oe.pcfBindingIssues=wH;function AH(e,t,r){let n=r.length;if(!He(e))return r.push((0,fe.issue)(t,"pcf-binding-shape","customControl must be an object")),!1;for(let i of Object.keys(e))bH.has(i)||r.push((0,fe.issue)(`${t}/${i}`,"pcf-binding-unknown-key",`customControl has no "${i}"`));if((typeof e.name!="string"||e.name.trim()==="")&&r.push((0,fe.issue)(`${t}/name`,"pcf-binding-shape","name must be the control's non-empty customcontrols name")),e.parameters!==void 0)if(!He(e.parameters))r.push((0,fe.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,fe.issue)(`${t}/parameters/${i}`,"pcf-binding-shape","a parameter must be a string, a finite number or a boolean"));if(e.formFactors!==void 0){let i=e.formFactors;Array.isArray(i)&&i.length>0&&i.every(a=>typeof a=="string"&&ui.includes(a))&&new Set(i).size===i.length||r.push((0,fe.issue)(`${t}/formFactors`,"pcf-binding-shape","formFactors must be distinct 'web', 'phone' and 'tablet', at least one"))}return r.length===n}function CH(e,t,r,n,i,o,a){var s;let l=`${r}/customControl`,u=AH(t.customControl,l,i);t.fieldName||i.push((0,fe.issue)(l,"pcf-binding-unbound","a PCF binding needs a control bound to a column (fieldName)")),t.genPage!==void 0&&i.push((0,fe.issue)(l,"pcf-binding-with-genpage","a control cannot embed a page and bind a PCF control")),Jg(e)||i.push((0,fe.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,fe.issue)(`${r}/classId`,"pcf-binding-class-id","classId must be a string"));let c=(0,q.authoredUniqueId)(t),d=(0,q.controlUniqueId)(t);if(c!==void 0&&!d?i.push((0,fe.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,fe.issue)(`${r}/bag`,"pcf-binding-unique-id","another control carries the same uniqueid")),!u)return;let f=jl(e,t,o,a);f.kind==="refused"&&i.push((0,fe.issue)(l,f.rule,f.message))}function EH(e,t,r){var n;let i=new Map,o=CP(e,t);for(let{cell:l,pointer:u}of(0,q.typedCellSites)(e)){let c=He(l.control)?(0,q.controlUniqueId)(l.control):"";if(c&&!i.has(c)&&i.set(c,{control:l.control,pointer:`${u}/control`}),He(l.control)&&!et(l.control)){let d=o.get(l.control);d!==void 0&&r.push((0,fe.issue)(`${u}/control`,"pcf-binding-unique-id",d))}}let a=(0,q.controlUniqueIds)(e);for(let{cell:l}of(0,q.typedCellSites)(t)){if(!et(l.control))continue;let u=(0,q.controlUniqueId)(l.control),c=i.get(u);!c||et(c.control)||(((n=a.get(u))!==null&&n!==void 0?n:0)>1?r.push((0,fe.issue)(c.pointer,"pcf-binding-unique-id","another control carries this binding\u2019s uniqueid; removing the binding would delete its description too")):qr(li(t.bag,u),li(e.bag,u))?c.control.fieldName!==l.control.fieldName&&r.push((0,fe.issue)(c.pointer,"pcf-binding-rebind","remove the binding, push, then bind the new column")):r.push((0,fe.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 uH(e,t))s.has(l)||r.push((0,fe.issue)(l,"pcf-binding-unique-id",cH))}var SH=new Set(["Form.Card"]),NH="MscrmControls.ModelForm.ModelFormControl";function SP(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=>!yP(s));if(o!==void 0)return`the property name "${o}" cannot be written as an element`;if(t===NH||n.some(s=>s.defaultType!==void 0&&SH.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"&&!jg(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 DH(e){return e.ofType!==null?[e.ofType]:e.ofTypeGroup}function NP(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?zg.get(r):void 0;if(n){let o=typeof t=="boolean"?void 0:vP(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&&hP.has(r))return t===!0||t===!1||t==="true"||t==="false"?void 0:"must be true or false";let i=r!==void 0?rH.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 _H(e,t,r){var n,i,o,a;let s={issues:[]},l=s.issues;for(let{cell:u,pointer:c}of(0,q.typedCellSites)(e)){let d=u.control;if(!et(d)||!d.fieldName)continue;let f=d.customControl;if(!He(f)||typeof f.name!="string")continue;let p=`${c}/control/customControl`,m=jl(e,d,r,!0);if(m.kind==="edit"){EP(m)&&PH(m,f,p,t,s);continue}if(m.kind!=="new")continue;let h=t?.control(f.name),g=t?.column((n=e.entityLogicalName)!==null&&n!==void 0?n:"",d.fieldName);if(!h||h.kind==="unavailable"){(i=s.unavailable)!==null&&i!==void 0||(s.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${f.name}" could not be read`,...h?.kind==="unavailable"?{cause:h.error}:{}});continue}if(h.kind!=="found"){l.push((0,fe.issue)(`${p}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${f.name}" (${h.kind})`));continue}if(!g||g.kind==="unavailable"){(o=s.unavailable)!==null&&o!==void 0||(s.unavailable={code:"PCF_COLUMN_UNAVAILABLE",message:`the column "${d.fieldName}" could not be read`,...g?.kind==="unavailable"?{cause:g.error}:{}});continue}let v=SP(h.value,f.name);if(v){l.push((0,fe.issue)(`${p}/name`,"pcf-binding-unsupported-control",`"${f.name}" is not supported: ${v}`));continue}let w=h.value.properties.find(F=>F.isPrimary),C=g.kind==="found"?g.value:void 0,E=C?(a=(0,eH.manifestTypesForColumn)(C.attributeTypeName,C.format,C.formatName))!==null&&a!==void 0?a:[]:[];C!==void 0&&!C.isPrimaryId&&C.isValidForForm&&Wg(C)!==void 0&&DH(w).some(F=>E.includes(F))?(0,q.effectiveFormType)(e)==="QuickCreate"&&C?.isValidForCreate!==!0&&l.push((0,fe.issue)(p,"pcf-binding-quick-create-column",`"${d.fieldName}" cannot be set when a record is created, so a Quick Create form cannot bind it`)):l.push((0,fe.issue)(p,"pcf-binding-incompatible-column",`"${f.name}" cannot be bound to "${d.fieldName}"`));let R=new Map(h.value.properties.filter(F=>F.usage==="input").map(F=>[F.name,F])),T=He(f.parameters)?f.parameters:{};for(let[F,z]of Object.entries(T)){let Ie=R.get(F);if(!Ie){l.push((0,fe.issue)(`${p}/parameters/${F}`,"pcf-binding-unknown-parameter",`"${f.name}" has no input "${F}"`));continue}let yt=NP(Ie,z);yt&&l.push((0,fe.issue)(`${p}/parameters/${F}`,"pcf-binding-parameter-value",`"${F}" ${yt}`))}for(let F of R.values())F.required&&!Wl(T,F.name)&&!F.defaultValue&&l.push((0,fe.issue)(`${p}/parameters`,"pcf-binding-missing-parameter",`"${F.name}" is required`));let I=Hg(h.value),P=Array.isArray(f.formFactors)?f.formFactors:void 0;(P?P.some(F=>!I.has(F)):I.size===0)&&l.push((0,fe.issue)(`${p}/formFactors`,"pcf-binding-form-factor",`"${f.name}" is available on ${I.size===0?"no form factor":[...I].join(", ")}`))}return s}oe.pcfReadIssues=_H;function IH(e,t){return t===void 0||!jg(t)?!1:e.ofType!==null?e.ofType===t:e.ofTypeGroup.includes(t)}function TH(e,t,r){var n,i;let o=SP(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&&!Wl(s,d.name));return c?`it now requires "${c.name}", which the binding does not store`:void 0}function PH(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,fe.issue)(`${r}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${t.name}" (${u.kind})`));return}let c=TH(u.value,t.name,e.stored);if(c){l.push((0,fe.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];IH(d.get(h),g)||l.push((0,fe.issue)(`${r}/parameters/${h}`,"pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which "${t.name}" does not take for it now: remove the binding, push, then add it`))}if(l.length>f)return;let p=(s=t.parameters)!==null&&s!==void 0?s:{};for(let h of e.changed){let g=NP(d.get(h),p[h],e.stored.parameterTypes[h]);g&&l.push((0,fe.issue)(`${r}/parameters/${h}`,"pcf-binding-parameter-value",`"${h}" ${g}`))}let m=Hg(u.value);e.added.some(h=>!m.has(h))&&l.push((0,fe.issue)(`${r}/formFactors`,"pcf-binding-form-factor",`"${t.name}" is available on ${m.size===0?"no form factor":[...m].join(", ")}`))}});var VP=b(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.classIdForAttributeType=sr.QUICK_VIEW_CLASS_ID=sr.NOTES_CLASS_ID=sr.SUBGRID_CLASS_ID=sr.formRegistration=sr.FormAdapter=void 0;var ci=(Xe(),hr(TE)),_P=(ze(),hr(PE)),OH=(ft(),hr(RE)),pt=(ie(),hr(OE)),Ke=(Co(),hr(kE)),RH=(Dg(),hr(Z2)),kH=(tP(),hr(eP)),tt=Pi(),IP=Tr(),ar=kr(),xH=Lm(),os=lt(),LH=qg(),Rt=fc(),Tn=DP(),is=X(),e0=ae(),Qg=Oi(),LP=ho(),FH={[pt.FormType.Main]:"Main",[pt.FormType.QuickCreate]:"QuickCreate",[pt.FormType.QuickViewForm]:"QuickView",[pt.FormType.Card]:"Card"},_d={Main:pt.FormType.Main,QuickCreate:pt.FormType.QuickCreate,QuickView:pt.FormType.QuickViewForm,Card:pt.FormType.Card},MH=new Map(Object.entries(Ke.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function t0(e){var t;return e&&(t=MH.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function Hl(e){return e.getAllProperties().map(t=>[t.key,t.value])}function xo(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function FP(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function r0(e,t){var r,n;let i=FP(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(r=o.find(s=>xo(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return a&&(n=xo(a).get("description"))!==null&&n!==void 0?n:""}function $H(e){let t=FP(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 MP(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function Yg(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function Kl(e){return String(e??"").replace(/[{}]/g,"")}function Xg(e){return`{${Kl(e)}}`}function TP(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function Td(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,tt.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:Hl(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,tt.rawFromNode)(u)})}),{modeled:s,bag:{a:Hl(e),c:o,w:{n:a.getNodeName(),a:Hl(a),c:l}}}}function $P(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,tt.rawFromNode)(o)})}),{modeled:n,bag:{a:Hl(e),c:i}}}function PP(e,t){let{modeled:r,bag:n}=Td(e,"tabs","tab");return{tabs:r.map(i=>BH(i,t)),bag:n}}function BH(e,t){var r,n;let i=xo(e),{modeled:o,bag:a}=Td(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:r0(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:o.map(s=>UH(s,t)),bag:a}}function UH(e,t){let r=xo(e),{modeled:n,bag:i}=Td(e,"sections","section");return{width:r.get("width"),sections:n.map(o=>qH(o,t)),bag:i}}function qH(e,t){var r,n,i;let o=xo(e),{modeled:a,bag:s}=Td(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:r0(e,t),visible:o.has("visible")?o.get("visible")==="true":!0,showLabel:o.get("showlabel")==="true",columns:MP((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(l=>VH(l,t)),bag:s}}function VH(e,t){let{modeled:r,bag:n}=$P(e,"cell",!1);return{cells:r.map(i=>GH(i,t)),bag:n}}function GH(e,t){var r;let n=xo(e),{modeled:i,bag:o}=$P(e,"control",!0),a=r0(e,t),s=n.get("showlabel")==="true",l=i[0]?WH(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:TP(n.get("colspan"),1),rowspan:TP(n.get("rowspan"),1),control:l,bag:o}}function WH(e,t,r){var n,i;let o=xo(e),a=Kl((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:t0(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:r,parameters:$H(e),bag:{a:Hl(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,tt.rawFromNode)(l)}))}}}function Hi(e){return e.a.length===0&&e.c.length===0&&!e.w}function BP(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Lo(e,t){var r;let n=new Set(e.a.map(a=>a[0])),i=Hi(e),o=[];for(let a of t)if(n.has(a.key)){let s=(r=BP(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,tt.mergeAttrs)(e.a,o)}var zi=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),ji=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),OP=(e,t,r=1)=>({key:e,matches:n=>Number(n)===t,render:()=>String(t),absentDefault:String(r)});function n0(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function Zg(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>({n:(0,e0.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${e[t]}`,a:[],c:[]}]}))}}function zH(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 jH(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 i0(e,t,r){let n=e.c.findIndex(o=>o.node.n==="labels");if(n<0){if(!t||Hi(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:n0(t,r)},...a]}}if(zH(e.c[n].node,r)===t)return e;let i=jH(e.c[n].node,t,r);return{...e,c:e.c.map((o,a)=>a===n?{...o,node:i}:o)}}function HH(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 KH(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function JH(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function QH(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||Hi(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:Zg(t)}]}}if(KH(HH(e.c[r].node),t))return e;let n=Zg(t);return{...e,c:e.c.map((i,o)=>o===r?{...i,node:n}:i)}}function Pd(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,tt.spliceChildren)(e.w.c,r)};return(0,tt.spliceChildren)(e.c,[a])}let i=n(),o={n:t,a:[],c:r};return e.c.length===0?[...i,o]:(0,tt.spliceChildren)(e.c,[...i,o])}function YH(e,t){let r=e.tabs.map(n=>XH(n,t));return{n:"form",a:Lo(e.bag,[]),c:e.tabs.length===0&&Hi(e.bag)?[]:Pd(e.bag,"tabs",r,()=>[])}}function UP(e,t,r){return t&&!e.c.some(n=>n.node.n==="labels")?[n0(t,r)]:[]}function XH(e,t){let r=[zi("id",e.id),zi("name",e.name),ji("expanded",e.expanded),ji("visible",e.visible,!0)],n=e.columns.map(o=>ZH(o,t)),i=i0(e.bag,e.label,t);return{n:"tab",a:Lo(i,r),c:Pd(i,"columns",n,()=>UP(i,e.label,t))}}function ZH(e,t){let r=e.width!==void 0?[zi("width",e.width)]:[],n=e.sections.map(i=>eK(i,t));return{n:"column",a:Lo(e.bag,r),c:Pd(e.bag,"sections",n,()=>[])}}function eK(e,t){let r=[zi("id",e.id),zi("name",e.name),ji("showlabel",e.showLabel),ji("visible",e.visible,!0),{key:"columns",matches:o=>MP(o)===e.columns,render:()=>Yg(e.columns),absentDefault:Yg(1)}],n=e.rows.map(o=>tK(o,t)),i=i0(e.bag,e.label,t);return{n:"section",a:Lo(i,r),c:Pd(i,"rows",n,()=>UP(i,e.label,t))}}function tK(e,t){let r=e.cells.map(n=>rK(n,t));return{n:"row",a:Lo(e.bag,[]),c:Hi(e.bag)?r:(0,tt.assembleChildren)(e.bag,r)}}function rK(e,t){let r=e.control?e.control.showLabel:BP(e.bag,"showlabel")==="true",n=[zi("id",e.id),ji("showlabel",r),ji("visible",e.visible,!0),OP("colspan",e.colspan),OP("rowspan",e.rowspan)],i=e.control?[nK(e.control)]:[],o;if(Hi(e.bag))o=[...e.control&&e.control.label?[n0(e.control.label,t)]:[],...i];else{let a=e.control?i0(e.bag,e.control.label,t):e.bag;o=(0,tt.assembleChildren)(a,i)}return{n:"cell",a:Lo(e.bag,n),c:o}}function nK(e){let t=[zi("id",e.id),{key:"classid",matches:i=>Kl(i)===e.classId,render:()=>Xg(e.classId),absentDefault:""}];e.fieldName!==null&&t.push(zi("datafieldname",e.fieldName)),t.push(ji("disabled",e.isReadOnly)),t.push(ji("isrequired",e.isRequired));let r=e.fieldName===null?JH(e.bag,"datafieldname"):e.bag,n;return Hi(r)?n=Object.keys(e.parameters).length>0?[Zg(e.parameters)]:[]:n=(0,tt.assembleChildren)(QH(r,e.parameters),[]),{n:"control",a:Lo(r,t),c:n}}var iK={make:(e,t)=>new OH.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function RP(e,t,r,n){(0,Qg.installDomShim)();let i=aK(e,r);(0,Rt.reconcileEmbedDescriptions)(i,n),(0,Tn.reconcilePcfDescriptions)(i,n,r?.pcf);let o=(0,tt.rebuildRaw)(YH(i,t),iK,null);return new kH.SerializationService(t).serializeFormXmlNode(o)}function oK(e){return JSON.parse(JSON.stringify(e))}function aK(e,t){var r;let n=oK(e);n.bag||(n.bag=(0,tt.emptyBag)()),mK(n.bag),t&&sK(n,t);for(let i of(r=n.tabs)!==null&&r!==void 0?r:[])lK(i);return n}function sK(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";o0(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=qP(s.attributeType)))})}function kP(e){let t=[];return o0(e,r=>t.push(r)),t}function o0(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 lK(e){e.id||(e.id=ci.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)uK(t);e.bag||(e.bag=(0,tt.emptyBag)())}function uK(e){e.sections||(e.sections=[]);for(let t of e.sections)cK(t);e.bag||(e.bag=(0,tt.emptyBag)()),e.width===void 0&&Hi(e.bag)&&(e.width="100%")}function cK(e){e.id||(e.id=ci.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)dK(t);e.bag||(e.bag=(0,tt.emptyBag)())}function dK(e){e.cells||(e.cells=[]);for(let t of e.cells)fK(t);e.bag||(e.bag=(0,tt.emptyBag)())}function fK(e){(0,Rt.hasGenPage)(e.control)&&(0,Rt.applyEmbedCellDefaults)(e),e.id||(e.id=ci.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&&pK(e.control),e.bag||(e.bag=(0,tt.emptyBag)())}function pK(e){var t;(0,Rt.hasGenPage)(e)&&(0,Rt.applyEmbedControlDefaults)(e),e.id||(e.id=ci.Guid.NewGuid()),e.classId===void 0&&(e.classId=String(Ke.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":t0(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,e0.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,tt.emptyBag)())}function mK(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"&&!xP(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",Xg(ci.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!xP(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",Xg(ci.Guid.NewGuid())])}}var Id=class{constructor(t=LP.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,o;let{tabs:a,bag:s}=PP(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=FH[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:a,bag:s};return(0,Rt.projectGenPageEmbeds)(l),(0,Tn.projectPcfBindings)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:RP(t,this.lcid),formid:t.id||(0,os.newId)(),objecttypecode:t.entityLogicalName,type:_d[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:pt.FormPresentation.AirForm,formactivationstate:t.status==="Active"?pt.FormActivationState.Active:pt.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,os.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,Qg.installDomShim)();let f=_P.ScriptUtilities.ParseXml(c),p=hK(f),m=this.deserializeDocument(d,f);return gK(this.toArtifact(m,(l=u.description)!==null&&l!==void 0?l:void 0),p)}toApiPayload(t,r,n){let i=(0,Rt.genPageEmbedIssues)(t);if(i.length>0)throw new is.ValidationError("form",t.id,i);let o=(0,Tn.pcfBindingIssues)(t,r,{atPush:!0});if(o.length>0)throw new is.ValidationError("form",t.id,o);let a=(0,Tn.pcfReadIssues)(t,n?.pcf,r);if(a.unavailable)throw(0,is.attachCause)(new is.SdkError(a.unavailable.code,a.unavailable.message),a.unavailable.cause);if(a.issues.length>0)throw new is.ValidationError("form",t.id,a.issues);return{formxml:RP(t,this.lcid,n,r),name:t.name,type:_d[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 o0(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,Tn.customControlNeeds)(t,r)}}createDefault(t){var r,n,i,o,a,s,l,u,c,d,f;let p=[...(0,Rt.genPageEmbedIssues)(t),...(0,Tn.pcfBindingIssues)(t)];if(p.length>0)throw new is.ValidationError("form",t.id||"(new)",p);let m=t.tabs&&t.tabs.length>0?void 0:DK(this.lcid),h=m!==void 0?m:t.tabs.map(w=>yK(w,this.lcid)).join(""),g=this.deserialize({formxml:`<form><tabs>${h}</tabs></form>`,formid:t.id||(0,os.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:_d[(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:pt.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?pt.FormActivationState.Active:pt.FormActivationState.InActive}),v=this.toArtifact(g,t.description);if(t.tabs&&t.tabs.length>0){let w=kP(t);kP(v).forEach((C,E)=>{w[E]&&w[E].label===void 0&&delete C.label,w[E]&&w[E].genPage!==void 0&&(C.genPage=JSON.parse(JSON.stringify(w[E].genPage))),w[E]&&w[E].customControl!==void 0&&(C.customControl=JSON.parse(JSON.stringify(w[E].customControl)))})}return{id:(l=t.id)!==null&&l!==void 0?l:v.id,name:(u=t.name)!==null&&u!==void 0?u:"New Form",entityLogicalName:(c=t.entityLogicalName)!==null&&c!==void 0?c:"",formType:(d=t.formType)!==null&&d!==void 0?d:"Main",status:(f=t.status)!==null&&f!==void 0?f:"Active",...t.description!==void 0?{description:t.description}:{},tabs:v.tabs,bag:v.bag}}assignMissingIds(t){return(0,os.assignMissingIds)(t)}completeAsStored(t,r){return(0,LH.completeRecordAsStored)(t,r,this.lcid)}normalize(t){return(0,Tn.mintPcfIdentity)((0,Rt.mintEmbedIdentity)(t))}committed(t,r){var n,i,o,a,s,l;let u=r?.formxml;if(typeof u!="string"||!((0,Rt.mayCommitEmbedState)(t)||(0,Tn.mayCommitPcfState)(t)))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,os.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:_d[(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:pt.FormPresentation.AirForm,formactivationstate:pt.FormActivationState.Active}),{bag:d}=PP(c,this.lcid),f=(0,Tn.commitPcfState)((0,Rt.commitEmbedState)(t,(l=(0,Rt.descriptionsRegion)(d))===null||l===void 0?void 0:l.node),t0);return{artifact:f,baseline:f}}validate(t){return LK(t)}deserialize(t){return(0,Qg.installDomShim)(),this.deserializeDocument(t,_P.ScriptUtilities.ParseXml(t.formxml))}deserializeDocument(t,r){let n=new RH.DeserializationService(this.lcid).deSerializeFormXml(r,new ci.Guid(t.formid),t.objecttypecode,pt.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===pt.FormActivationState.InActive?"Inactive":"Active"}};sr.FormAdapter=Id;function hK(e){var t;let r=e?.getElementsByTagName("form")[0],n=new Set;for(let i=(t=r?.firstChild)!==null&&t!==void 0?t:null;i;i=i.nextSibling)i.nodeType===1&&(i.nodeName==="header"||i.nodeName==="footer")&&n.add(i.nodeName);return n}function gK(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=["header","footer"].filter(o=>!t.has(o)),i=e.bag.c.filter(o=>{var a;return n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>o.i);return i.length>0&&(e.bag.c=e.bag.c.filter(o=>{var a;return!n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>({...o,i:o.i-i.filter(a=>a<o.i).length}))),e}function on(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function a0(e,t){return e?`<labels><label description="${on(e)}" languagecode="${t}" /></labels>`:""}function s0(e){return e&&e.length>0?Kl(e):(0,os.newId)()}function yK(e,t){var r,n,i,o;let a=(r=e.columns)!==null&&r!==void 0?r:[],s=(a.length>0?a:[NK()]).map(l=>vK(l,t)).join("");return`<tab id="{${on(s0(e.id))}}" name="${on((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}">${a0(e.label,t)}<columns>${s}</columns></tab>`}function vK(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(o=>bK(o,t)).join("");return`<column width="${on((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function bK(e,t){var r,n,i,o,a;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>wK(l,t)).join("");return`<section id="{${on(s0(e.id))}}" name="${on((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="${Yg((a=e.columns)!==null&&a!==void 0?a:1)}">${a0(e.label,t)}<rows>${s}</rows></section>`}function wK(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>AK(n,t)).join("")}</row>`}function AK(e,t){var r,n,i,o,a;let s=CK(e),l=s.control,u=l?a0((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?EK(l):"";return`<cell id="{${on(s0(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 CK(e){if(!(0,Rt.hasGenPage)(e.control))return e;let t={...e.control};(0,Rt.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,Rt.applyEmbedCellDefaults)(r),r}function EK(e){var t,r,n;let i=e.fieldName?` datafieldname="${on(e.fieldName)}"`:"",o=SK(e.parameters),a=e.classId?Kl(e.classId):String(Ke.ControlClassId.TextboxControl);return`<control id="${on((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${on(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 SK(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,e0.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${on(e[n])}</${n}>`).join("")}</parameters>`)}function NK(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function DK(e){return`<tab id="{${ci.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${ci.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 _K(e=LP.DEFAULT_LCID){return{adapter:new Id(e),api:xH.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,IP.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,IP.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}sr.formRegistration=_K;var IK=new Set(["id","name","label","expanded","visible","columns","bag"]),TK=new Set(["id","width","sections","bag"]),PK=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),OK=new Set(["id","cells","bag"]),RK=new Set(["id","visible","colspan","rowspan","control","bag"]),kK=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","customControl","bag"]),xK={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 LK(e){let t=[];return(0,ar.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let o=`/tabs/${i}`;(0,ar.rejectUnknownKeys)(n,IK,o,"tab",t),(0,ar.childObjects)(n,"columns",o,"column",t).forEach(({node:s,index:l})=>{let u=`${o}/columns/${l}`;(0,ar.rejectUnknownKeys)(s,TK,u,"column",t),(0,ar.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:f})=>{let p=`${u}/sections/${f}`;(0,ar.rejectUnknownKeys)(d,PK,p,"section",t),(0,ar.childObjects)(d,"rows",p,"row",t).forEach(({node:h,index:g})=>{let v=`${p}/rows/${g}`;(0,ar.rejectUnknownKeys)(h,OK,v,"row",t),(0,ar.childObjects)(h,"cells",v,"cell",t).forEach(({node:C,index:E})=>{let k=`${v}/cells/${E}`;(0,ar.rejectUnknownKeys)(C,RK,k,"cell",t,xK);let R=C.control;R!=null&&!(0,ar.isJsonObject)(R)?t.push((0,ar.issue)(`${k}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof R}`)):(0,ar.isJsonObject)(R)&&(0,ar.rejectUnknownKeys)(R,kK,`${k}/control`,"control",t)})})})})}),t.push(...(0,Rt.genPageEmbedIssues)(e)),t.push(...(0,Tn.pcfBindingIssues)(e)),t}sr.SUBGRID_CLASS_ID=Ke.ControlClassId.SubgridControl;sr.NOTES_CLASS_ID=Ke.ControlClassId.TimelineControl;sr.QUICK_VIEW_CLASS_ID=Ke.ControlClassId.QuickViewControl;var FK={Lookup:String(Ke.ControlClassId.LookupControl),Customer:String(Ke.ControlClassId.LookupControl),Owner:String(Ke.ControlClassId.LookupControl),PartyList:String(Ke.ControlClassId.PartyListControl),Boolean:String(Ke.ControlClassId.BooleanControl),DateTime:String(Ke.ControlClassId.DateTimeControl),Decimal:String(Ke.ControlClassId.DecimalControl),Double:String(Ke.ControlClassId.FloatingNumberControl),Money:String(Ke.ControlClassId.CurrencyControl),Integer:String(Ke.ControlClassId.IntegerControl),BigInt:String(Ke.ControlClassId.IntegerControl),Memo:String(Ke.ControlClassId.TextAreaControl),String:String(Ke.ControlClassId.TextboxControl)},MK="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function qP(e){return e==="Picklist"||e==="State"||e==="Status"?MK:e&&FK[e]||String(Ke.ControlClassId.TextboxControl)}sr.classIdForAttributeType=qP;function xP(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var l0=b(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.viewApi=as.findDefaultViews=void 0;var jP=Mt(),qt=we(),an=ae(),$K=ya(),GP="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",BK="savedqueryid,name,returnedtypecode,querytype,isdefault",UK=60*1e3;function Od(e){return(e.localName||e.nodeName).toLowerCase()}function Jl(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 qK(e){if(!e)return;let t=!0,r=()=>{t=!1},n=new $K.DOMParser({errorHandler:{warning:r,error:r,fatalError:r}}).parseFromString(e,"text/xml").documentElement;return t&&n&&Od(n)==="fetch"?n:void 0}function VK(e){for(let t=e.parentNode;t;t=t.parentNode)if(Od(t)==="link-entity")return!0;return!1}function WP(e,t){var r,n,i;if(((r=e.canbedeleted)===null||r===void 0?void 0:r.Value)!==!1)return!1;let o=qK(e.fetchxml);if(!o)return!1;let a=Array.from(o.getElementsByTagName("*")),s=a.filter(u=>Od(u)==="condition"),l=s.length===1?s[0]:void 0;return l!==void 0&&a.filter(u=>Od(u)==="link-entity").every(u=>{var c;return((c=Jl(u,"link-type"))===null||c===void 0?void 0:c.toLowerCase())==="outer"})&&!VK(l)&&Jl(l,"entityname")===void 0&&((n=Jl(l,"attribute"))===null||n===void 0?void 0:n.toLowerCase())==="statecode"&&((i=Jl(l,"operator"))===null||i===void 0?void 0:i.toLowerCase())==="eq"&&Jl(l,"value")===String(t)}function GK(e,t){let r=String(e??"").trim().toLowerCase().split(/\s+/),n=String(t??"").trim().toLowerCase().split(/\s+/);return r.length===n.length&&r.filter((i,o)=>i!==n[o]).length===1}function WK(e){var t,r;let n=e.filter(a=>WP(a,0)),i=e.filter(a=>WP(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:"")))<=UK&&GK(a.name,s.name)&&o.push({active:a,inactive:s});return o.length===1?o[0]:void 0}async function zK(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,an.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,an.odataQuery)([["$select","savedqueryid,name,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,jP.collectPages)(e,a,`findDefaultViews('${t}')`),l=WK(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:"")}})}as.findDefaultViews=zK;async function jK(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,an.odataPathLiteral)(t)}')${(0,an.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 zP(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await jK(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}as.viewApi={async get(e,t){let r=(0,an.normalizeGuid)(t,"id"),n=await(0,qt.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,an.odataQuery)([["$select",GP]]);return{raw:(0,qt.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,an.normalizeGuid)(t,"id"),n=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,an.odataQuery)([["$select",GP]]),i=(0,qt.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,qt.readRowEtag)(e,"savedqueries","savedqueryid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueries${(0,an.odataQuery)([["$select",BK],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,an.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,jP.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,qt.echoWrite)("savedqueryid"),o=`/savedqueries${i.query}`,a=await zP(e,n.layoutxml,n.returnedtypecode),s=Object.freeze((0,qt.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,qt.ensureSuccess)(await(0,qt.resendDeadlockVictim)(()=>e.post(o,{...s},i.options)),e.apiUrl(o));return{id:(0,qt.resolveCreatedId)(l,"savedqueryid","view",r),etag:(0,qt.readEtag)(l)}},async update(e,t,r,n){let i=r,o=(0,an.normalizeGuid)(t,"id"),a=(0,qt.echoWrite)("savedqueryid",{"If-Match":(0,qt.requireEtag)(n,"view",o)}),s=`/savedqueries(${o})${a.query}`,l=await zP(e,i.layoutxml,i.returnedtypecode),u=(0,qt.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,qt.readEtag)(u)}},delete(e,t){return(0,qt.deleteRecord)(e,"savedqueries",t)}}});var sO=b(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.viewRegistration=ss.ViewAdapter=void 0;var ZP=X(),Er=kr(),u0=Pi(),Fo=Ri(),HP=Tr(),HK=l0(),c0=Oi(),KK=lt(),eO=100,kd=class{toArtifact(t){var r,n,i,o,a,s,l,u;(0,c0.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",f=(0,Fo.parseXmlRoot)(c,"<fetch/>"),p=(0,Fo.parseXmlRoot)(d,"<grid/>"),m=rO(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:QK(f),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:tO(p,f),filters:iO(f),sort:nO(f),...m.length>0?{linkEntities:m}:{},fetchBag:c?(0,Fo.projectElementBag)(f):void 0,layoutBag:d?(0,Fo.projectElementBag)(p):void 0}}fromArtifact(t){(0,c0.installDomShim)();let{fetchxml:r,layoutxml:n}=KP(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,c0.installDomShim)();let{fetchxml:s,layoutxml:l}=KP(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,KK.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,Er.childObjects)(n,"columns","","column",r),(0,Er.childObjects)(n,"sort","","sort",r),(0,Er.childObjects)(n,"linkEntities","","linkEntity",r),JK(n.linkEntities,r);let i=n.filters;return i!=null&&((0,Er.isJsonObject)(i)?d0(i,"/filters",r):r.push((0,Er.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};ss.ViewAdapter=kd;function JK(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,Er.isJsonObject)(r))return;for(let o of["name","from","to"]){let a=r[o];(typeof a!="string"||a.trim()==="")&&t.push((0,Er.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,Er.isJsonObject)(i)?d0(i,`/linkEntities/${n}/filters`,t):t.push((0,Er.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function d0(e,t,r){(0,Er.childObjects)(e,"conditions",t,"condition",r),(0,Er.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:o})=>d0(i,`${t}/groups/${o}`,r))}function QK(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function tO(e,t){var r;let n=f0(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)?eO: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 f0(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 rO(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of kt(t,"link-entity")){let i=n.getAttribute("name"),o=n.getAttribute("from"),a=n.getAttribute("to");if(!i||!o||!a)continue;let s=n.getAttribute("alias"),l=n.getAttribute("link-type"),u=kt(n,"filter").find(c=>!xd(c));r.push({name:i,from:o,to:a,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:p0(u)}:{}})}return r}function nO(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 iO(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=kt(t,"filter").filter(i=>!xd(i)).map(p0);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function xd(e){if(e.getAttribute("isquickfindfields")==="1")return!0;if(kt(e,"filter").length>0)return!1;let t=kt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||kt(r,"value").length>0||XK(r))}var YK=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function XK(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&&!YK.has(i))return!0}return!1}function p0(e){var t,r;let n=((t=e.getAttribute("type"))!==null&&t!==void 0?t:"and").toLowerCase()==="or"?"or":"and",i=[],o=[],a=e.childNodes;for(let s=0;s<a.length;s+=1){let l=a[s];if(l.nodeType===1)if(l.tagName==="condition"){if(l.getAttribute("isquickfindfields")==="1")continue;let u=l.getAttribute("attribute");if(!u)continue;let c={attribute:u,operator:(r=l.getAttribute("operator"))!==null&&r!==void 0?r:""},d=l.getAttribute("value");d!==null&&(c.value=d);let f=l.getAttribute("entityname")||"";f&&(c.entityname=f),i.push(c)}else l.tagName==="filter"&&o.push(p0(l))}return{type:n,conditions:i,groups:o}}function kt(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}var m0=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function ZK(e,t){let r=f0(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=r.get(i.name);if(o){let a=m0(i),s=n.get(a);s?s.push(o.link):n.set(a,[o.link])}}return n}function eJ(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(m0(s));return!!l&&l.some(u=>!i.has(u))});if(a.length!==0)throw new ZP.ValidationError("view",e.id,a.map(s=>(0,Er.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 KP(e){let t=tJ(e.columns);if(!JP(e.fetchBag)||!JP(e.layoutBag))return{fetchxml:pJ({...e,columns:t}),layoutxml:mJ({...e,columns:t},`${e.entityLogicalName}id`)};let r=new DOMParser().parseFromString("<root/>","text/xml"),n=QP(e.fetchBag,"fetch",r),i=QP(e.layoutBag,"grid",r),o=tO(i,n),a=!Rd(t,o),s=!Rd(e.sort,nO(n)),l=!Rd(e.filters,iO(n)),u=e.linkEntities,c=u!==void 0&&!Rd(u,rO(n)),d=c?ZK(n,o):void 0;return c&&cJ(r,n,u),c&&(fJ(e,n,t,d),eJ(e,n,t,d)),a?(YP(r,n,t,o),oJ(r,i,t)):c&&YP(r,n,t,o),s&&lJ(r,n,e.sort),l&&uJ(r,n,e.filters),{fetchxml:(0,Fo.serializeNode)(n),layoutxml:(0,Fo.serializeNode)(i)}}function tJ(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:eO,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function JP(e){return!!e&&(e.c.length>0||e.a.length>0)}function QP(e,t,r){let n={n:t,a:(0,u0.mergeAttrs)(e.a,[]),c:(0,u0.spliceChildren)(e.c,[])};return(0,u0.rebuildRaw)(n,(0,Fo.domEngine)(r),null)}function YP(e,t,r,n){var i,o;let a=t.getElementsByTagName("entity")[0];if(!a)return;let s=d=>{var f,p;return`${(f=d.relatedEntity)!==null&&f!==void 0?f:""}:${d.name}:${(p=d.sourceAttribute)!==null&&p!==void 0?p:d.name}`},l=new Set(r.map(s));for(let d of n)l.has(s(d))||rJ(a,d);let u=f0(t),c=new Set(kt(a,"attribute").map(d=>d.getAttribute("name")).filter(d=>!!d));for(let d of[...r].sort((f,p)=>f.order-p.order))if(d.relatedEntity){let f=u.get(d.name);if(f&&f.attributeName===((i=d.sourceAttribute)!==null&&i!==void 0?i:d.name)&&(f.linkKey===d.relatedEntity||f.linkName===d.relatedEntity||!aO(a,d.relatedEntity)))continue;let p=nJ(e,a,d.relatedEntity),m=e.createElement("attribute");oO(m,d),p.appendChild(m),u.set(d.name,{linkKey:d.relatedEntity,linkName:p.getAttribute("name")||d.relatedEntity,attributeName:(o=d.sourceAttribute)!==null&&o!==void 0?o:d.name,link:p})}else{if(c.has(d.name))continue;let f=e.createElement("attribute");f.setAttribute("name",d.name),iJ(a,f),c.add(d.name)}}function oO(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 rJ(e,t){if(t.relatedEntity){for(let r of kt(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of kt(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of kt(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function aO(e,t,r=!1){let n=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of kt(e,"link-entity"))if(n(o))return o;if(r)return;let i=e.getElementsByTagName("link-entity");for(let o=0;o<i.length;o+=1)if(n(i[o]))return i[o]}function nJ(e,t,r){let n=aO(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function iJ(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 oJ(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),o=aJ(n);if(sJ(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 aJ(e){return kt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function sJ(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 lJ(e,t,r){let n=t.getElementsByTagName("entity")[0];if(!n)return;let i=(f,p)=>`${f.toLowerCase()}\0${p.toLowerCase()}`,o=new Map,a=new Map,s=(f,p,m)=>{let h=f.get(p);h?h.push(m):f.set(p,[m])};for(let f of kt(n,"order")){let p=f.getAttribute("attribute")||"";p&&(s(o,i(f.getAttribute("entityname")||"",p),f),s(a,p.toLowerCase(),f)),n.removeChild(f)}let l=new Set,u=(f,p)=>{let m=f.get(p);for(;m&&m.length>0;){let h=m.shift();if(!l.has(h))return l.add(h),h}},c=f=>{var p;let m=a.get(f.toLowerCase());if(!m)return;let h=m.filter(v=>!l.has(v)),g=(p=h.find(v=>!v.getAttribute("entityname")))!==null&&p!==void 0?p:h[0];return g&&l.add(g),g},d=r.map(f=>{let p=String(f.attribute);return f.entityname===void 0?{expression:f,element:void 0}:{expression:f,element:u(o,i(f.entityname,p))}});for(let f of d)f.expression.entityname===void 0&&(f.element=c(String(f.expression.attribute)));for(let{expression:f,element:p}of d){let m=p??e.createElement("order");m.setAttribute("attribute",f.attribute),m.setAttribute("descending",String(f.descending)),f.entityname?m.setAttribute("entityname",f.entityname):f.entityname===""&&m.removeAttribute("entityname"),n.appendChild(m)}}function uJ(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of kt(n,"filter"))xd(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(Ql(e,r))}}function Rd(e,t){return JSON.stringify(e)===JSON.stringify(t)}function cJ(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=kt(i,"link-entity").filter(m=>m.getAttribute("name")&&m.getAttribute("from")&&m.getAttribute("to")),a=(m,h)=>m.getAttribute(h)||"",s=new Array(r.length),l=new Set,u=m=>{r.forEach((h,g)=>{if(s[g])return;let v=o.filter(E=>!l.has(E)&&m(E,h));if(v.length!==1)return;let w=v[0];r.some((E,k)=>k!==g&&!s[k]&&m(w,E))||(s[g]=w,l.add(w))})};u((m,h)=>!!h.alias&&a(m,"name")===h.name&&a(m,"alias")===h.alias),u((m,h)=>a(m,"name")===h.name&&a(m,"from")===h.from&&a(m,"to")===h.to),u((m,h)=>a(m,"name")===h.name&&a(m,"from")===h.from),u((m,h)=>a(m,"name")===h.name&&a(m,"to")===h.to),u((m,h)=>a(m,"name")===h.name);let c=r.map((m,h)=>h).filter(m=>!s[m]),d=o.filter(m=>!l.has(m)),f=new Map;for(let m of d){let h=f.get(a(m,"name"));h?h.push(m):f.set(a(m,"name"),[m])}let p=new Map;for(let m of c){let h=p.get(r[m].name);h?h.push(m):p.set(r[m].name,[m])}for(let[m,h]of p){let g=(n=f.get(m))!==null&&n!==void 0?n:[];g.length===h.length&&h.forEach((v,w)=>{s[v]=g[w],l.add(g[w])})}r.forEach((m,h)=>{let g=s[h];if(g){XP(e,g,m);return}let v=e.createElement("link-entity");XP(e,v,m),i.appendChild(v)});for(let m of o)l.has(m)||i.removeChild(m)}var dJ=new Set(["inner","outer"]);function fJ(e,t,r,n){if(!t.getElementsByTagName("entity")[0])return;let o=new Set,a=t.getElementsByTagName("link-entity");for(let c=0;c<a.length;c+=1){let d=a[c],f=d.getAttribute("name"),p=d.getAttribute("alias");f&&o.add(f),p&&o.add(p)}let s=new Set;for(let c=0;c<a.length;c+=1)s.add(a[c]);let l=c=>{let d=n?.get(m0(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 ZP.ValidationError("view",e.id,u.map(c=>{var d;let f=((d=e.linkEntities)!==null&&d!==void 0?d:[]).some(p=>p.name===c.relatedEntity||p.alias===c.relatedEntity);return(0,Er.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 XP(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):dJ.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=kt(t,"filter").find(o=>!xd(o)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?Ql(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function pJ(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(Ql(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){oO(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(Ql(r,e.filters)),new XMLSerializer().serializeToString(r)}function Ql(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(Ql(e,n));return r}function mJ(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 hJ(){return{adapter:new kd,api:HK.viewApi,publish:(e,t,r)=>(0,HP.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,HP.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}ss.viewRegistration=hJ});function Ld(e,t){return e==="SetFieldValue"&&t!==void 0&&gJ.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var gJ,h0=L(()=>{"use strict";gJ=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function lO(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function g0(e){return e==="AllForms"||lO(e)?1:2}function y0(e){return lO(e)?e:null}function uO(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:ls.WorkflowCategory.BusinessRule,type:ls.WorkflowTypeCode.Definition,mode:1,scope:ls.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:g0(e.scope),processtriggerformid:y0(e.scope)}}var ls,cO=L(()=>{"use strict";ls=ye(Ci());});function dO(e,t=0){return(At[e[t+0]]+At[e[t+1]]+At[e[t+2]]+At[e[t+3]]+"-"+At[e[t+4]]+At[e[t+5]]+"-"+At[e[t+6]]+At[e[t+7]]+"-"+At[e[t+8]]+At[e[t+9]]+"-"+At[e[t+10]]+At[e[t+11]]+At[e[t+12]]+At[e[t+13]]+At[e[t+14]]+At[e[t+15]]).toLowerCase()}var At,fO=L(()=>{At=[];for(let e=0;e<256;++e)At.push((e+256).toString(16).slice(1))});function v0(){return Fd>Md.length-16&&((0,pO.randomFillSync)(Md),Fd=0),Md.slice(Fd,Fd+=16)}var pO,Md,Fd,mO=L(()=>{pO=require("crypto"),Md=new Uint8Array(256),Fd=Md.length});var hO,b0,gO=L(()=>{hO=require("crypto"),b0={randomUUID:hO.randomUUID}});function yJ(e,t,r){if(b0.randomUUID&&!t&&!e)return b0.randomUUID();e=e||{};let n=e.random??e.rng?.()??v0();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 dO(n)}var Vt,yO=L(()=>{gO();mO();fO();Vt=yJ});var w0=L(()=>{yO()});var vO=L(()=>{"use strict";});var A0=b(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.WorkflowConditionOperator=Vr.WorkflowAttributeType=Vr.SystemStep=Vr.FieldRequiredLevelTypes=Vr.AttributeDateTimeBehavior=void 0;Vr.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};Vr.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};Vr.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};Vr.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"};Vr.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 CO(e){switch(e){case"Boolean":return Re.WorkflowAttributeType.Boolean;case"Customer":return Re.WorkflowAttributeType.Customer;case"DateTime":return Re.WorkflowAttributeType.DateTime;case"Decimal":return Re.WorkflowAttributeType.Decimal;case"Double":return Re.WorkflowAttributeType.Float;case"Integer":return Re.WorkflowAttributeType.Integer;case"Lookup":return Re.WorkflowAttributeType.Lookup;case"Money":return Re.WorkflowAttributeType.Money;case"Owner":return Re.WorkflowAttributeType.Owner;case"Picklist":return Re.WorkflowAttributeType.Picklist;case"State":return Re.WorkflowAttributeType.State;case"Status":return Re.WorkflowAttributeType.Status;case"Uniqueidentifier":case"UniqueIdentifier":return Re.WorkflowAttributeType.UniqueIdentifier;case"BigInt":return Re.WorkflowAttributeType.BigType;default:return Re.WorkflowAttributeType.String}}function TO(e){return e&&e!==Re.WorkflowAttributeType.String?e:void 0}function wJ(e){return{__class:IO,parameterName:"primaryEntity",entityName:e}}function bO(e){return{__class:E0,type:C0,typeSet:!1,behavior:Re.AttributeDateTimeBehavior.None,method:EO,parameters:[e]}}function wO(e,t,r=Re.WorkflowAttributeType.String){return{__class:NO,type:r,behavior:Re.AttributeDateTimeBehavior.None,typeSet:!1,entity:wJ(t),attributeName:e}}function AJ(e,t=Re.WorkflowAttributeType.String){return{__class:DO,type:t,behavior:Re.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function CJ(e){return{__class:_O,type:C0,typeSet:!1,behavior:Re.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function PO(e,t){let r=vJ[e.operator],n=bO(wO(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=CJ(e.right.value??"0"):e.right.kind==="field"?i=wO(e.right.field??"",t,e.right.workflowType):i=AJ(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=bO(i);return{__class:E0,type:C0,typeSet:!1,behavior:Re.AttributeDateTimeBehavior.None,method:SO,parameters:[r,n,o]}}function OO(e){return typeof e=="object"&&e.__class===E0}function EJ(e){return typeof e=="object"&&e.__class===_O}function $d(e){return OO(e)&&e.method===EO&&e.parameters.length>0?$d(e.parameters[0]):e}function AO(e){if(typeof e!="object"||e.__class!==NO)return null;let t=e.entity;if(t&&t.__class&&t.__class!==IO)return null;let r=e.attributeName;return r?{field:r,workflowType:TO(e.type)}:null}function RO(e){if(!e)return null;let t=$d(e);if(!OO(t)||t.method!==SO||t.parameters.length!==3)return null;let r=t.parameters[0],n=bJ[String(r)];if(!n)return null;let i=AO($d(t.parameters[1]));if(!i)return null;let o=$d(t.parameters[2]);if(EJ(o))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=AO(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===DO){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:TO(o.type)}}}return null}function N0(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=S0&&r<=us}function Mo(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&&!N0(t)?"invalidDayCount":null}function cs(e){return Mo(e)===null}var Re,EO,SO,C0,NO,DO,E0,_O,IO,vJ,bJ,S0,us,Yl=L(()=>{"use strict";Re=ye(A0());EO="0",SO="3",C0="0",NO="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",DO="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",E0="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",_O="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",IO="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";vJ={"+":0,"-":1,"*":2,"/":3},bJ={0:"+",1:"-",2:"*",3:"/"};S0=0,us=2147483647});var kO=L(()=>{"use strict";});function di(e){return!SJ.has(e)}function D0(e){return e==="Equals"||e==="DoesNotEqual"}function MO(e){return kJ.has(e)}function Bd(e){return LO.has(e)?NJ:PJ.has(e)?DJ:FO.has(e)?_J:RJ.has(e)?TJ:IJ}function $O(e){return Bd(e)[0]}function BO(e,t){return Bd(t).includes(e)}function xO(e){return LO.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":FO.has(e)?"date":OJ.has(e)?"boolean":"other"}function Ud(e,t){let r=xO(e),n=xO(t);return r==="other"||n==="other"?e===t:r===n}var SJ,NJ,DJ,_J,IJ,TJ,LO,PJ,FO,OJ,RJ,kJ,qd=L(()=>{"use strict";kO();SJ=new Set(["ContainsData","DoesNotContainData"]);NJ=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],DJ=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],_J=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],IJ=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],TJ=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],LO=new Set(["String","Memo","EntityName"]),PJ=new Set(["Integer","BigInt","Money","Decimal","Double"]),FO=new Set(["DateTime"]),OJ=new Set(["Boolean"]),RJ=new Set(["Lookup","Owner","Customer"]);kJ=new Set(["Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith"])});function LJ(e){return e.startsWith("__")&&!xJ.has(e)}function FJ(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{LJ(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function XO(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function $o(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Vd(e){return XO(e)||$o(e)}function MJ(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function Xl(){return{list:[]}}function _0(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:Vt(),languageCode:r,description:t}]}}function O0(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function jd(e,t,r){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,entity:O0(t),attributeName:e}}function fs(e,t){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function UJ(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?tR:eR:ZO}function rR(e){return e.bpfField==="StageCategory"?j.WorkflowAttributeType.BpfStageCategory:j.WorkflowAttributeType.BpfProcess}function qJ(e,t){let r=rR(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${qO}_${UO}`,entityName:UO,relatedAttributeName:qO},attributeName:BJ}:jd($J,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,method:x0,parameters:[UJ(e),n]}}function nR(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==x0)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===eR?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===tR?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===ZO?{bpfField:"ProcessName"}:null}function Gd(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===x0){let r=(t.parameters??[])[0];if(typeof r=="string"&&VJ.has(r.replace(/^"+|"+$/g,"")))return!0}return $o(e)?Gd(e.operand):XO(e)?Gd(e.left)||(e.right??[]).some(Gd):!1}function iR(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 GJ(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 VO(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return iR(e);case"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions":return e.primitiveValue!=null;case"LookupExpression:#Microsoft.Crm.Workflow.Expressions":case"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions":return!0;default:return!1}}function WJ(e){let t=k0[e.conditionOperatoroperator];if(!t)return!1;let r=t==="ContainsData"||t==="DoesNotContainData";if($o(e))return r&&GO(e.operand,!0);let n=e.right??[];return n.length!==(r?0:1)?!1:GO(e.left,r,n[0])}function GO(e,t,r){return nR(e)||iR(e)?t||VO(r):!1}function R0(e){if(!e||!Vd(e))return!1;let t=e.conditionOperatoroperator;if(!$o(e)&&(t===j.WorkflowConditionOperator.LogicalAnd||t===j.WorkflowConditionOperator.LogicalOr)){let r=e.right??[];return r.length>0&&R0(e.left)&&r.every(R0)}return WJ(e)}function WO(e){return!e||GJ(e)?!1:Gd(e)||!R0(e)}function oR(e){return{__class:"LookupExpression:#Microsoft.Crm.Workflow.Expressions",type:e.workflowType??j.WorkflowAttributeType.Lookup,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,entityType:e.entityType,label:e.label??"",staticValue:fs(e.id.replace(/[{}]/g,""),j.WorkflowAttributeType.UniqueIdentifier)}}function zO(e){return e==="ContainsData"||e==="DoesNotContainData"}function I0(e){return zJ.has(e)}function jO(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function HO(e,t){let r=e.valueType==="Lookup"?e.lookupValue?.workflowType??j.WorkflowAttributeType.Lookup:e.valueWorkflowType??j.WorkflowAttributeType.String,n=e.leftWorkflowType??r,i=I0(n)&&MO(e.operator),o=P0[e.operator]??j.WorkflowConditionOperator.Equal;if(e.source==="BusinessProcess"){let l=qJ(e,t);if(zO(e.operator))return jO(l,o);let u=rR(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o,left:l,right:[fs(e.value??"",u)]}}let a=jd(e.field,t,n);if(zO(e.operator))return jO(a,o);let s;if(e.valueType==="Field"&&e.valueField){let l=I0(n)&&I0(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:n;s=[jd(e.valueField,t,i?j.WorkflowAttributeType.String:l)]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[oR(e.lookupValue)]}else e.valueType==="Clear"?s=[fs(null,r)]:e.valueType==="Expression"?s=[zd(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)]:s=[fs(e.value??"",r)];return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o,left:a,right:s}}function jJ(e,t,r){if(e.length===0)return null;let n=HO(e[0],r);for(let i=1;i<e.length;i++){let o=e[i].connector??t;n={__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?j.WorkflowConditionOperator.LogicalAnd:j.WorkflowConditionOperator.LogicalOr,left:n,right:[HO(e[i],r)]}}return n}function Wd(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")return e.primitiveValue==null?{valueType:"Clear",valueWorkflowType:e.type}:{valueType:"Value",value:e.primitiveValue!=null?String(e.primitiveValue):"",valueWorkflowType:e.type};if(e.__class==="LookupExpression:#Microsoft.Crm.Workflow.Expressions"){let t=e.staticValue,r=typeof t=="object"&&t?.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?t.primitiveValue:t;return{valueType:"Lookup",lookupValue:{entityType:e.entityType,id:String(r??""),label:e.label,...e.type!==j.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=RO(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function HJ(e){let t=k0[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=$o(e)?e.operand:e.left,i=$o(e)?[]:e.right??[],o=nR(n);if(o){let d=i[0];return{id:Vt(),field:"",fieldDisplayName:"",source:"BusinessProcess",bpfField:o.bpfField,...o.stageType?{stageType:o.stageType}:{},operator:t,valueType:"Value",value:d?.primitiveValue!=null&&!r?String(d.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"}:Wd(i[0]),c=u.valueWorkflowType??l;return{id:Vt(),field:s,fieldDisplayName:s,operator:t,...u,...c?{valueWorkflowType:c}:{},...l?{leftWorkflowType:l}:{}}}function KO(e){if(!e||!Vd(e))return{clauses:[],logic:"AND"};let t=[],r=(o,a)=>{let s=o.conditionOperatoroperator;if($o(o)||s!==j.WorkflowConditionOperator.LogicalAnd&&s!==j.WorkflowConditionOperator.LogicalOr){t.push({...HJ(o),...a?{connector:a}:{}});return}let l=s===j.WorkflowConditionOperator.LogicalAnd?"AND":"OR";Vd(o.left)&&r(o.left,a),(o.right??[]).filter(Vd).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 zd(e,t,r,n,i,o,a,s){if(e==="Field"&&r)return jd(r,n,j.WorkflowAttributeType.String);if(e==="Expression"){if(i)return PO(i,n);if(o!=null)return o}return e==="Lookup"&&a?oR(a):e==="Clear"?fs(null,s??j.WorkflowAttributeType.String):fs(t??"",j.WorkflowAttributeType.String)}function T0(e,t){return{propertyName:e,propertyValueExpr:t}}function ds(e){return`Step_${e.value++}`}function Gr(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 JO(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):Gr(t,r)}function KJ(e){return e===YO.StateCode.Activated?"Active":"Draft"}function JJ(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function aR(e,t=1033){return new ps({languageCode:t}).serialize(e)}function sR(e){return new ps().deserialize(e)}var YO,j,xJ,P0,k0,x0,ZO,eR,tR,$J,BJ,UO,qO,VJ,zJ,L0,ps,F0=L(()=>{"use strict";w0();YO=ye(Ci());vO();Yl();qd();j=ye(A0());xJ=new Set(["__class"]);P0={Equals:j.WorkflowConditionOperator.Equal,DoesNotEqual:j.WorkflowConditionOperator.NotEqual,IsGreaterThan:j.WorkflowConditionOperator.GreaterThan,IsLessThan:j.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:j.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:j.WorkflowConditionOperator.LessThanOrEqual,Contains:j.WorkflowConditionOperator.Contains,DoesNotContain:j.WorkflowConditionOperator.DoesNotContain,BeginsWith:j.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:j.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:j.WorkflowConditionOperator.EndsWith,DoesNotEndWith:j.WorkflowConditionOperator.DoesNotEndWith,On:j.WorkflowConditionOperator.On,NotOn:j.WorkflowConditionOperator.NotOn,ContainsData:j.WorkflowConditionOperator.NotNull,DoesNotContainData:j.WorkflowConditionOperator.IsNull},k0={};for(let e of Object.keys(P0))k0[P0[e]]=e;x0="23",ZO="BpfProcess",eR="ActiveStageCategory",tR="SelectedStageCategory",$J="processid",BJ="stagecategory",UO="processstage",qO="stageid";VJ=new Set(["ActiveStage","SelectedStage","Stage"]);zJ=new Set([j.WorkflowAttributeType.Lookup,j.WorkflowAttributeType.Owner,j.WorkflowAttributeType.Customer]);L0={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"};ps=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>L0[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??Vt(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:Xl(),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:Gr("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??ds(this.stepCounter),stepLabels:{list:[]},specification:T0(t.field,zd(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:O0(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),o=t??"",a=n?.stepLabels,s=_0(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:JO(n?.id,"ActionStep",this.idCounter),name:n?.name??ds(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??Vt(),uniqueName:n?.uniqueName??`id_${Vt().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=O0(this.entityName),n=t.stepName??ds(this.stepCounter),i=t.stepLabels??Xl(),o={name:n,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:Gr("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:T0(t.field,zd(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:Gr("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:T0(t.field,zd(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:Gr("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...o,id:Gr("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?j.FieldRequiredLevelTypes.Required:j.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...o,id:Gr("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=_0(t.stepLabels,s,this.languageCode);return{...o,id:Gr("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=_0(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:Gr("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??ds(this.stepCounter),n=Gr("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??jJ(o.clauses,o.logic,this.entityName),l=a?o.branchName??ds(this.stepCounter):ds(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?JO(o.branchId,"ConditionBranchStep",this.idCounter):Gr("ConditionBranchStep",this.idCounter),name:l,description:o.displayName,stepLabels:Xl(),conditionExpression:s??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:Xl(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:Gr("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:Xl(),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??Vt():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:FJ(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:JJ(r,i?.formId),status:KJ(t.statecode),rootCondition:n,wfomRoot:i}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(MJ);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...o]=t,{clauses:a,logic:s}=KO(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)??Vt(),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,...WO(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=KO(n.conditionExpression);return i.length===0&&!WO(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||Vt(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...Wd(u?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=Wd(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=Wd(t.specification.propertyValueExpr);return{kind:"action",id:t.id,type:"SetDefaultValue",displayName:t.description||t.name||this.label("setDefaultValue"),stepName:t.name,stepLabels:t.stepLabels,field:t.specification.propertyName,...r}}case"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"LockUnlock",displayName:t.description||t.name||this.label("lockUnlock"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,lock:t.isReadOnly};case"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"SetBusinessRequired",displayName:t.description||t.name||this.label("setBusinessRequired"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,required:t.requiredLevel!==j.FieldRequiredLevelTypes.None};case"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel":return{kind:"action",id:t.id,type:"SetVisibility",displayName:t.description||t.name||this.label("setVisibility"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,visible:t.isVisible};case"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=t.stepLabels?.list,n=r&&r.length>0?r[0].description??"":"";if((t.level??"").toUpperCase()==="RECOMMENDATION"){let{applyActions:i,meta:o,acceptanceText:a}=this.parseRecommendationApplyActions(t.actionSteps);return{kind:"action",id:t.id,type:"Recommendation",displayName:t.description||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,recommendationTitle:t.description||"",messageText:n,acceptanceText:a,applyActions:i,recommendationActionStepMeta:o}}return{kind:"action",id:t.id,type:"ShowErrorMessage",displayName:t.description||this.label("showErrorMessage"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,errorMessage:n||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:r,meta:n,acceptanceText:i}=this.parseRecommendationApplyActions({list:[t]});return{kind:"action",id:t.id,type:"Recommendation",displayName:t.name||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.actionControl?.controlId??"",recommendationTitle:t.name||"",messageText:t.description||"",acceptanceText:i,applyActions:r,recommendationActionStepMeta:n}}default:return null}}}});function U0(e){return QJ.has(e.type)}function M0(e,t,r,n,i,o,a){let s=i.get(r);!s||!cR.has(s.attributeType)||n!=="Value"||a?.operator&&!D0(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 YJ(e,t){let r=t.get(e.field);return!!r&&cR.has(r.attributeType)&&D0(e.operator)}function $0(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function B0(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${us}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:us}}}function lR(e,t,r,n,i,o,a,s){if(i!=="Clear")return;let l=o.get(n);Ld(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 Kd(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(U0(t))return!0}else if(Kd(t))return!0;return!1}function q0(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=q0(r,t);if(n)return n}}return null}function ms(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=ms(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=ms(n,t);if(i)return i}}return null}function V0(e,t){return{...e,trueBranch:uR(e.trueBranch,t),falseBranch:uR(e.falseBranch,t)}}function uR(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?V0(r,t):r)}function Ki(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?Ki(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?Ki(n,t,r):n)}}function Hd(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Hd(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?Hd(n,t,r):n)}}function dR(e,t,r,n){return Ki(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function G0(e){return e.length===1&&e[0].kind==="condition"}function ZJ(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(G0(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function eQ(e){return!!e&&ZJ(e)<XJ}function tQ(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let o=[];if(G0(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 fR(e,t,r){let n=tQ(e,t);return!n||!eQ(n)?e:Ki(e,t,i=>pR(i,r))}function pR(e,t){if(G0(e.falseBranch))return{...e,falseBranch:[pR(e.falseBranch[0],t)]};let r=W0(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function mR(e,t){let r=ms(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 Ki(e,r.node.id,o=>({...o,falseBranch:i}))}function hR(e,t,r){let n=ms(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 Ki(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 W0(e){return{kind:"condition",id:Vt(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function gR(e,t){let r={kind:"action",id:Vt(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:Vt(),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 yR(e){if(!e)return[];let t=[];return vR(e,t),[...new Set(t)]}function vR(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?vR(r,t):"field"in r&&r.field&&t.push(r.field)})}function bR(e,t=[]){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition.",target:"node"}];let r=[],n=new Map(t.map(i=>[i.logicalName,i]));return wR(e,r,n),Kd(e)||r.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),r}function wR(e,t,r){let n=!!e.rawConditionExpression;e.clauses.length===0&&!n&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition.",target:"node",messageKey:"Validation.AddClause"}),e.clauses.forEach(i=>{if(n)return;if(i.source==="BusinessProcess"){i.bpfField?i.value||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:i.id}):t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a business process field for this clause.",target:"clauseField",itemId:i.id,messageKey:"Validation.SelectBusinessProcessField"});return}let o=i.valueType==="Expression"&&!i.rawExpression?Mo(i.expression):null;if(!i.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause.",target:"clauseField",itemId:i.id});else if(di(i.operator)&&i.valueType==="Value"&&!i.value&&!YJ(i,r))t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:i.id});else if(di(i.operator)&&i.valueType==="Value"&&i.value){let a=r.get(i.field);a?.maxLength&&i.value.length>a.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${a.maxLength} characters.`,target:"clauseValue",itemId:i.id,messageParams:{maxLength:a.maxLength}})}else di(i.operator)&&i.valueType==="Expression"&&!i.rawExpression&&!cs(i.expression)?t.push(o==="invalidDayCount"?B0(e.id,"clauseValue",i.id):{nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause.",target:"clauseValue",itemId:i.id,messageKey:"Validation.CompleteClauseFormula"}):di(i.operator)&&i.valueType==="Field"&&!i.valueField&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a field to compare to for this clause.",target:"clauseValue",itemId:i.id,messageKey:"Validation.EmptyClauseCompareField"});di(i.operator)&&i.valueType==="Lookup"&&($0(i.lookupValue)||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause.",target:"clauseValue",itemId:i.id,messageKey:"Validation.EmptyClauseLookupValue"})),di(i.operator)&&M0(e.id,"Condition",i.field,i.valueType,r,t,{operator:i.operator,target:"clauseValue",itemId:i.id})}),[...e.trueBranch,...e.falseBranch].forEach(i=>{if(i.kind==="condition")wR(i,t,r);else{if(!("field"in i)||!i.field)t.push({nodeId:i.id,kind:"EMPTY_ACTION_FIELD",message:`${i.type}: a target field is required.`,target:"actionField",messageParams:{actionType:i.type}});else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&(i.valueType??"Value")==="Value"&&!i.value?.trim())t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please provide a value.`,target:"actionValue",messageParams:{actionType:i.type}});else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Value"&&i.value){let o=r.get(i.field);o?.maxLength&&i.value.length>o.maxLength&&t.push({nodeId:i.id,kind:"ACTION_VALUE_TOO_LONG",message:`${i.type}: value exceeds the field's maximum length of ${o.maxLength} characters.`,target:"actionValue",messageParams:{actionType:i.type,maxLength:o.maxLength}})}else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Field"){if(!i.valueField)t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please select a field to copy from.`,target:"actionValue",messageKey:"Validation.SelectActionSourceField",messageParams:{actionType:i.type}});else if(r.size>0){let o=r.get(i.field),a=r.get(i.valueField);o&&a&&!Ud(o.attributeType,a.attributeType)&&t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: the source field's type is not compatible with the target field.`,target:"actionValue",messageKey:"Validation.IncompatibleActionSourceField",messageParams:{actionType:i.type}})}}else if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Expression"){let o=i.rawExpression?null:Mo(i.expression);!i.rawExpression&&!cs(i.expression)&&t.push(o==="invalidDayCount"?B0(i.id,"actionValue"):{nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please complete the formula.`,target:"actionValue",messageKey:"Validation.CompleteActionFormula",messageParams:{actionType:i.type}})}else(i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.valueType==="Lookup"&&!$0(i.lookupValue)&&t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:`${i.type}: please complete the lookup record.`,target:"actionValue",messageKey:"Validation.EmptyActionLookupValue",messageParams:{actionType:i.type}});if((i.type==="SetFieldValue"||i.type==="SetDefaultValue")&&i.field&&(M0(i.id,i.type,i.field,i.valueType,r,t,{target:"actionValue"}),lR(i.id,i.type,i.type,i.field,i.valueType,r,t,{target:"actionValue"})),i.type==="ShowErrorMessage"&&!i.errorMessage?.trim()&&t.push({nodeId:i.id,kind:"EMPTY_ACTION_MESSAGE",message:"Show error message: please enter an error message.",target:"actionMessage"}),i.type==="Recommendation"){let o=i.applyActions??[];i.recommendationTitle?.trim()||t.push({nodeId:i.id,kind:"EMPTY_RECOMMENDATION_TITLE",message:"Recommendation: please enter a recommendation title.",target:"recommendationTitle"}),i.messageText?.trim()||t.push({nodeId:i.id,kind:"EMPTY_RECOMMENDATION_MESSAGE",message:"Recommendation: please enter a recommendation message.",target:"recommendationMessage"}),o.length===0&&t.push({nodeId:i.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply.",target:"node"}),o.forEach(a=>{if(!a.field)t.push({nodeId:i.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply.",target:"applyActionField",itemId:a.id,messageKey:"Validation.RecommendationApplyField"});else if(a.valueType==="Field")a.valueField||t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplySourceField"});else if(a.valueType==="Expression"){let s=a.rawExpression?null:Mo(a.expression);!a.rawExpression&&!cs(a.expression)&&t.push(s==="invalidDayCount"?B0(i.id,"applyActionValue",a.id):{nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplyFormula"})}else a.valueType==="Lookup"?$0(a.lookupValue)||t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplyLookupValue"}):a.valueType==="Clear"||a.value?.trim()||t.push({nodeId:i.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply.",target:"applyActionValue",itemId:a.id,messageKey:"Validation.RecommendationApplyValue"});a.field&&(M0(i.id,"Recommendation",a.field,a.valueType,r,t,{target:"applyActionValue",itemId:a.id}),lR(i.id,"Recommendation","SetFieldValue",a.field,a.valueType,r,t,{target:"applyActionValue",itemId:a.id}))})}}})}var QJ,cR,XJ,z0=L(()=>{"use strict";w0();h0();qd();Yl();QJ=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);cR=new Set(["Lookup","Customer","Owner"]);XJ=10});var AR={};Ir(AR,{DAY_COUNT_MAX:()=>us,DAY_COUNT_MIN:()=>S0,DEFAULT_DESERIALIZE_LABELS:()=>L0,WorkflowJsonMapper:()=>ps,addElseIfInTree:()=>fR,appendToBranch:()=>dR,areFieldKindsCompatible:()=>Ud,attributeTypeToWorkflowType:()=>CO,buildWorkflowEntity:()=>uO,collectUsedFields:()=>yR,createEmptyAction:()=>gR,createEmptyCondition:()=>W0,deserializeWorkflowJson:()=>sR,findNode:()=>q0,findParent:()=>ms,getDefaultOperatorForFieldType:()=>$O,getExpressionModelIssue:()=>Mo,getOperatorsForFieldType:()=>Bd,hasAnyTriggerGeneratingAction:()=>Kd,isDayCountValid:()=>N0,isExpressionModelComplete:()=>cs,isOperatorCompatible:()=>BO,isTriggerGeneratingAction:()=>U0,moveBranchItemInTree:()=>hR,operatorNeedsValue:()=>di,processTriggerFormIdFromScope:()=>y0,processTriggerScopeFromScope:()=>g0,removeElseIfInTree:()=>mR,removeNodeFromTree:()=>V0,serializeToWorkflowJson:()=>aR,supportsClearForActionType:()=>Ld,updateActionInTree:()=>Hd,updateConditionInTree:()=>Ki,validateBusinessRule:()=>bR});var CR=L(()=>{"use strict";h0();cO();F0();F0();z0();z0();qd();Yl();Yl();});var j0=b(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});Jd.cloneJson=void 0;function rQ(e){return JSON.parse(JSON.stringify(e))}Jd.cloneJson=rQ});var xR=b(Ji=>{"use strict";Object.defineProperty(Ji,"__esModule",{value:!0});Ji.BUSINESS_RULE_NULL_GUID=Ji.businessRuleRegistration=Ji.BusinessRuleAdapter=void 0;var ER=lt(),Zl=(CR(),hr(AR)),SR=Tr(),NR=X(),nQ=j0(),Pn=kr(),iQ=fp(),oQ=lt(),aQ=ho(),sQ=new Set(["ShowErrorMessage","Recommendation"]);function TR(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)?TR(n):sQ.has(String(n.type))):!1}function lQ(e){return PR((0,nQ.cloneJson)(e))}function PR(e){var t,r;let n=i=>(i??[]).map(o=>uQ(o)?PR(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 uQ(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 cQ(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new NR.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 NR.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 dQ="00000000-0000-0000-0000-000000000000";Ji.BUSINESS_RULE_NULL_GUID=dQ;var fQ=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),pQ=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],mQ=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],hQ=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function sn(e,t){return e===void 0?t:{...e,...t}}var Bo=["kind","id","type","displayName","field","stepName","stepLabels"],DR=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],gQ={Recommendation:[...Bo,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...Bo,"lock"],ShowErrorMessage:[...Bo,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...Bo,...DR],SetDefaultValue:[...Bo,...DR],SetBusinessRequired:[...Bo,"required"],SetVisibility:[...Bo,"visible"]};function ee(e,t){return t===void 0?{}:{[e]:t}}function OR(e){var t;return e===void 0?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function H0(e){return{valueType:e.valueType,...ee("valueWorkflowType",e.valueWorkflowType),...ee("value",e.value),...ee("valueField",e.valueField),...ee("lookupValue",OR(e.lookupValue)),...ee("expression",e.expression),...ee("rawExpression",e.rawExpression)}}function RR(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 yQ=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function vQ(e){return sn(e.bag,{id:e.id,field:e.field,...H0(e),...ee("stepName",e.stepName),...ee("displayName",e.displayName)})}function bQ(e){let t=RR(e,yQ);return{id:e.id,field:e.field,valueType:e.valueType,...ee("valueWorkflowType",e.valueWorkflowType),...ee("value",e.value),...ee("valueField",e.valueField),...ee("lookupValue",e.lookupValue),...ee("expression",e.expression),...ee("rawExpression",e.rawExpression),...ee("stepName",e.stepName),...ee("displayName",e.displayName),...ee("bag",t)}}function _R(e){return{valueType:e.valueType,...ee("valueWorkflowType",e.valueWorkflowType),...ee("value",e.value),...ee("valueField",e.valueField),...ee("lookupValue",e.lookupValue),...ee("expression",e.expression),...ee("rawExpression",e.rawExpression)}}function IR(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var wQ=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),AQ=new Set,CQ="INVALID_CLEAR_FOR_FIELD";function EQ(e){let t=n=>{var i;return(0,Pn.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,Pn.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 Qd=class{toArtifact(t){let r=this.residualBag(t,pQ),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 sn(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,Zl.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return TR(t.rootCondition)}toApiPayload(t,r,n){var i,o;let a=this.fromArtifact(t);a.wfomRoot&&(a.wfomRoot={...a.wfomRoot,name:t.name,title:t.name,primaryEntityName:t.entityLogicalName||a.wfomRoot.primaryEntityName});let s=(0,Zl.serializeToWorkflowJson)(a,(i=n?.baseLanguageCode)!==null&&i!==void 0?i:aQ.DEFAULT_LCID),l=(o=a.ruleId)!==null&&o!==void 0?o:(0,ER.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,Zl.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(lQ(cQ(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,ER.newId)()),u}assignMissingIds(t){return(0,oQ.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,Pn.isJsonObject)(n)?(kR(n,"/rootCondition",r),r):(r.push((0,Pn.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,Pn.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=n.rootCondition===null?null:EQ(n.rootCondition),o;return r.length===0?o=wQ:r.some(a=>a.requiredLevel!==void 0)?o=AQ:o=new Set([CQ]),(0,Zl.validateBusinessRule)(i,r).filter(a=>!o.has(a.kind)).map(a=>(0,Pn.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 RR(t,r)}buildWorkflowEntity(t,r){return(0,Zl.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,mQ),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,hQ),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,gQ[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...ee("stepName",t.stepName),...ee("stepLabels",t.stepLabels),...ee("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ee("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(bQ),...ee("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ee("messageLevel",t.messageLevel),...ee("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",..._R(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",..._R(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return IR(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return sn(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 sn(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,...ee("value",t.value),...ee("valueField",t.valueField),...ee("lookupValue",OR(t.lookupValue)),...ee("expression",t.expression),...ee("rawExpression",t.rawExpression),...ee("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!fQ.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);NQ(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...ee("stepName",t.stepName),...ee("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return sn(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ee("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(vQ),...ee("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return sn(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return sn(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ee("messageLevel",t.messageLevel),...ee("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return sn(t.bag,{...r,type:"SetFieldValue",...H0(t)});case"SetDefaultValue":return sn(t.bag,{...r,type:"SetDefaultValue",...H0(t)});case"SetBusinessRequired":return sn(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return sn(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return IR(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};Ji.BusinessRuleAdapter=Qd;function kR(e,t,r){(0,Pn.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,Pn.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,Pn.childObjects)(e,n,t,"branchItem",r).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?kR(o,`${t}/${n}/${a}`,r):SQ(o,`${t}/${n}/${a}`,r)})}function SQ(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,Pn.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function NQ(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function DQ(){return{adapter:new Qd,api:iQ.businessRuleApi,publish:(e,t,r)=>(0,SR.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,SR.boundEntityPublishScope)(t)}}Ji.businessRuleRegistration=DQ});var YR=b(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.appRegistration=Qi.AppAdapter=Qi.HEADER_NAV_BOOLEAN_RULE=void 0;var fi=kr(),mt=Pi(),tu=Ri(),_Q=Tr(),WR=Oc(),K0=Ec(),J0=Oi(),IQ=lt(),TQ=ae(),zR=ho(),jR=X(),HR=Nc();Object.defineProperty(Qi,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return HR.HEADER_NAV_BOOLEAN_RULE}});var ef="7.0.0.0",LR=`<SiteMap IntroducedVersion="${ef}"></SiteMap>`,FR="/_imgs/imagestrips/transparent_spacer.gif",MR="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",PQ=["Entity","Url","DefaultDashboard","Page","GenPageId"],eu="sitemapId",$R="sitemapName",OQ="sitemapNameUnique",BR="aiDescription",UR="[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}",RQ=new RegExp(`^(?:\\{${UR}\\}|${UR})$`);function qR(e,t){if(!RQ.test(e.trim()))throw new jR.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function VR(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new jR.ValidationError("app",t,[KR(e)]);return e}function KR(e){return(0,fi.issue)("/headerAndNavigationRefresh",HR.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function kQ(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,TQ.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 xQ(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 tf=class{constructor(t=zR.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=Yd(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,mt.emptyBag)()}}fromArtifact(t){(0,J0.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,mt.rebuildRaw)(i,(0,tu.domEngine)(n),null)}fromApiResponse(t){var r,n,i,o,a,s,l,u,c,d,f;(0,J0.installDomShim)();let p=t??{},m=(r=p.$sitemap)!==null&&r!==void 0?r:p,h=(0,tu.parseXmlRoot)((n=m.sitemapxml)!==null&&n!==void 0?n:LR,LR),g=this.toArtifact(h);return g.id=(i=p.appmoduleid)!==null&&i!==void 0?i:"",g.name=(o=p.name)!==null&&o!==void 0?o:"",g.uniqueName=(a=p.uniquename)!==null&&a!==void 0?a:"",g.description=(s=p.description)!==null&&s!==void 0?s:"",p.aiappdescription&&(g.aiDescription=p.aiappdescription),g.bag={a:[[eu,(u=(l=m.sitemapid)!==null&&l!==void 0?l:p._sitemapid_value)!==null&&u!==void 0?u:""],[$R,(c=m.sitemapname)!==null&&c!==void 0?c:""],[OQ,(d=m.sitemapnameunique)!==null&&d!==void 0?d:""],[BR,(f=p.aiappdescription)!==null&&f!==void 0?f:""]],c:[]},g}toApiPayload(t,r){var n,i,o,a,s,l,u,c,d,f,p,m,h,g,v;(0,J0.installDomShim)();let w=(0,tu.serializeNode)(this.fromArtifact(t)),C=[],E=[];for(let R of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let T of(o=R.groups)!==null&&o!==void 0?o:[])for(let I of(a=T.subAreas)!==null&&a!==void 0?a:[])I.type==="Entity"&&I.entity?C.push(I.entity):I.type==="DashBoard"&&I.dashboardId&&E.push(I.dashboardId);let k=(s=t.bag)!==null&&s!==void 0?s:(0,mt.emptyBag)();return{sitemapId:Y0(k,eu)||(t.sitemapId?qR(t.sitemapId,t.id):""),sitemapxml:w,sitemapname:Y0(k,$R)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:Y0(k,BR))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[K0.HEADER_AND_NAVIGATION_REFRESH]:VR(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?K0.APP_SETTING_ON:K0.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:(m=(p=t.components)===null||p===void 0?void 0:p.charts)!==null&&m!==void 0?m:[],dashboards:[...(g=(h=t.components)===null||h===void 0?void 0:h.dashboards)!==null&&g!==void 0?g:[],...E],...((v=t.components)===null||v===void 0?void 0:v.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,IQ.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:qR(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:VR(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(Z0):Array.isArray(r.areas)?r.areas.forEach(Z0):Array.isArray(r.groups)?Z0(r):Array.isArray(r.subAreas)?QR(r):"type"in r&&rf(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,fi.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(KR(o)),i==null)return r;if(!(0,fi.isJsonObject)(i))return r.push((0,fi.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let a=(0,fi.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return a.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,fi.childObjects)(l,"groups",c,"group",r).forEach(({node:f,index:p})=>{let m=`${c}/groups/${p}`;(0,fi.childObjects)(f,"subAreas",m,"subArea",r).forEach(({node:g,index:v})=>{let w=`${m}/subAreas/${v}`;(0,fi.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],w,"subarea-type-invalid",r);let C=kQ(g);if(!C)return;let E=s.get(C);if(E===void 0){s.set(C,w);return}r.push((0,fi.issue)(w,"subarea-duplicate-target",`the sitemap already navigates to this target at ${E}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}issuesBlockingPush(t){var r;return(0,WR.mainFormSetShapeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsByTable,xQ(t))}applyServerIdentity(t,r){let n=r[eu];if(!n)return;t.bag||(t.bag=(0,mt.emptyBag)());let i=t.bag.a.find(o=>o[0]===eu);i?i[1]=n:t.bag.a.push([eu,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=Yd(t,"Group"),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Q0(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}=Yd(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:Q0(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:n}}subAreaToJson(t){var r;let{bag:n}=Yd(t,null),i=LQ(t),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:Q0(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!==FR&&(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,mt.emptyBag)(),l=Xd(a)?[["IntroducedVersion",ef]]:[],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,mt.mergeAttrs)(a.a,l),c:(0,mt.spliceChildren)(a.c,u)}}areaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,mt.emptyBag)(),i=Xd(n),o=[],a=[];t.id&&o.push(["Id",t.id]),i&&o.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",ef]),t.icon!==void 0?o.push(["Icon",t.icon]):Zd(n.a,"Icon")&&a.push("Icon"),t.vectorIcon!==void 0?o.push(["VectorIcon",t.vectorIcon]):Zd(n.a,"VectorIcon")&&a.push("VectorIcon");let s=t.groups.map(u=>this.groupToRaw(u)),l=X0((0,mt.spliceChildren)(n.c,s),t.title,i,this.lcid);return{n:"Area",a:(0,mt.mergeAttrs)(n.a,o,a),c:l}}groupToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,mt.emptyBag)(),i=Xd(n),o=[];t.id&&o.push(["Id",t.id]),i&&o.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",ef],["IsProfile","false"]);let a=t.subAreas.map(l=>this.subAreaToRaw(l)),s=X0((0,mt.spliceChildren)(n.c,a),t.title,i,this.lcid);return{n:"Group",a:(0,mt.mergeAttrs)(n.a,o),c:s}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,mt.emptyBag)(),i=Xd(n),o=MQ(n.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]),BQ(a,t),i?(a.push(["ResourceId","SitemapDesigner.NewSubArea"],["Client","All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web"],["Sku","All,OnPremise,Live,SPLA"],["AvailableOffline","true"],["PassParams","false"]),t.icon&&a.push(["Icon",t.icon])):t.icon!==void 0?a.push(["Icon",t.icon]):Zd(o,"Icon",FR)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Zd(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",MR]):s.push("VectorIcon"):t.type==="GenPage"&&!FQ(o,"VectorIcon")&&a.push(["VectorIcon",MR]);let l=X0((0,mt.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,mt.mergeAttrs)(o,a,s),c:l}}};Qi.AppAdapter=tf;function Yd(e,t){let r=(0,tu.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,mt.rawFromNode)((0,tu.nodeLikeFromDom)(l))}),a+=1)}return{bag:{a:r,c:n},modeledEls:i}}function GR(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 Q0(e,t){var r;let n=GR(e,"Titles")[0];if(!n)return"";let o=GR(n,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(r=o.getAttribute("Title"))!==null&&r!==void 0?r:""}function LQ(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function Xd(e){return e.a.length===0&&e.c.length===0}function FQ(e,t){return e.some(([r])=>r===t)}function Zd(e,t,r){let n=e.find(([o])=>o===t),i=n?.[1];return!!i&&i!==r}function Y0(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function MQ(e,t){let r=$Q(t);return e.filter(([n])=>!PQ.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function $Q(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 BQ(e,t){var r,n,i,o,a;switch(t.type){case"Entity":e.push(["Entity",(r=t.entity)!==null&&r!==void 0?r:""]);break;case"URL":e.push(["Url",(n=t.url)!==null&&n!==void 0?n:""]);break;case"DashBoard":e.push(["DefaultDashboard",(i=t.dashboardId)!==null&&i!==void 0?i:""]),t.dashboardUrl!==void 0&&e.push(["Url",t.dashboardUrl]);break;case"CustomPage":e.push(["Page",(o=t.page)!==null&&o!==void 0?o:""]);break;case"GenPage":e.push(["GenPageId",(a=t.genPageId)!==null&&a!==void 0?a:""]);break;default:break}}function X0(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]=UQ(e[i],t,n),o}return r?[qQ(t,n),...e]:e}function UQ(e,t,r){let n=!1,i=e.c.map(o=>!n&&o.n==="Title"&&VQ(o,"LCID")===String(r)?(n=!0,{n:o.n,a:(0,mt.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return n||i.unshift(JR(t,r)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function qQ(e,t){return{n:"Titles",a:[],c:[JR(e,t)]}}function JR(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function VQ(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function GQ(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function rf(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${GQ(8)}`)}function Z0(e){var t;rf(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])QR(r)}function QR(e){var t;rf(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])rf(r,"subarea")}function WQ(e=zR.DEFAULT_LCID){return{adapter:new tf(e),api:WR.appApi,languageSensitive:!0,publish:(t,r)=>(0,_Q.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]}),rebaselineAfterPublish:"bracket"}}Qi.appRegistration=WQ});var XR={};Ir(XR,{ActionType:()=>ty,AppActionOrigin:()=>uy,AppActionVisibilityType:()=>ly,ButtonType:()=>ny,CannotUpdateAppActionColumns:()=>zQ,Context:()=>oy,IconType:()=>ry,Location:()=>iy,OnClickEventType:()=>sy,Scope:()=>ay,VisibilityType:()=>ey});var ey,ty,ry,ny,iy,oy,ay,sy,ly,uy,zQ,ZR=L(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(ey||(ey={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(ty||(ty={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(ry||(ry={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(ny||(ny={}));(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"})(iy||(iy={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(oy||(oy={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(ay||(ay={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(sy||(sy={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(ly||(ly={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(uy||(uy={}));zQ=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var a1=b(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.commandApi=Sr.COMMAND_ROW_NOT_IN_BAR_CODE=Sr.COMMAND_TABLE_MISMATCH_CODE=void 0;var cy=Mt(),lr=we(),Yi=X(),ur=ae();Sr.COMMAND_TABLE_MISMATCH_CODE="COMMAND_TABLE_MISMATCH";Sr.COMMAND_ROW_NOT_IN_BAR_CODE="COMMAND_ROW_NOT_IN_BAR";var jQ="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function dy(e,t){let r=`/EntityDefinitions(LogicalName='${(0,ur.odataPathLiteral)(t)}')${(0,ur.odataQuery)([["$select","MetadataId"]])}`,i=(0,lr.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,o=i?.MetadataId;return o?(0,ur.normalizeGuid)(o,"entityMetadataId"):""}function fy(e,t){return t?`_contextentity_value eq ${t}`:`contextvalue eq '${(0,ur.odataLiteral)(e)}'`}function ru(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 e1(e,t){let r=e.entityLogicalName;if(t===void 0)return r;if(typeof r!="string"||r.toLowerCase()!==t.toLowerCase())throw new Yi.SdkError(Sr.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 t1(e,t,r){let n=await dy(e,t);if(r){let i=(0,ur.normalizeGuid)(r,"entityMetadataId");if(i!==n)throw new Yi.SdkError(Sr.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. `+ru(t))}return n}Sr.commandApi={async get(e,t){let r=t,n=await dy(e,r),i=fy(r,n),o=`/appactions${(0,ur.odataQuery)([["$expand",jQ],["$filter",i]])}`,a,s=await(0,cy.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,ur.normalizeGuid)(d,"appactionid")]=typeof f=="string"?f:null}}return{raw:l,etag:a?(0,lr.readEtag)(a):null,memberEtags:u}},async list(e,t){let r=t?.entityLogicalName;return r?[{type:"command",id:r,name:`${r} commands`,entityLogicalName:r,isDirty:!1}]:[]},async create(e,t,r){let n=t,i=e1(n,r),o=await t1(e,i,n.entityMetadataId);return r1(e,i,{...n,entityMetadataId:o},!1)},async update(e,t,r,n,i){let o=r,a=e1(o,t),s=await t1(e,a,o.entityMetadataId);return r1(e,a,{...o,entityMetadataId:s},!0,i)},async delete(e,t){let r=await dy(e,t),n=`/appactions${(0,ur.odataQuery)([["$select","appactionid"],["$filter",fy(t,r)]])}`,i=await(0,cy.collectPages)(e,n,"deleteArtifact('command')");for(let o of i)o.appactionid&&await(0,lr.deleteRecord)(e,"appactions",o.appactionid)}};async function r1(e,t,r,n,i){let o=r.entityMetadataId?(0,ur.normalizeGuid)(r.entityMetadataId,"entityMetadataId"):"",a=await KQ(e,t,r,o,n,i),s={};try{await QQ(e,a,o,s)}catch(l){throw(0,Yi.withPartialTokens)(l,{memberEtags:s})}return{id:r.entityLogicalName,etag:null,memberEtags:s}}function o1(e){return e.replace(/[{}]/g,"").toLowerCase()}var HQ={entities:/^\/entities\(([^()]+)\)$/,appactions:/^\/appactions\(([^()]+)\)$/};function n1(e,t){let r=HQ[t].exec(e);return r?o1(r[1]):void 0}async function KQ(e,t,r,n,i,o){var a,s;let l=YQ(r.rows),u=new Set(l.map(f=>o1(f.appactionid))),c={writes:[],deletes:[]};for(let f of l){let p=f.body["[email protected]"];if(p!==void 0&&!(typeof p=="string"&&n!==""&&n1(p,"entities")===n))throw new Yi.SdkError(Sr.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' binds to ${typeof p=="string"?`'${p}'`:String(p)}, not to table '${t}' (${n?`/entities(${n})`:"whose id is not resolvable"}). `+ru(t));let m=f.body["[email protected]"];if(typeof m=="string"){let h=n1(m,"appactions");if(h===void 0||!u.has(h))throw new Yi.SdkError(Sr.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' would be placed under '${m}', which is not a row of this command. `+ru(t))}if(i&&f.exists){let h=(0,ur.normalizeGuid)(f.appactionid,"id"),g=(a=o?.[h])!==null&&a!==void 0?a:f.etag;if(!(0,lr.isVersionToken)(g))throw i1(t,h,"update",g);c.writes.push({kind:"patch",row:f,id:h,token:g})}else{if(p===void 0&&!n)throw new Yi.SdkError("COMMAND_CONTEXT_ENTITY_UNRESOLVED",`Cannot create app action '${f.appactionid}' for entity '${r.entityLogicalName}': the entity MetadataId could not be resolved, so the required ContextEntity bind cannot be set. A row written without it is created but is permanently unreadable \u2014 commandApi.get filters on _contextentity_value. Verify the entity logical name exists and is readable, then retry.`);c.writes.push({kind:"post",row:f})}}for(let f of(s=r.deletedRowIds)!==null&&s!==void 0?s:[]){let p=(0,ur.normalizeGuid)(f,"id"),m=o?.[p];if(!(0,lr.isVersionToken)(m))throw i1(t,p,"delete",m);c.deletes.push({id:p,token:m})}let d=[...c.writes.flatMap(f=>f.kind==="patch"?[{id:f.id,verb:"update"}]:[]),...c.deletes.map(f=>({id:f.id,verb:"delete"}))];if(d.length>0){let f=await JQ(e,t,n),p=d.find(m=>!f.has(m.id));if(p)throw new Yi.SdkError(Sr.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': it would ${p.verb} app action '${p.id}', which is not in table '${t}''s command bar on the server \u2014 a row of another table, or one deleted since the fetch. `+ru(t))}return c}function i1(e,t,r,n){return new Yi.SdkError(lr.UPDATE_NO_ETAG_CODE,`Refusing to push command '${e}': ${typeof n=="string"&&n!==""?`the token held for app action '${t}' ('${n}') is not a version`:`no token is held for app action '${t}'`}, so its ${r} could not be made conditional and would overwrite or remove a concurrent edit. `+ru(e))}async function JQ(e,t,r){let n=`/appactions${(0,ur.odataQuery)([["$select","appactionid"],["$filter",fy(t,r)]])}`,i=await(0,cy.collectPages)(e,n,"pushArtifact('command') bar membership"),o=new Set;for(let a of i)typeof a.appactionid=="string"&&o.add((0,ur.normalizeGuid)(a.appactionid,"appactionid"));return o}async function QQ(e,t,r,n){for(let i of t.writes)if(i.kind==="patch"){let o=(0,lr.echoWrite)("appactionid",{"If-Match":i.token}),a=`/appactions(${i.id})${o.query}`,s=(0,lr.ensureSuccess)(await e.patch(a,i.row.body,o.options),e.apiUrl(a));n[i.id]=(0,lr.readEtag)(s)}else{let o=(0,lr.echoWrite)("appactionid"),a=`/appactions${o.query}`,s={...i.row.body};s["[email protected]"]===void 0&&(s["[email protected]"]=`/entities(${r})`);let l=(0,lr.ensureSuccess)(await e.post(a,s,o.options),e.apiUrl(a)),u=(0,lr.readCreatedId)(l,"appactionid");u&&(n[(0,ur.normalizeGuid)(u,"appactionid")]=(0,lr.readEtag)(l))}for(let{id:i,token:o}of[...t.deletes].reverse())await(0,lr.deleteRecord)(e,"appactions",i,o),delete n[i]}function YQ(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 b1=b(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.commandRegistration=hs.CommandAdapter=void 0;var Je=(ZR(),hr(XR)),s1=Tr(),Wr=kr(),XQ=a1(),ZQ=lt(),gs=ae(),hy="$ClientSvg:",gy=".svg",eY=2,tY=1,rY=1,c1="entityMetadataId",nY=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"]),nf=class{toArtifact(t){var r,n,i,o,a,s;let l=(r=t.appActions)!==null&&r!==void 0?r:[],u=(n=t.entityLogicalName)!==null&&n!==void 0?n:"",c=new Map;for(let p of l){let m=typeof p._parentappactionid_value=="string"&&p._parentappactionid_value?p._parentappactionid_value:"",h=(i=c.get(m))!==null&&i!==void 0?i:[];h.push(p),c.set(m,h)}let d=new Map;for(let p of(o=c.get(""))!==null&&o!==void 0?o:[]){let m=lY(p.location),h=(a=d.get(m))!==null&&a!==void 0?a:[];h.push(p),d.set(m,h)}let f=[];for(let[p,m]of d)f.push({location:p,groups:oY(m,c,h1(p),u)});return{id:u,entityLogicalName:u,commandBars:sY(f),bag:{a:[[c1,(s=t.entityMetadataId)!==null&&s!==void 0?s:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:vy(t),appActions:py(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?py(r).map(l=>l.appactionid):[]),i=py(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?wY(l.row):v1(l.row)}}),s=[...n].filter(l=>!o.has(l));return{entityLogicalName:t.entityLogicalName,entityMetadataId:vy(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,ZQ.assignMissingIds)(t)}validate(t){let r=[];return(0,Wr.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,Wr.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",r),(0,Wr.childObjects)(i,"groups",a,"group",r).forEach(({node:l,index:u})=>{let c=`${a}/groups/${u}`;d1(l.bag)||((0,Wr.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."})),f1((0,Wr.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};hs.CommandAdapter=nf;function d1(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function f1(e,t,r){e.forEach(({node:n,index:i})=>{let o=`${t}/${i}`;d1(n.bag)||(0,Wr.optionalGuidId)(n,"id",o,"control-id-invalid",r),(0,Wr.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,Wr.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,Wr.isJsonObject)(n.action)?(0,Wr.optionalEnum)(n.action,"type",["javascript"],`${o}/action`,"action-type-invalid",r):r.push((0,Wr.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,Wr.childObjects)(n,"children",o,"control",r);s.length>0&&f1(s,`${o}/children`,r)})}function yy(e){return{a:Object.entries(e)}}function iY(e){return Object.fromEntries(e.a)}function of(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function vy(e){let t=of(e.bag,c1);return typeof t=="string"?t:""}function oY(e,t,r,n){var i,o;let a=[],s=[];for(let l of sf(e))l.type===Je.ButtonType.Group?a.push({id:m1(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:sf((o=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(u=>af(u,t,r,n)),bag:yy(l)}):s.push(af(l,t,r,n));return s.length>0&&a.unshift({id:bY(n,r),title:"",controls:s}),a}function by(e){let t=e.bag?of(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function af(e,t,r,n){var i,o,a,s,l;let u=m1(e.name,n),c={id:u,type:uY(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:yy(e)},d=p1(e);d&&(c.icon=d);let f=aY(e);f&&(c.action=f),typeof e.hidden=="boolean"&&(c.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(c.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(c.location=e.location);let p=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(p&&p.length>0){let m=[],h=[];for(let g of sf(p))if(g.type===Je.ButtonType.Group){let v=(o=g.appactionid)!==null&&o!==void 0?o:"",w=yy(g);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(a=g.appactionid)!==null&&a!==void 0?a:void 0,c.flyoutGroupBag=w);let C=[];for(let E of sf((l=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let k=af(E,t,r,n);m.push(k),C.push(by(k))}h.push({id:v,bag:w,childIds:C})}else m.push(af(g,t,r,n));c.children=m,h.length>1&&(c.flyoutGroups=h)}return c}function p1(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(hy)?e.fonticon.slice(hy.length)+gy:e.fonticon}function aY(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 l1(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function sf(e){return[...e].sort((t,r)=>l1(t)-l1(r))}function sY(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 m1(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 lY(e){switch(e){case Je.Location.Form:case Je.Location.QuickForm:return"MainTab";case Je.Location.HomePageGrid:case Je.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function h1(e){switch(e){case"MainTab":return Je.Location.Form;case"HomeTab":return Je.Location.HomePageGrid;default:return Je.Location.SubGridStandard}}function uY(e){switch(e){case Je.ButtonType.Dropdown:return"FlyoutAnchor";case Je.ButtonType.Split:return"SplitButton";default:return"Button"}}function cY(e){switch(e){case"FlyoutAnchor":return Je.ButtonType.Dropdown;case"SplitButton":return Je.ButtonType.Split;default:return Je.ButtonType.Standard}}function dY(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function g1(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 py(e,t=new Set){var r,n,i,o;let a=[],s=vy(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=h1(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(p=>{var m;return(m=p.controls)!==null&&m!==void 0?m:[]}),d=c.length>0&&c.every(p=>!g1(p,t)),f=0;for(let p of(i=l.groups)!==null&&i!==void 0?i:[]){let m;if(dY(p)){let h=pY(p,u,void 0,e,s);a.push(h),m=h.appactionid}for(let h of(o=p.controls)!==null&&o!==void 0?o:[])y1(h,u,m,e,s,a,d?f:void 0,t),f+=1}}return a}function y1(e,t,r,n,i,o,a,s=new Set){var l;let u=fY(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=>!g1(h,s)),f=(h,g,v)=>{y1(h,t,g,n,i,o,d?v:void 0,s)},p=e.flyoutGroups;if(p&&p.length>0){let h=new Map(c.map(E=>[by(E),E])),g=new Set,v=0,w;for(let[E,k]of p.entries()){let R=k.id||(E===0?my(u.appactionid):Ay("flyout-group",`${u.appactionid}#${E}`)),T=u1(R,t,u.appactionid,n,i,k.bag);o.push(T);let I=T.appactionid;w===void 0&&(w=I);for(let P of k.childIds){let F=h.get(P);!F||g.has(P)||(g.add(P),f(F,I,v),v+=1)}}let C=w??my(u.appactionid);for(let E of c){let k=by(E);g.has(k)||(g.add(k),f(E,C,v),v+=1)}return}let m=e.flyoutGroupId||my(u.appactionid);o.push(u1(m,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,g]of c.entries())f(g,m,h)}function fY(e,t,r,n,i,o){let a=wy(e,t,r,n,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let l=p1(s);return e.location!==void 0&&(s.location=e.location),s.type=cY(e.type),s.buttonlabeltext=e.label,hY(s,e.icon,l),yY(s,e.action),gY(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function pY(e,t,r,n,i){let o=wy(e,t,r,n,i);return o.row.type=Je.ButtonType.Group,o.row.grouptitle=e.title,o}function u1(e,t,r,n,i,o){let a=wy({id:e,bag:o},t,r,n,i),s=a.row;return s["[email protected]"]=`/appactions(${(0,gs.normalizeGuid)(r,"Command flyout group id")})`,s.type=Je.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),a}function wy(e,t,r,n,i){let o,a,s,l;if(e.bag&&e.bag.a.length>0){o=iY(e.bag),a=!0;let u=of(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=of(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else l=e.id,o=mY(l,t,n,i),a=!1,s=null;return r?o["[email protected]"]=`/appactions(${(0,gs.normalizeGuid)(r,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==Je.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:l,exists:a,etag:s,row:o}}function mY(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:Je.Context.Entity,contextvalue:r.entityLogicalName,scope:Je.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,gs.normalizeGuid)(n,"Command context entity metadata id")})`),i}function hY(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,gs.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(gy)?hy+t.slice(0,t.length-gy.length):t,e.IconWebResourceId=null}function gY(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,gs.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===tY&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===rY)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function yY(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=eY,t.webResourceId){let r=(0,gs.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 vY(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 Ay(e,t){let r="";for(let n=0;n<4;n+=1)r+=vY(`${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 my(e){return Ay("flyout-group",e)}function bY(e,t){return Ay("loose-group",`${e}|${t}`)}function v1(e){let t={...e};for(let r of nY)delete t[r];return t}function wY(e){let t=v1(e);for(let r of Je.CannotUpdateAppActionColumns)delete t[r];return t}function AY(){return{adapter:new nf,api:XQ.commandApi,publish:(e,t,r)=>(0,s1.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,s1.boundEntityPublishScope)(t)}}hs.commandRegistration=AY});var A1=b(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});lf.chartApi=void 0;var CY=Mt(),cr=we(),Uo=ae(),w1="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",EY="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";lf.chartApi={async get(e,t){let r=(0,Uo.normalizeGuid)(t,"id"),n=await(0,cr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Uo.odataQuery)([["$select",w1]]);return{raw:(0,cr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,Uo.normalizeGuid)(t,"id"),n=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Uo.odataQuery)([["$select",w1]]),i=(0,cr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,cr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueryvisualizations${(0,Uo.odataQuery)([["$select",EY],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,Uo.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,CY.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,cr.echoWrite)("savedqueryvisualizationid"),o=`/savedqueryvisualizations${i.query}`,a=(0,cr.ensureSuccess)(await e.post(o,(0,cr.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,cr.resolveCreatedId)(a,"savedqueryvisualizationid","chart",r),etag:(0,cr.readEtag)(a)}},async update(e,t,r,n){let i=r,o=(0,Uo.normalizeGuid)(t,"id"),a=(0,cr.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,cr.requireEtag)(n,"chart",o)}),s=`/savedqueryvisualizations(${o})${a.query}`,l=(0,cr.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,cr.readEtag)(l)}},delete(e,t){return(0,cr.deleteRecord)(e,"savedqueryvisualizations",t)}}});var B1=b(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});vs.chartRegistration=vs.ChartAdapter=void 0;var Cy=Pi(),C1=kr(),On=Ri(),E1=Tr(),SY=A1(),Ey=Oi(),NY=lt(),DY=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],_Y=new Map(DY.map(e=>[e.toLowerCase(),e]));function I1(e){var t;return e&&(t=_Y.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function IY(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function TY(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="${ys(h.series.attribute)}" aggregate="${ys(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${ys(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${ys(h.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(h,g)=>{if(!h){l.push(g);return}let v=u.get(h);v?v.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="${ys(h)}">${g.join("")}</link-entity>`).join(""),f=l.join("")+d,p=i.map(h=>`<measurecollection><measure alias="${h.alias}" /></measurecollection>`).join(""),m=(r=(t=o[0])===null||t===void 0?void 0:t.alias)!==null&&r!==void 0?r:"";return`<datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="${ys(n)}">${f}</entity></fetch></fetchcollection><categorycollection><category alias="${m}">${p}</category></categorycollection></datadefinition>`}var uf=class{toArtifact(t){var r,n,i,o,a,s,l;(0,Ey.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,On.parseXmlRoot)(u,"<datadefinition/>"),f=(0,On.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:T1(f),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:R1(d),categories:k1(d),presentation:P1(f),dataBag:u?(0,On.projectElementBag)(d):void 0,presentationBag:c?(0,On.projectElementBag)(f):void 0,rowBag:PY(t.charttype,t.type)}}fromArtifact(t){(0,Ey.installDomShim)();let{datadescription:r,presentationdescription:n}=OY(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:S1(t.rowBag,"charttype"),type:S1(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,Ey.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,NY.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,C1.childObjects)(n,"series","","series",r),(0,C1.childObjects)(n,"categories","","category",r),r}};vs.ChartAdapter=uf;function PY(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 S1(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 T1(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return I1(t[r].getAttribute("ChartType"));return"Column"}function P1(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 cf(e){return e.getElementsByTagName("fetch")[0]}function O1(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 R1(e){let t=cf(e);if(!t)return[];let r=O1(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=I1(c));let d=a.getAttribute("alias");d&&(u.alias=d);let f=d??l,p=r.get(f);p&&(u.relatedEntity=p),i.push(u)}return i}function k1(e){var t;let r=cf(e);if(!r)return[];let n=O1(r),i=r.getElementsByTagName("attribute"),o=[];for(let a=0;a<i.length;a+=1){let s=i[a];if(((t=s.getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()!=="true")continue;let l=s.getAttribute("name");if(!l)continue;let u={attribute:l},c=s.getAttribute("dategrouping");c&&(u.dateGrouping=c);let d=s.getAttribute("alias");d&&(u.alias=d);let f=d??l,p=n.get(f);p&&(u.relatedEntity=p),o.push(u)}return o}function OY(e){if(!N1(e.dataBag)||!N1(e.presentationBag)){let o=TY(e);return{datadescription:o,presentationdescription:QY(e,o)}}let t=new DOMParser().parseFromString("<root/>","text/xml"),r=D1(e.dataBag,"datadefinition",t),n=D1(e.presentationBag,"Chart",t),i=R1(r);if(!Sy(e.series,i)){let o=Ny(r);RY(t,r,e.series);let a=Ny(r),s=a.length>0?a:e.series.map(()=>"");x1(t,n,s,o,e.chartType)}return Sy(e.categories,k1(r))||kY(t,r,e.categories),e.chartType!==T1(n)&&M1(n,e.chartType),Sy(e.presentation,P1(n))||$1(n,e.presentation),{datadescription:(0,On.serializeNode)(r),presentationdescription:(0,On.serializeNode)(n)}}function N1(e){return!!e&&(e.c.length>0||e.a.length>0)}function x1(e,t,r,n,i){let o,a=t.childNodes;for(let d=0;d<a.length;d+=1)if(a[d].nodeType===1&&a[d].tagName==="Series"){o=a[d];break}o||(o=e.createElement("Series"),t.insertBefore(o,t.firstChild));let s=[],l=o.childNodes;for(let d=0;d<l.length;d+=1)l[d].nodeType===1&&l[d].tagName==="Series"&&s.push(l[d]);let u=new Map;n.forEach((d,f)=>{let p=s[f];if(!p)return;let m=u.get(d);m?m.push(p):u.set(d,[p])});let c=r.map(d=>{let f=u.get(d),p=f&&f.length>0?f.shift():void 0;if(p)return p;let m=e.createElement("Series");m.setAttribute("ChartType",i);let h=s.length>0?s[0].getAttribute("ChartArea"):null;return h&&m.setAttribute("ChartArea",h),m});for(let d of s)o.removeChild(d);for(let d of c)o.appendChild(d)}function Ny(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 D1(e,t,r){let n={n:t,a:(0,Cy.mergeAttrs)(e.a,[]),c:(0,Cy.spliceChildren)(e.c,[])};return(0,Cy.rebuildRaw)(n,(0,On.domEngine)(r),null)}function RY(e,t,r){let n=cf(t),i=n?.getElementsByTagName("entity")[0];!n||!i||L1(e,t,i,UY(n),r,VY,{aliasPrefix:"aggregate_column",addRef:FY,removeRef:BY})}function kY(e,t,r){let n=cf(t),i=n?.getElementsByTagName("entity")[0];!n||!i||L1(e,t,i,qY(n),r,GY,{aliasPrefix:"groupby_column",addRef:MY,removeRef:$Y})}function L1(e,t,r,n,i,o,a){let s=new Map;for(let p of n){let m=p.getAttribute("alias");m&&s.set(m,p)}let l=new Set,u=[],c=(p,m)=>{var h;let g=WY(r,p),v=m.relatedEntity;(g??void 0)!==(v??void 0)&&((h=p.parentNode)===null||h===void 0||h.removeChild(p),_1(e,r,p,v))};for(let p of i){let m=p.alias?s.get(p.alias):void 0;m&&!l.has(m)?(o(m,p),c(m,p),l.add(m)):u.push(p)}let d=n.filter(p=>!l.has(p)),f=0;for(let p of u)if(f<d.length){let m=d[f];o(m,p),c(m,p),l.add(m),f+=1}else{let m=e.createElement("attribute"),h=p.alias||LY(t,a.aliasPrefix);m.setAttribute("alias",h),o(m,p),_1(e,r,m,p.relatedEntity),a.addRef(e,t,h)}for(let p of n)if(!l.has(p)){let m=p.getAttribute("alias");m&&a.removeRef(t,m),jY(p)}}function xY(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 LY(e,t){let r=xY(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function F1(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function FY(e,t,r){let n=F1(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 MY(e,t,r){let n=F1(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function $Y(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 BY(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"&&!KY(a)&&((r=a.parentNode)===null||r===void 0||r.removeChild(a))}}function UY(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 qY(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 VY(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function GY(e,t){e.setAttribute("name",t.attribute),e.setAttribute("groupby","true"),t.dateGrouping?e.setAttribute("dategrouping",t.dateGrouping):e.getAttribute("dategrouping")!==null&&e.removeAttribute("dategrouping")}function WY(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 _1(e,t,r,n){n?zY(e,t,n).appendChild(r):t.appendChild(r)}function zY(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 jY(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!HY(t))){let r=t.parentNode;r&&r.removeChild(t)}}function HY(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 KY(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function M1(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(!JY(r[i])){r[i].setAttribute("ChartType",t);return}}}function JY(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 $1(e,t){var r;let n=e.ownerDocument;if(t.palette!==void 0&&e.setAttribute("Palette",t.palette),t.showLegend!==void 0){let i=[],o=e.getElementsByTagName("Legends");for(let a=0;a<o.length;a+=1)i.push(o[a]);if(t.showLegend&&i.length===0){let a=n.createElement("Legends"),s=n.createElement("Legend");s.setAttribute("Name","Default"),a.appendChild(s),e.appendChild(a)}else if(!t.showLegend)for(let a of i)(r=a.parentNode)===null||r===void 0||r.removeChild(a)}if(t.title!==void 0){let i=e.getElementsByTagName("Title")[0];i&&(i.textContent=t.title)}}function QY(e,t){let r=(0,On.parseXmlRoot)(IY(),"<Chart/>");M1(r,e.chartType),$1(r,e.presentation);let n=Ny((0,On.parseXmlRoot)(t,"<datadefinition/>"));return n.length>0&&x1(r.ownerDocument,r,n,n.slice(0,1),e.chartType),(0,On.serializeNode)(r)}function Sy(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ys(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function YY(){return{adapter:new uf,api:SY.chartApi,publish:(e,t,r)=>(0,E1.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,E1.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}vs.chartRegistration=YY});var G1=b(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.dashboardApi=qo.dashboardEntity=void 0;var XY=Mt(),Xi=we(),bs=ae(),ZY=Pm(),U1=ol();function q1(e){return e&&e.toLowerCase()!=="none"?e:void 0}qo.dashboardEntity=q1;var V1="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",eX={select:V1,required:["name","type","objecttypecode","istabletenabled"]},tX="formid,name,type,objecttypecode",rX=0,nX=10;qo.dashboardApi={async get(e,t){let r=(0,bs.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,bs.odataQuery)([["$select",V1]]),i=(0,Xi.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,U1.assertSystemFormRecordKind)(i.body,r,"dashboard","fetch"),{raw:i.body,etag:(0,Xi.readEtag)(i)}},async list(e,t){let r=[`(type eq ${rX} or type eq ${nX})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,bs.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,bs.odataQuery)([["$select",tX],["$filter",r.join(" and ")]])}`;return(await(0,XY.collectPages)(e,n,"listArtifacts('dashboard')")).map(o=>{var a,s;let l=q1(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,Xi.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,Xi.ensureSuccess)(await e.post(o,(0,Xi.withClientMintedId)(a,"formid",r),i.options),e.apiUrl(o));return{id:(0,Xi.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Xi.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,ZY.patchSystemForm)(e,(0,bs.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,eX)},readContentThenToken(e,t){return qo.dashboardApi.get(e,t)},async delete(e,t){let r=(0,bs.normalizeGuid)(t,"id");return await(0,U1.assertSystemFormKind)(e,r,"dashboard"),(0,Xi.deleteRecord)(e,"systemforms",r)}}});var rk=b(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.dashboardRegistration=Rn.TILE_CLASS_ID=Rn.DashboardAdapter=void 0;var iu=Pi(),zr=Ri(),Dy=Tr(),nu=kr(),J1=G1(),_y=Oi(),Vo=lt(),Q1=ae(),Y1=ho(),iX=qg(),W1="0",Iy="10",oX=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"]]),aX="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",ff=class{constructor(t=Y1.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,o,a;(0,_y.installDomShim)();let s=(r=t.formxml)!==null&&r!==void 0?r:"",l=(0,zr.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:sX(t.type),entityLogicalName:(a=(0,J1.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:lX(l),components:z1(l,this.lcid),bag:(0,zr.projectElementBag)(l)}}fromArtifact(t){var r;return(0,_y.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?Iy:W1,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:j1(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}completeAsStored(t,r){return(0,iX.completeRecordAsStored)(t,r,this.lcid)}toApiPayload(t){return{name:t.name,description:t.description,formxml:j1(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?Iy:W1,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,o,a,s,l,u;(0,_y.installDomShim)();let c=(0,zr.parseXmlRoot)(AX(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,Vo.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:z1(c,this.lcid),bag:(0,zr.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,Vo.newId)())}return t}validate(t){let r=[],n=(0,nu.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,nu.isJsonObject)(u)&&r.push((0,nu.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,nu.isJsonObject)(o.position)){let l=ou(o.position);i.has(l)?r.push((0,nu.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};Rn.DashboardAdapter=ff;function sX(e){return String(e??"")===Iy?"Interactive":"Standard"}function lX(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),r=parseInt(t??"",10);return Number.isNaN(r)?0:r}function ne(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 z1(e,t){let r=[];return ne(e,"tabs").flatMap(i=>ne(i,"tab")).forEach((i,o)=>{ne(i,"columns").flatMap(s=>ne(s,"column")).forEach((s,l)=>{ne(s,"sections").flatMap(c=>ne(c,"section")).forEach((c,d)=>{uX(c,{tabIndex:o,columnIndex:l,sectionIndex:d},r,t)})})}),r}function uX(e,t,r,n){ne(e,"rows").flatMap(o=>ne(o,"row")).forEach((o,a)=>{ne(o,"cell").forEach((s,l)=>{let u=cX(s,{...t,rowIndex:a,cellIndex:l},n);u&&r.push(u)})})}function cX(e,t,r){var n,i;let o=ek((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(o.toLowerCase().startsWith("spacer"))return null;let a=ne(e,"control")[0];if(!a)return null;let s=(i=a.getAttribute("classid"))!==null&&i!==void 0?i:"",l=pX(a),u=mX(s,l,a),c=dX(a);return{id:a.getAttribute("id")||o,type:u,name:Z1(e,r),classId:s,position:t,colspan:Ty(e,"colspan",1),rowspan:Ty(e,"rowspan",1),parameters:l,bag:(0,zr.projectElementBag)(e),...c?{icProperties:c}:{}}}function X1(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 dX(e){let t=X1(e);return t?(0,zr.serializeNode)(t):void 0}function fX(e,t,r){let n=X1(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,o=(0,iu.rebuildRaw)((0,iu.rawFromNode)((0,zr.nodeLikeFromDom)(i)),(0,zr.domEngine)(e),null);n&&(0,zr.serializeNode)(n)===(0,zr.serializeNode)(o)||(n?t.replaceChild(o,n):t.appendChild(o))}function Z1(e,t){var r,n;let i=ne(e,"labels")[0];if(!i)return"";let o=ne(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 pX(e){var t;let r={},n=ne(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 mX(e,t,r){var n;let i=oX.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"&&((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===aX?"assistant":i:"unknown"}function Ty(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 ek(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function hX(e,t){let r={n:"form",a:(0,iu.mergeAttrs)(e.bag.a,[]),c:(0,iu.spliceChildren)(e.bag.c,[])};return(0,iu.rebuildRaw)(r,(0,zr.domEngine)(t),null)}function j1(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=hX(e,r);return vX(r,n,e.components,t),gX(r,n,e.components,t),(0,zr.serializeNode)(n)}function gX(e,t,r,n){let i=tk(t);for(let o of r)i.has(ou(o.position))||yX(e,t,o,n)}function yX(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=CX(t,e,l);for(let F of ne(u,"row"))ne(F,"cell").some(z=>ne(z,"control").length>0)||u.removeChild(F);let c=r.classId||Rn.TILE_CLASS_ID[r.type]||Rn.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,f=r.bag&&H1(r.bag,"id")?String(H1(r.bag,"id")):df((0,Vo.newId)()),p=r.id?df(r.id):df((0,Vo.newId)()),m=u.parentNode,h=Math.max(1,parseInt(m&&m.getAttribute&&m.getAttribute("columns")||"1",10)||1),g=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),h),v=ne(u,"row"),w=v[v.length-1],C=w?ne(w,"cell").reduce((F,z)=>F+Ty(z,"colspan",1),0):0;(!w||C+g>h)&&(w=e.createElement("row"),u.appendChild(w));let E=e.createElement("cell");E.setAttribute("id",f),E.setAttribute("colspan",String(g)),E.setAttribute("rowspan",String(d)),E.setAttribute("showlabel","true");let k=e.createElement("labels"),R=e.createElement("label");R.setAttribute("description",(a=r.name)!==null&&a!==void 0?a:""),R.setAttribute("languagecode",String(n)),k.appendChild(R),E.appendChild(k);let T=e.createElement("control");T.setAttribute("id",p),T.setAttribute("classid",df(c));let I=e.createElement("parameters"),P=(s=r.parameters)!==null&&s!==void 0?s:{};for(let F of Object.keys(P)){let z=(0,Q1.createSafeXmlElement)(e,F,"dashboard tile parameter");z.textContent=P[F],I.appendChild(z)}T.appendChild(I),E.appendChild(T),w.appendChild(E)}function H1(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function vX(e,t,r,n){var i;let o=tk(t),a=new Set(r.map(s=>ou(s.position)));for(let s of r){let l=o.get(ou(s.position));if(!l)continue;let u=ne(l,"control")[0];u&&(bX(e,l,s.name,n),wX(e,u,s.parameters),K1(l,"colspan",s.colspan),K1(l,"rowspan",s.rowspan),s.icProperties!==void 0&&fX(e,u,s.icProperties))}for(let[s,l]of o)a.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function tk(e){let t=new Map;return ne(e,"tabs").flatMap(n=>ne(n,"tab")).forEach((n,i)=>{ne(n,"columns").flatMap(a=>ne(a,"column")).forEach((a,s)=>{ne(a,"sections").flatMap(u=>ne(u,"section")).forEach((u,c)=>{ne(u,"rows").flatMap(f=>ne(f,"row")).forEach((f,p)=>{ne(f,"cell").forEach((m,h)=>{var g;ek((g=m.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||ne(m,"control")[0]&&t.set(ou({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:p,cellIndex:h}),m)})})})})}),t}function ou(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function bX(e,t,r,n){if(r===Z1(t,n))return;let i=ne(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let o=ne(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 wX(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let o=ne(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,Q1.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,o.appendChild(d)}}}function K1(e,t,r){var n;((n=e.getAttribute(t))!==null&&n!==void 0?n:"")!==String(r)&&e.setAttribute(t,String(r))}function AX(e=2){let t=`{${(0,Vo.newId)()}}`,r=`{${(0,Vo.newId)()}}`,n=`{${(0,Vo.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>`}Rn.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 df(e){return`{${e.replace(/[{}]/g,"")}}`}function CX(e,t,r){var n;let i=ne(e,"tabs").flatMap(u=>ne(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let o=ne(i,"columns").flatMap(u=>ne(u,"column"))[0];if(!o)throw new Error("addDashboardTile: dashboard formxml has no <column>");let a=ne(o,"sections").flatMap(u=>ne(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=ne(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function EX(e=Y1.DEFAULT_LCID){return{adapter:new ff(e),api:J1.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,Dy.publishBoundEntity)(t,n):(0,Dy.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,Dy.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}Rn.dashboardRegistration=EX});var Oy=b(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.readEveryInOrder=dr.readInOrder=dr.plainRead=dr.resolveReadConcurrency=dr.MAX_READ_CONCURRENCY=void 0;var nk=X();dr.MAX_READ_CONCURRENCY=8;function SX(e){if(e===void 0)return 1;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>dr.MAX_READ_CONCURRENCY)throw new nk.InvalidArgumentError(`readConcurrency must be a whole number from 1 to ${dr.MAX_READ_CONCURRENCY} (got ${typeof e=="string"?`'${e}'`:String(e)})`);return e}dr.resolveReadConcurrency=SX;var NX=e=>({ok:!0,value:e}),Py=e=>({ok:!1,error:e});function DX(e){let t=(async()=>e())().then(NX,Py);return{outcome:t,finish:async r=>{await r()},discard:async()=>{await t}}}dr.plainRead=DX;async function ik(e,t,r,n,i){if(!Number.isInteger(t)||t<1)throw new nk.InvalidArgumentError(`a read window holds a whole number of reads, at least 1 (got ${String(t)})`);let o=new Map,a=0,s=Promise.resolve(),l=!1,u=0,c,d=async f=>{if(l)return{refusal:new Error("The read was not started: an earlier read had already failed.")};try{let p=await r(e[f],f),m=p.outcome.catch(Py);return i==="stop"&&m.then(h=>{l=l||!h.ok}),{read:p,outcome:m}}catch(p){return l=l||i==="stop",{refusal:p}}};try{for(let f=0;f<e.length;f+=1){for(;a<e.length&&a<f+t;){let g=a;a+=1;let v=s.then(()=>d(g));o.set(g,v),s=v}let p=await o.get(f),m="read"in p?await p.outcome:Py(p.refusal);if(!m.ok&&i==="stop"){c={error:m.error};break}u=f+1,o.delete(f);let h=()=>n(m,e[f],f);"read"in p?await p.read.finish(h):await h()}}finally{l=!0;for(let f=u;f<a;f+=1){let p=await o.get(f);"read"in p&&await p.read.discard().catch(()=>{})}}if(c)throw c.error}function _X(e,t,r,n){return ik(e,t,r,(i,o,a)=>n(i.value,o,a),"stop")}dr.readInOrder=_X;function IX(e,t,r,n){return ik(e,t,r,n,"continue")}dr.readEveryInOrder=IX});var Ak=b(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});mf.genPageApi=void 0;var pf=Mt(),gk=Qs(),xe=we(),ue=ae(),ln=Ac(),Ge=X(),yk=lt(),ok=Oy();function TX(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 kn="uxagentprojects",Wo="uxagentprojectfiles",lu="agentconversationmessages",uu="uxagentprojectid",Ct="uxagentprojectfileid",zo="agentconversationmessageid",au=`${uu},name`,PX=`${Ct},filename,filetype`,vk=2e8,bk=200000001,jo={"MSCRM.IncludeUnpublished":"true"},Ry={};function Go(e,t){return{"MSCRM.VersioningChangeset":e,...jo,...t}}async function Ly(e,t,r,n){var i;let o=`/${t}(${r})`+(0,ue.odataQuery)([["$select",n]]),a=(0,xe.ensureSuccess)(await e.get(o,{headers:{...jo}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,xe.readEtag)(a)}}async function cu(e,t,r=jo){let n=`/${Wo}(${t})/filecontent/$value`,i=await e.get(n,{headers:{...r}});if(i.status===404)return{status:"unavailable",reason:"missing"};(0,xe.ensureSuccess)(i,e.apiUrl(n));let o=i.body,a=TX(o);if(a)return{status:"available",data:(0,ln.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,ln.utf8ToBase64)(o)};throw new Ge.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 wk(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function OX(e,t,r,n,i,o){if(!e.supportsBinaryPatch)throw new Ge.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=`/${Wo}(${t})/filecontent`,s=(0,ln.base64ToBytes)(n);(0,ue.assertNoControlChars)(r,"generative-page file name"),(0,xe.ensureSuccess)(await e.patchRaw(a,s,{headers:Go(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":wk(r),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function su(e,t,r=jo){let n=`/${Wo}`+(0,ue.odataQuery)([["$select",PX],["$filter",`_${uu}_value eq ${t}`]]);return(await(0,pf.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 ky(e,t){let r=`/${lu}`+(0,ue.odataQuery)([["$select",`${zo},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,pf.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{...jo}})}async function ak(e,t){var r,n,i;let{row:o,etag:a}=await Ly(e,kn,t,au),s=new Map;for(let{row:l,etag:u}of await su(e,t))s.set((0,ue.normalizeGuid)(String((r=l[Ct])!==null&&r!==void 0?r:""),Ct),{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 sk(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,ue.normalizeGuid)(c.id,"file id");u.add(d);let f=r?.rows.get(d);if(c.content.status==="retain"){if(!r)throw new Ge.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 Ge.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 Fy(e){let t=(0,ln.base64ToUtf8)(e);return(0,ln.utf8ToBase64)(t)===(0,ln.bytesToBase64)((0,ln.base64ToBytes)(e))?t:void 0}function RX(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?{[zo]:(0,ue.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${kn}(${e})`,message:t.message,messagecontext:JSON.stringify(f),messagesender:t.sender==="user"?vk:bk}}async function kX(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,ue.normalizeGuid)(f,"message id"));if(s.length===0)return r;let l=`/${lu}`+(0,ue.odataQuery)([["$select",`${zo},message,messagesender,_regardingobjectid_value`],["$filter",s.map(f=>`${zo} eq ${f}`).join(" or ")]]),u=await(0,pf.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{...jo}});if(u.length===0)return r;let c=new Map(u.map(f=>{var p;return[String((p=f[zo])!==null&&p!==void 0?p:"").toLowerCase(),f]})),d=[];for(let f of(i=r.messages)!==null&&i!==void 0?i:[]){let p=f.id?c.get((0,ue.normalizeGuid)(f.id,"message id")):void 0;if(!p){d.push(f);continue}if(!(String((o=p.message)!==null&&o!==void 0?o:"")===f.message&&Number(p.messagesender)===(f.sender==="user"?vk:bk)&&String((a=p._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new Ge.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 xy(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${kn}`,body:(0,xe.withClientMintedId)({name:t.name},uu,e),headers:Go(n)};case"createRow":return{method:"POST",path:`/${Wo}`,body:(0,xe.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${uu}@odata.bind`]:`/${kn}(${e})`},Ct,(0,ue.normalizeGuid)(t.file.id,"file id")),headers:Go(n)};case"renameRow":return{method:"PATCH",path:`/${Wo}(${(0,ue.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Go(n,{"If-Match":"*"})};case"content":{let i=Fy(t.data);if(i===void 0)throw new Ge.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,ue.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${Wo}(${(0,ue.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Go(n,{"x-ms-file-name":wk(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${Wo}(${t.fileId})`,headers:Go(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${kn}(${e})`,body:{name:t.name},headers:Go(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${lu}`,body:RX(e,t.turn,r,n)};default:{let i=t;throw new Ge.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function lk(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||Fy(r.data)!==void 0)}async function uk(e,t,r,n,i){await(0,gk.postChangeSet)(e,r.map(o=>xy(t,o,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function ck(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 OX(e,(0,ue.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=xy(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,xe.ensureSuccess)(c,e.apiUrl(l.path))}if(a.length===0)return{warnings:[],turnRecorded:!0};try{let s=a.map(l=>xy(t,l,n,i));if(e.supportsAtomicBatch)await(0,gk.postChangeSet)(e,s,`the conversation turn of generative page '${t}'`);else for(let l of s)(0,xe.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 dk(e,t,r,n,i,o,a){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...a,u]});try{let u=await ak(e,t),c=new Map;for(let C of r)(C.kind==="createRow"||C.kind==="renameRow"||C.kind==="content")&&c.set((0,ue.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,E]of c){let k=u.rows.get(C);k&&(k.filename!==E.name||k.filetype!==E.fileType)&&d.push(`file '${E.name}' is stored as '${k.filename}' (type ${k.filetype})`)}for(let C of r){if(C.kind!=="content")continue;let E=await cu(e,(0,ue.normalizeGuid)(C.file.id,"file id")),k=(0,ln.bytesToBase64)((0,ln.base64ToBytes)(C.data));(E.status!=="available"||E.data!==k)&&d.push(E.status==="available"?`file '${C.file.name}' holds ${(0,ln.base64ToBytes)(E.data).byteLength} byte(s) that differ from the ${(0,ln.base64ToBytes)(k).byteLength} written`:`file '${C.file.name}' holds no content`)}let f=new Set(r.filter(C=>C.kind==="content").map(C=>(0,ue.normalizeGuid)(C.file.id,"file id")));for(let[C,E]of c)!f.has(C)&&(await cu(e,C)).status==="available"&&d.push(`file '${E.name}' holds content this push did not write`);if(d.length>0)return l(`Generative page '${t}' was written, but reading it back does not match what was sent: ${d.join("; ")}. The local baseline is now unusable: re-fetch the page to see what the server holds \u2014 the next push will refuse rather than overwrite blind.`);let p=await ak(e,t),m=[...p.rows.keys()],h=p.etag!==u.etag||p.rows.size!==u.rows.size||m.some(C=>{var E,k;return((E=u.rows.get(C))===null||E===void 0?void 0:E.etag)!==((k=p.rows.get(C))===null||k===void 0?void 0:k.etag)}),g=m.length!==i.size||m.some(C=>!i.has(C)),v={},w=[];for(let[C,E]of p.rows){let k=c.has(C)||!o?E.etag:(s=o.get(C))!==null&&s!==void 0?s:null;v[C]=k,k!==E.etag&&w.push(E.filename)}return h||g||!p.etag||Object.values(v).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.`):xX({id:t,etag:p.etag,memberEtags:v},[...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 fk(e,t,r,n=e.readConcurrency){var i;let o=(0,ue.normalizeGuid)(t,"id"),{row:a,etag:s}=await Ly(e,kn,o,au),l=await su(e,o),u={},c=[];if(n>1)await(0,ok.readInOrder)(l,n,({row:f})=>{var p;let m=(0,ue.normalizeGuid)(String((p=f[Ct])!==null&&p!==void 0?p:""),Ct);return(0,ok.plainRead)(async()=>({fileId:m,content:await cu(e,m)}))},({fileId:f,content:p},{row:m,etag:h})=>{u[f]=h,c.push({...m,content:p})});else for(let{row:f,etag:p}of l){let m=(0,ue.normalizeGuid)(String((i=f[Ct])!==null&&i!==void 0?i:""),Ct);u[m]=p;let h=await cu(e,m);c.push({...f,content:h})}return{raw:r?{project:a,files:c,conversation:await ky(e,o)}:{project:a,files:c},etag:s,memberEtags:u}}mf.genPageApi={get(e,t,r){return fk(e,t,!0,r?.fileConcurrency)},getForRebaseline(e,t){return fk(e,t,!1)},async getPublished(e,t){var r,n;let i=(0,ue.normalizeGuid)(t,"id"),o=`/${kn}(${i})`+(0,ue.odataQuery)([["$select",au]]),a=await e.get(o);if(a.status===404)return null;(0,xe.ensureSuccess)(a,e.apiUrl(o));let s=(r=a.body)!==null&&r!==void 0?r:{},l={},u=[],c=await su(e,i,Ry);for(let{row:g,etag:v}of c){let w=(0,ue.normalizeGuid)(String((n=g[Ct])!==null&&n!==void 0?n:""),Ct);l[w]=v,u.push({...g,content:await cu(e,w,Ry)})}let d=g=>g.map(({row:v,etag:w})=>`${String(v[Ct])}@${String(w)}`).sort().join("|"),f=()=>new Ge.SdkError("GENPAGE_PUBLISHED_READ_MOVED",`The published projection of generative page '${i}' changed while it was being read, so what was read is not one published state. PublishXml is asynchronous \u2014 re-read shortly.`),p=await e.get(o);if(p.status===404)throw f();(0,xe.ensureSuccess)(p,e.apiUrl(o));let m=await su(e,i,Ry);if([(0,xe.readEtag)(a),(0,xe.readEtag)(p),...[...c,...m].map(g=>g.etag)].some(g=>!g))throw new Ge.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,xe.readEtag)(p)!==(0,xe.readEtag)(a)||d(m)!==d(c))throw f();return{raw:{project:s,files:u,conversation:[]},etag:(0,xe.readEtag)(a),memberEtags:l}},async list(e,t){let r=`/${kn}`+(0,ue.odataQuery)([["$select",au]]);return(await(0,pf.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{...jo}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[uu])!==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;hk(e,i);let o=r?(0,ue.normalizeGuid)(r,"id"):(0,yk.newId)();mk(e,o,i);let a=sk(o,i,void 0),s=pk(),l=[],u=!0;lk(e,a)?await uk(e,o,a,i,s):{warnings:l,turnRecorded:u}=await ck(e,o,a,i,s);let c=new Set(((n=i.files)!==null&&n!==void 0?n:[]).map(f=>(0,ue.normalizeGuid)(f.id,"file id"))),d=await dk(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,ue.normalizeGuid)(t,"id");hk(e,s);let u=await kX(e,l,s);mk(e,l,u);let c=await su(e,l),{row:d,etag:f}=await Ly(e,kn,l,au);if(n&&f&&n!==f)throw new Ge.SdkError(xe.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 Ge.SdkError(xe.VERSION_CONFLICT_CODE,`Cannot verify generative page '${l}' before writing: ${n?"the server did not return the page's current token":"no baseline token was recorded"}. This entity accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let p=new Map(c.map(({row:T})=>{var I,P;return[(0,ue.normalizeGuid)(String((I=T[Ct])!==null&&I!==void 0?I:""),Ct),{filename:String((P=T.filename)!==null&&P!==void 0?P:""),filetype:Number(T.filetype)}]})),m=new Set(p.keys()),h=new Set(((o=u.files)!==null&&o!==void 0?o:[]).map(T=>(0,ue.normalizeGuid)(T.id,"file id")));if(!i)throw new Ge.SdkError(xe.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(T=>T.toLowerCase()));for(let T of h)if(!m.has(T)&&g.has(T))throw new Ge.SdkError(xe.VERSION_CONFLICT_CODE,`Generative-page file '${T}' 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 T of m)if(!g.has(T))throw new Ge.SdkError(xe.VERSION_CONFLICT_CODE,`Generative-page file '${T}' 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 v=new Map(c.map(({row:T,etag:I})=>{var P;return[(0,ue.normalizeGuid)(String((P=T[Ct])!==null&&P!==void 0?P:""),Ct),I]}));for(let[T,I]of Object.entries(i)){let P=T.toLowerCase();if(!m.has(P))continue;let F=v.get(P);if(!I||!F)throw new Ge.SdkError(xe.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${P}' before writing: ${I?"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(I!==F)throw new Ge.SdkError(xe.VERSION_CONFLICT_CODE,`Generative-page file '${P}' changed on the server after this page was fetched (baseline ${I}, server ${F}) \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=sk(l,u,{rows:p,name:String((a=d.name)!==null&&a!==void 0?a:"")});if(w.length===0)return{id:l,etag:f,memberEtags:Object.fromEntries(c.map(({row:T,etag:I})=>{var P;return[(0,ue.normalizeGuid)(String((P=T[Ct])!==null&&P!==void 0?P:""),Ct),I]}))};let C=pk(),E=[],k=!0;lk(e,w)?await uk(e,l,w,u,C):{warnings:E,turnRecorded:k}=await ck(e,l,w,u,C);let R=await dk(e,l,w,u,h,v,E);return k?R:{...R,intentPending:!0}},async delete(e,t){var r;let n=(0,ue.normalizeGuid)(t,"id"),i=await ky(e,n);await(0,xe.deleteRecord)(e,kn,n);let o=new Set(i.map(l=>{var u;return String((u=l[zo])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),a=!1;try{for(let l of await ky(e,n)){let u=String((r=l[zo])!==null&&r!==void 0?r:"");u!==""&&o.add(u)}}catch{a=!0}let s=[];for(let l of o)try{await(0,xe.deleteRecord)(e,lu,l)}catch(u){u instanceof Ge.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||a)throw new Ge.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 ${lu} rows regarding '${n}'.`)}};function pk(){return`uxagentproject_${(0,yk.newId)()}`}function xX(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function mk(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 Ge.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 hk(e,t){var r,n;if(((r=t.files)!==null&&r!==void 0?r:[]).some(a=>a.content.status==="available"&&!a.unchanged)&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new Ge.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient implements neither patchRaw() nor postRaw(). A Dataverse File column is not writable through a JSON body, so proceeding would create the page and its rows and then fail, leaving a page whose source never uploaded.");if(((n=t.files)!==null&&n!==void 0?n:[]).some(a=>a.content.status==="available"&&!a.unchanged&&Fy(a.content.data)===void 0)&&!e.supportsBinaryPatch)throw new Ge.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 $k=b(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});As.genPageRegistration=As.GenPageAdapter=void 0;var LX=Ak(),FX=Tr(),Ce=kr(),bf=lt(),wf=Ac(),Ho=X(),Rk=Gm(),My=Pp(),Zi=2e8,kk=200000001,mi={source:{name:"src/pages/page.tsx",fileType:Zi},output:{name:"src/pages/page.compiled",fileType:kk},config:{name:"config.json",fileType:Zi},prompt:{name:"firstPrompt.json",fileType:Zi}},xk=Object.keys(mi),MX=["dataSources","model","connectorBindings","actionBindings"],$X=["userMessage","agentMessage"],Ck=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,BX={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},UX="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function Lk(e,t){var r;let n=e.replace(/[{}-]/g,"").toLowerCase(),i=[];for(let a=0;a<32;a+=1)i.push(parseInt((r=n[a])!==null&&r!==void 0?r:"0",16)^parseInt(t[a],16));i[12]=4,i[16]=i[16]&3|8;let o=i.map(a=>(Number.isNaN(a)?0:a).toString(16)).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function hf(e,t){return Lk(e,BX[t])}function qX(e,t){let r=Lk(e,UX),n=parseInt(r.slice(24),16)%2**47+(t==="agent"?1:0);return`${r.slice(0,24)}${n.toString(16).padStart(12,"0")}`}function Ek(e){return typeof e=="string"&&e.trim()!==""?e:(0,bf.newId)()}function pi(e){return(0,Ce.isJsonObject)(e)?e:{}}function ws(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function gf(e){return JSON.parse(JSON.stringify(e))}function VX(e){let t=pi(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function fu(e){if(!e||e.status!=="available")return;let t=(0,wf.base64ToUtf8)(e.data);return(0,wf.utf8ToBase64)(t)===e.data?t:void 0}function Fk(e,t,r){var n,i,o,a;return e.source!==void 0&&t!==void 0&&t?.source===e.source&&ws((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,Rk.isLoadableGenPageOutput)(r)}function GX(e,t){var r;try{return Fk(e,t,fu((r=e.bag)===null||r===void 0?void 0:r.output))}catch{return!1}}function yf(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,Ce.isJsonObject)(t)?t:void 0}catch{return}}function Sk(e,t){if(t===Zi&&e.includes("page.tsx"))return"source";if(t===kk&&e.includes(".compiled"))return"output";if(t===Zi&&e===mi.config.name)return"config";if(t===Zi&&e===mi.prompt.name)return"prompt"}function Nk(e){let t=e.toLowerCase();return xk.some(r=>mi[r].name.toLowerCase()===t)}function $y(e){return Object.fromEntries(e)}function Mk(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),$y(i)}function Dk(e){var t,r,n;return Mk({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},MX,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function _k(e){var t,r;return Mk({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},$X,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function Ik(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=$y(n)),!0}function Tk(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=$y(n)),!0}function pu(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 WX=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function Pk(e){return pu(e)?[]:WX.filter(t=>e[t]!==void 0).map(t=>(0,Ce.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 Ok(){return(0,Ce.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 vf(e){return{status:"available",data:(0,wf.utf8ToBase64)(e)}}function du(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 Af=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=pi(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(g=>{var v,w,C;let E=pi(g);return{id:String((v=E.uxagentprojectfileid)!==null&&v!==void 0?v:""),name:String((w=E.filename)!==null&&w!==void 0?w:""),fileType:Number((C=E.filetype)!==null&&C!==void 0?C:Zi),content:VX(E.content)}}),o=Array.isArray(r?.conversation)?r.conversation.map(g=>{var v,w;let C=pi(g);return{sender:Number(C.messagesender)===200000001?"agent":"user",message:String((v=C.message)!==null&&v!==void 0?v:""),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 v=Sk(g.name,g.fileType);v?((s.has(v)||g.name!==mi[v].name)&&(u=!1),s.set(v,g)):(Nk(g.name)&&(u=!1),l.push(g))}if(!u||s.size===0)return a(du(n,i));let c=du(n,l),d={rows:{}};for(let[g,v]of s)d.rows[g]=v.id;let f=s.get("source");if(f){let g=fu(f.content);if(g===void 0)return a(du(n,i));c.source=g}let p=s.get("output");p&&(d.output=p.content);let m=s.get("config");if(m){let g=yf(fu(m.content));if(!g||!Ik(c,d,g))return a(du(n,i))}let h=s.get("prompt");if(h){let g=yf(fu(h.content));if(!g||!Tk(c,d,g))return a(du(n,i))}return c.bag=d,a(c)}async toApiPayload(t,r,n){var i,o,a,s,l,u,c,d,f,p,m,h,g;if(r&&!ws((i=t.conversation)!==null&&i!==void 0?i:[],(o=r.conversation)!==null&&o!==void 0?o:[]))throw new Ho.ValidationError("genPage",t.id,[(0,Ce.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 v=Pk(t);if(v.length>0)throw new Ho.ValidationError("genPage",t.id,v);let w=[],C=r===void 0,E=C&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(pu(E)){let T=(s=(a=E.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},I=Te=>{var Qe;return(Qe=T[Te])!==null&&Qe!==void 0?Qe:hf(E.id,Te)},P=(Te,Qe,ce)=>{w.push({id:I(Te),name:mi[Te].name,fileType:mi[Te].fileType,content:Qe,unchanged:ce})};if(E.source!==void 0){P("source",vf(E.source),!C&&r?.source===E.source&&T.source!==void 0);let Te=fu((l=E.bag)===null||l===void 0?void 0:l.output);Fk(E,r,Te)?P("output",{status:"retain"},!0):P("output",vf(await this.compile(E,E.source,n)),!1)}else{if(T.source!==void 0)throw new Ho.ValidationError("genPage",E.id,[Ok()]);if(T.output!==void 0){if(!C&&!ws((u=r?.dataSources)!==null&&u!==void 0?u:[],(c=E.dataSources)!==null&&c!==void 0?c:[]))throw new Ho.ValidationError("genPage",E.id,[(0,Ce.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 F=Dk(E),z=!C&&r!==void 0&&ws(Dk(r),F);(C||T.config!==void 0||!z)&&P("config",vf(JSON.stringify(F)),z&&T.config!==void 0);let Ie=_k(E),yt=!C&&r!==void 0&&ws(_k(r),Ie);(T.prompt!==void 0||Object.keys(Ie).length>0&&!yt)&&P("prompt",vf(JSON.stringify(Ie)),yt&&T.prompt!==void 0)}for(let T of(d=E.files)!==null&&d!==void 0?d:[]){let I=(f=r?.files)===null||f===void 0?void 0:f.find(P=>P.id===T.id);w.push({id:T.id,name:T.name,fileType:T.fileType,content:T.content,unchanged:I!==void 0&&ws(I,T)})}let k=[];if(E.newTurn){let T=E.newTurn.id,I=P=>T?{id:qX(T,P)}:{};k.push({...I("user"),sender:"user",message:E.newTurn.prompt}),E.newTurn.agentMessage&&k.push({...I("agent"),sender:"agent",message:E.newTurn.agentMessage})}let R=(m=(p=E.bag)===null||p===void 0?void 0:p.config)!==null&&m!==void 0?m:{};return{name:E.name,files:w,...k.length>0?{messages:k,messageContext:{dataSources:(h=E.dataSources)!==null&&h!==void 0?h:[],model:(g=E.model)!==null&&g!==void 0?g:"",enabledTools:Array.isArray(R.enabledTools)?R.enabledTools:[],configurableTools:Array.isArray(R.configurableTools)?R.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:gf(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,o,a,s,l;if(!pu(t)&&!t.newTurn)return t;let u=gf(t);if(delete u.newTurn,!pu(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=xk.find(m=>mi[m].name===d.name&&mi[m].fileType===d.fileType);if(!f||u.files.some(m=>m.id===d.id)||(c.rows[f]=d.id,d.content.status!=="available"))continue;let p=(0,wf.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,Ik(u,c,(s=yf(p))!==null&&s!==void 0?s:{})):f==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,Tk(u,c,(l=yf(p))!==null&&l!==void 0?l:{}))}return u.bag=c,u}baselineContent(t){var r;let n={...t};return delete n.conversation,delete n.newTurn,n.files=[...(r=t.files)!==null&&r!==void 0?r:[]].sort((i,o)=>i.id<o.id?-1:i.id>o.id?1:0),n}normalize(t){let r=t.newTurn;return!(0,Ce.isJsonObject)(r)||typeof r.id=="string"&&Ck.test(r.id)?t:{...t,newTurn:{...r,id:(0,bf.newId)()}}}async compile(t,r,n){var i;let o=(i=t.dataSources)!==null&&i!==void 0?i:[],a=[],s=[];if(o.forEach((f,p)=>{var m;let h=(m=n?.resolveEntity)===null||m===void 0?void 0:m.call(n,f);h&&h.columnDetailComplete===!0?a.push(h):s.push((0,Ce.issue)(`/dataSources/${p}`,h?"genpage-data-source-incomplete":"genpage-data-source-unresolved",h?`the column metadata of data source '${f}' could not be read completely (a choice or lookup request failed), 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 Ho.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new Ho.ValidationError("genPage",t.id,[(0,Ce.issue)("/source","genpage-compiler-unavailable","no TypeScript compiler is available to compile the page")]);let l=await n.loadTypeScript(),u=a.length>0?(0,My.buildGenPageRuntimeTypes)(a):void 0,c=a.length>0?(0,My.buildGenPageLegacyEnums)(a):void 0,d=(0,Rk.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new Ho.ValidationError("genPage",t.id,d.diagnostics.map(zX));return d.code}metadataNeeds(t,r){if(t.source===void 0||!Array.isArray(t.dataSources))return[];let n=GX(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=Ek(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:Ek(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=a.fileType)!==null&&l!==void 0?l:Zi,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=gf(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=gf(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:hf(i,"source"),output:hf(i,"output"),config:hf(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,bf.newId)()};if(!(0,Ce.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,bf.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,Ce.issue)(`/${s}`,"genpage-field-type",`${s} must be a string, got ${typeof n[s]}`));if(n.source===void 0&&pi(pi(n.bag).rows).source!==void 0&&r.push(Ok()),r.push(...Pk(t)),n.newTurn!==void 0){let s=pi(n.newTurn);(!(0,Ce.isJsonObject)(n.newTurn)||typeof s.prompt!="string"||s.prompt.trim()==="")&&r.push((0,Ce.issue)("/newTurn/prompt","genpage-turn-prompt","newTurn needs a non-empty prompt")),s.agentMessage!==void 0&&typeof s.agentMessage!="string"&&r.push((0,Ce.issue)("/newTurn/agentMessage","genpage-field-type","newTurn.agentMessage must be a string")),s.id!==void 0&&(typeof s.id!="string"||!Ck.test(s.id))&&r.push((0,Ce.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,Ce.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"||!My.TABLE_LOGICAL_NAME.test(l)?r.push((0,Ce.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,Ce.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,Ce.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,Ce.issue)("/files","files-must-be-array",`files must be an array, got ${typeof i}`)),r;let o=pu(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=pi(s),d=typeof c.id=="string"?c.id.trim().toLowerCase():"";if(d==="")r.push((0,Ce.issue)(u,"file-id-required","a generative-page file needs an id"));else{let g=a.get(d);g!==void 0?r.push((0,Ce.issue)(u,"file-id-duplicate",`two files share the id '${c.id}' (also at /files/${g}); a file's id is its identity, so a duplicate makes an edit ambiguous`)):a.set(d,l)}let f=typeof c.name=="string"?c.name:"",p=f.split("/");f===""||/[\u0000-\u001F\u007F]/.test(f)||f.includes("\\")||p.some(g=>g===""||g==="."||g==="..")?r.push((0,Ce.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&&(Nk(f)||Sk(f,Number(c.fileType))!==void 0)&&r.push((0,Ce.issue)(u+"/name","file-name-reserved",`'${f}' would be read by the maker portal as one of the page's managed rows (its source, output, config or first prompt), which the SDK writes from source and the configuration fields; it cannot also be a file in files[]`));let m=c.content;if(m===void 0){r.push((0,Ce.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=pi(m);h.status==="available"?typeof h.data!="string"&&r.push((0,Ce.issue)(u+"/content/data","file-content-data-invalid","available content needs base64 `data`")):h.status!=="unavailable"&&r.push((0,Ce.issue)(u+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(h.status)}`))}),r}};As.GenPageAdapter=Af;function zX(e){let t=`line ${e.line}, column ${e.column}`;return e.rule==="genpage-source-syntax"?(0,Ce.issue)("/source",e.rule,`${t}: ${e.message} (TS${e.code}) \u2014 the page cannot run, so it was not pushed`):(0,Ce.issue)("/source",e.rule,`${t}: ${e.message}`)}function jX(){return{adapter:new Af,api:LX.genPageApi,publish:(e,t)=>(0,FX.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}As.genPageRegistration=jX});var Uk=b(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});Sf.reconcileBpfSecurityRoles=void 0;var Ef=we(),Cf=ae(),HX="Global",Bk={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function KX(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,Cf.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,a=(n=(r=(0,Ef.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[],s={},l=new Set;return Object.keys(Bk).forEach(u=>{let c=a.find(d=>d.PrivilegeType===Bk[u]);if(c){let d=(0,Cf.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function JX(e,t){var r,n;let i=`/RetrieveRolePrivilegesRole(RoleId=${t})`,a=(n=(r=(0,Ef.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.RolePrivileges)!==null&&n!==void 0?n:[];return new Set(a.map(s=>(0,Cf.normalizeGuid)(s.PrivilegeId,"PrivilegeId")))}async function QX(e,t,r){if(r.length===0)return;let n={Privileges:r.map(o=>({Depth:HX,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,Ef.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function YX(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,Ef.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function XX(e,t,r){var n;if(!r||r.length===0)return;let i=await KX(e,t.toLowerCase());for(let o of r){let a=(0,Cf.normalizeGuid)(o.roleId,"roleId"),s=new Set(((n=o.access)!==null&&n!==void 0?n:[]).map(f=>i.byAccess[f]).filter(f=>!!f)),l=await JX(e,a),u=new Set([...l].filter(f=>i.all.has(f))),c=[...s].filter(f=>!u.has(f)),d=[...u].filter(f=>!s.has(f));await QX(e,a,c);for(let f of d)await YX(e,a,f)}}Sf.reconcileBpfSecurityRoles=XX});var Jk=b(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});_f.bpfApi=void 0;var fr=Ci(),qk=Qs(),ZX=Mt(),Et=X(),xt=we(),xn=ae(),eZ=Uk(),tZ=dp(),rZ={"Content-Type":"application/json",Accept:"application/json"},Nf={...rZ,Prefer:"return=representation"},nZ=new Set([408,502,503,504]),iZ=`category eq ${fr.WorkflowCategory.BusinessProcessFlow} and type eq ${fr.WorkflowTypeCode.Definition} and businessprocesstype eq ${fr.BusinessProcessType.BusinessFlow}`,oZ="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",aZ="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",sZ=["xaml","name","description","processorder"];async function By(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,eZ.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Kk(e,t,r){let n={statecode:fr.StateCode.Activated,statuscode:fr.StatusCode.Activated},i=`/workflows(${t})`,o={...Nf};return r&&(o["If-Match"]=r),(0,xt.ensureSuccess)(await e.patch(i,n,{headers:o}),e.apiUrl(i))}async function Vk(e,t,r){return(0,xt.readEtag)(await Kk(e,t,r))}function Gk(e,t){return new Et.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. `+Df(e))}async function mu(e,t){var r;let n=`/workflows(${t})${(0,xn.odataQuery)([["$select","statecode"]])}`,i=(0,xt.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 Et.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 Uy(e,t,r,n){if((n??await mu(e,t))!==fr.StateCode.Activated)return{deactivated:!1,etag:null};let i={statecode:fr.StateCode.Draft,statuscode:fr.StatusCode.Draft},o=`/workflows(${t})`,a={...Nf};r&&(a["If-Match"]=r);let s;try{s=await e.patch(o,i,{headers:a})}catch(u){return await Wk(e,t,u)}if(nZ.has(s.status))return await Wk(e,t,new Et.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' answered HTTP ${s.status} from an intermediary, so whether it committed is unknown.`));let l=(0,xt.ensureSuccess)(s,e.apiUrl(o));return{deactivated:!0,etag:(0,xt.readEtag)(l)}}async function Wk(e,t,r){let n;try{n=await mu(e,t)}catch{n=void 0}if(n===fr.StateCode.Draft)return{deactivated:!0,etag:null,uncertainCause:r};if(n===fr.StateCode.Activated)throw r;let i=new Et.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`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,Et.attachCause)(i,r),i}async function zk(e,t){let r=(0,xn.normalizeGuid)(t,"workflowid");try{return await Kk(e,r,null),"restored"}catch{try{let n=await mu(e,r);return n===fr.StateCode.Activated?"restored":n===fr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}}function jk(e,t,r,n){let i=`Original failure: ${n instanceof Error?n.message:String(n)}`,o=r==="disabled"?new Et.SdkError("BPF_LEFT_DEACTIVATED",`Business process flow '${e}' was deactivated ${t}, and it could NOT be reactivated \u2014 it is left DISABLED. ${i}`):new Et.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",`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. ${i}`);return(0,Et.attachCause)(o,n),o}async function lZ(e,t){try{return await mu(e,t),"survived"}catch(r){return r instanceof Et.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function uZ(e,t,r){if(r)try{let{deactivated:n,etag:i}=await Uy(e,t,r),o=n?i:r;if(o)return await(0,xt.deleteRecord)(e,"workflows",t,o),"removed"}catch{}return lZ(e,t)}function Df(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 Hk(e,t){return new Et.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. ${Df(e)}`)}function cZ(e,t){let r=new Et.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.) ${Df(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Et.attachCause)(r,t),r}function dZ(e,t){let r=new Et.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. ${Df(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Et.attachCause)(r,t),r}function fZ(e,t){let r=new Et.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,Et.attachCause)(r,t),r}function qy(e){let t={};for(let r of sZ)e[r]!==void 0&&(t[r]=e[r]);return t}var pZ=["name,processorder","description,name,processorder"];function mZ(e){let{xaml:t,...r}=qy(e);return typeof t=="string"&&pZ.includes(Object.keys(r).sort().join(","))}async function hZ(e,t,r,n){let{xaml:i,...o}=qy(r),[,a]=await(0,qk.sendChangeSet)(e,[{method:"PATCH",path:`/workflows(${t})`,body:o,etag:n},{method:"PATCH",path:`/workflows(${t})${(0,xn.odataQuery)([["$select","workflowid"]])}`,body:{xaml:i},headers:{Prefer:"return=representation"}}],`business process flow '${t}'`);return(0,xt.readEtag)((0,qk.partResponse)(a))}_f.bpfApi={async get(e,t){let n=`/workflows(${(0,xn.normalizeGuid)(t,"id")})${(0,xn.odataQuery)([["$select",aZ]])}`,i=(0,xt.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,xt.readEtag)(i)}},async list(e,t){let r=[iZ];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,xn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,xn.odataQuery)([["$select",oZ],["$filter",r.join(" and ")]])}`;return(await(0,ZX.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,xn.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",o=(0,xt.ensureSuccess)(await e.post(i,r.record,{headers:Nf}),e.apiUrl(i)),a=(0,xt.readEtag)(o);if(!a)throw Hk(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 Vk(e,n,a)),await By(e,r)}catch(l){let u=await uZ(e,n,s);throw u==="survived"?cZ(n,l):u==="unknown"?dZ(n,l):l instanceof Et.SdkError&&l.code===xt.VERSION_CONFLICT_CODE?fZ(n,l):l}if(!s)throw Hk(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,xn.normalizeGuid)(t,"id"),a=(0,xt.requireEtag)(n,"bpf",o),s=await mu(e,o);if(s===fr.StateCode.Activated&&i.status==="Active"&&e.supportsAtomicBatch&&mZ(i.record)){let d=await hZ(e,o,i.record,a);return await By(e,i),{id:o,etag:d}}let{deactivated:l,etag:u,uncertainCause:c}=await Uy(e,o,a,s);try{if(c!==void 0)throw c;let d=a;if(l){if(!u)throw Gk(o,"deactivation");d=u}let f=`/workflows(${o})`,p=(0,xt.ensureSuccess)(await e.patch(f,qy(i.record),{headers:{...Nf,"If-Match":d}}),e.apiUrl(f)),m=(0,xt.readEtag)(p);if(i.status==="Active"){if(!m)throw Gk(o,"definition write");m=await Vk(e,o,m)}return await By(e,i),{id:o,etag:m}}catch(d){if(l){let f=await zk(e,o);if(f!=="restored")throw jk(o,"to apply an edit, the edit failed",f,d)}throw d}},async delete(e,t){let r=(0,xn.normalizeGuid)(t,"id");await(0,tZ.assertWorkflowKind)(e,r,fr.WorkflowCategory.BusinessProcessFlow);let{deactivated:n}=await Uy(e,r,null);try{await(0,xt.deleteRecord)(e,"workflows",r)}catch(i){if(n){let o=await zk(e,r);if(o!=="restored")throw jk(r,"so it could be deleted, the delete failed",o,i)}throw i}}}});var Rx=b(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});Es.bpfRegistration=Es.BpfAdapter=void 0;var If=Ci(),gZ=Jk(),Vy=Pi(),Ko=Ri(),lx=Oi(),Nr=kr(),pr=lt(),Ln=X(),yZ=100,Wy='<?xml version="1.0" encoding="utf-16"?>',Qk=1033,ux="mxswa:Workflow",vZ="mxswa:ActivityReference.Properties",bZ="mcwo:StepLabel",wZ="mcwb:Control",Yk="mcwb:Control.ControlDisplayName",cx="mcwb:Control.DataFieldName",dx="DataFieldName",Xk="ControlDisplayName",fx="Literal",Tf="x:Null",Zk="x:String",zy="x:Key",jy="DisplayName",Of="Activities",AZ="StepLabels",px="StageId",mx="StageCategory",hx="NextStageId",gx="ProcessStepId",Hy="IsProcessRequired",yx="EntityComposite",vx="StageComposite",bx="StepComposite";function Gy(e){return(0,Nr.isJsonObject)(e)?e:{}}function Fn(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 Jo(e,t){var r;return(r=Fn(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function Mn(e){return Jo(e,vZ)}function Gt(e,t){var r;return(r=Fn(e).find(n=>n.getAttribute(zy)===t))!==null&&r!==void 0?r:null}function Cs(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function gi(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function wx(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function hu(e){var t;let r=(t=e.getAttribute(jy))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function Ax(e,t){var r;let n=(r=e.getAttribute(jy))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(jy,i>=0?n.slice(0,i+2)+t:t)}function Cx(e,t){let r=Gt(e,AZ),n=Jo(r,bZ);n&&n.setAttribute("Description",t)}function CZ(e){let t=Gt(e,mx);if(!t||t.tagName===Tf)return;let r=gi(t).trim();return r===""?void 0:Number(r)}function EZ(e){let t=Gt(e,hx);if(!t||t.tagName===Tf)return;let r=gi(t).trim();return r===""?void 0:r}function Ex(e){let t=Sx(e);if(!t)return;let r=Dx(t,dx,cx);return r===""?void 0:r}function Ky(e,t){let r=Fn(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of Fn(n))r.push(i)}return null}function Sx(e){let t=Gt(Mn(e),Of);return t?Ky(t,wZ):null}function Nx(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 Dx(e,t,r){var n;return Nx(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":IZ(e,r)}function ex(e,t,r,n){if(Nx(e,t)){e.setAttribute(t,n);return}if(Jo(e,r)){SZ(e,r,n);return}throw new Ln.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function SZ(e,t,r){let n=Jo(e,t),i=n?Ky(n,fx):null;i&&i.setAttribute("Value",r)}function _x(e){return hu(e)}function Rf(e){let t=Jo(e,ux),r=[];for(let n of Fn(t).filter(i=>Cs(i,yx))){let i=Gt(Mn(n),Of);for(let o of Fn(i).filter(a=>Cs(a,vx)))r.push({el:o,entity:_x(n)})}return r}function Jy(e){let t=Gt(Mn(e),Of);return Fn(t).filter(r=>Cs(r,bx))}function NZ(e){let t=Mn(e),r=gi(Gt(t,Hy)).trim().toLowerCase(),n=Ex(e),i={id:gi(Gt(t,gx)),name:hu(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function DZ(e,t){let r=Mn(e),n=CZ(r),i=EZ(r),o={id:gi(Gt(r,px)),name:hu(e),entityLogicalName:t,steps:Jy(e).map(NZ)};return n!==void 0&&(o.category=n),i!==void 0&&(o.nextStageId=i),o}function _Z(e){return Rf(e).map(({el:t,entity:r})=>DZ(t,r))}function hi(e){return new Ln.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 IZ(e,t){var r;let n=Jo(e,t),i=n?Ky(n,fx):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function Qy(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(Qy(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function Ix(e){return Gt(Mn(e),Of)}function TZ(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,pr.newId)(),{body:a}=kf(Yy(i,(0,pr.newId)(),t.id,o));return Qy(e,Rf((0,Ko.parseXmlRoot)(a,"<Activity/>"))[0].el)}function PZ(e,t){let{body:r}=kf(Yy("account",(0,pr.newId)(),(0,pr.newId)(),t.id));return Qy(e,Jy(Rf((0,Ko.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function Tx(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function Px(e,t,r,n){let i=Gt(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw hi(`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!==Tf){let s=t.createElement(Tf);s.setAttribute(zy,r),o.replaceChild(s,i)}return}if(i.tagName===Zk){gi(i)!==n&&wx(i,t,n);return}let a=t.createElement(Zk);a.setAttribute(zy,r),a.appendChild(t.createTextNode(n)),o.replaceChild(a,i)}function OZ(e,t,r){Px(e,t,mx,r===void 0?void 0:String(r))}function RZ(e,t,r){Px(e,t,hx,r)}function Ox(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 tx(e){return gi(Gt(Mn(e),px))}function rx(e){return gi(Gt(Mn(e),gx))}function nx(e,t,r){var n,i,o,a;let s=Mn(e);r.name!==hu(e)&&(Ax(e,r.name),Cx(s,r.name));let l=gi(Gt(s,Hy)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=Gt(s,Hy);u&&wx(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((o=Ex(e))!==null&&o!==void 0?o:"")){let u=Sx(e);if(!u)throw new Ln.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=r.fieldName)!==null&&a!==void 0?a:"";ex(u,dx,cx,c),c!==""&&Dx(u,Xk,Yk)===""&&ex(u,Xk,Yk,c)}}function ix(e,t,r,n){var i;let o=Mn(e);if(!o)throw new Ln.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==hu(e)&&(Ax(e,r.name),Cx(o,r.name)),OZ(o,t,r.category),RZ(o,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw hi("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw hi("stage actions or conditional branching");let a=Ix(e);if(!a)throw new Ln.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new Ln.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=Jy(e);if(Ox(l,s.map(d=>d.id),rx)){l.forEach((d,f)=>nx(d,t,s[f]));return}let u=new Map(l.map(d=>[rx(d),d]));if(Fn(a).some(d=>!Cs(d,bx)))throw hi("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:PZ(t,d)});Tx(a,c),c.forEach((d,f)=>nx(d,t,s[f]))}function kZ(e,t,r){let n=Jo(e,ux);if(!n)throw new Ln.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw hi("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new Ln.InvalidArgumentError("a BPF must have at least one stage");let i=Rf(e),o=i.map(f=>f.el);if(Ox(o,r.stages.map(f=>f.id),tx)){i.forEach(({el:f,entity:p},m)=>{let h=r.stages[m];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==p)throw hi(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${p}')`);ix(f,t,h,h.nextStageId)});return}let a=Fn(n).filter(f=>Cs(f,yx));if(a.length!==1)throw hi("adding, removing or reordering stages on a multi-table process");let s=a[0],l=_x(s),u=Ix(s);if(!u)throw new Ln.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(Fn(u).some(f=>!Cs(f,vx)))throw hi("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 hi(`a stage on a different table ('${f.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(o.map(f=>[tx(f),f])),d=r.stages.map(f=>{var p;return(p=c.get(f.id))!==null&&p!==void 0?p:TZ(t,f,l)});Tx(u,d),d.forEach((f,p)=>{let m=p<d.length-1?r.stages[p+1].id:void 0;ix(f,t,r.stages[p],m)})}function kf(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function xZ(e){var t,r,n,i,o,a;(0,lx.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let f=new DOMParser().parseFromString("<root/>","text/xml"),p={n:"Activity",a:(0,Vy.mergeAttrs)(s.a,[]),c:(0,Vy.spliceChildren)(s.c,[])};return{root:(0,Vy.rebuildRaw)(p,(0,Ko.domEngine)(f),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Wy,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=Yy(e.entityLogicalName,(0,pr.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,pr.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,pr.newId)()),{body:d}=kf(c);return{root:(0,Ko.parseXmlRoot)(d,"<Activity/>"),prolog:Wy,eol:"lf"}}function LZ(e){let{root:t,prolog:r,eol:n}=xZ(e);kZ(t,t.ownerDocument,e);let i=(0,Ko.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r
+`)),r+i}function FZ(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Pf=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,lx.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}=kf(o),u=(0,Ko.parseXmlRoot)(l,"<Activity/>");a.stages=_Z(u),a.bag={xaml:(0,Ko.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,pr.newId)(),name:t.name,uniquename:FZ(t),primaryentity:t.entityLogicalName,xaml:LZ(t),category:If.WorkflowCategory.BusinessProcessFlow,type:If.WorkflowTypeCode.Definition,businessprocesstype:If.BusinessProcessType.BusinessFlow,scope:If.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:yZ};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 Ln.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(ax):[ax({id:(0,pr.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,pr.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=Gy(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,pr.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,Nr.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,Nr.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=Gy(l),f=typeof d.id=="string"?d.id.trim():"";f===""?r.push((0,Nr.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(f.toLowerCase())?r.push((0,Nr.issue)(`${c}/id`,"stage-id-duplicate",`two stages share the id '${l.id}' (also at /stages/${a.get(f.toLowerCase())})`)):a.set(f.toLowerCase(),u),typeof l.entityLogicalName=="string"&&l.entityLogicalName!==""&&o.add(l.entityLogicalName);let p=Array.isArray(l.steps)?l.steps:[];p.length===0&&r.push((0,Nr.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),p.length>30&&r.push((0,Nr.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${p.length}`));let m=new Map;p.forEach((h,g)=>{let v=`${c}/steps/${g}`,w=typeof Gy(h).id=="string"?h.id.trim():"";w===""?r.push((0,Nr.issue)(`${v}/id`,"step-id-required","a step needs an id")):m.has(w.toLowerCase())?r.push((0,Nr.issue)(`${v}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):m.set(w.toLowerCase(),g)}),l.branch&&!ox(i,l.branch.nextStageId)&&r.push((0,Nr.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${l.branch.nextStageId}' does not match any stage id`)),typeof l.nextStageId=="string"&&l.nextStageId!==""&&!ox(i,l.nextStageId)&&r.push((0,Nr.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${l.nextStageId}' does not match any stage id`))}),o.size>5&&r.push((0,Nr.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=MZ(i);return s>=0&&r.push((0,Nr.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};Es.BpfAdapter=Pf;function MZ(e){let t=new Map(e.map(r=>[r.id,r]));for(let r=0;r<e.length;r+=1){let n=new Set,i=e[r];for(;i&&typeof i.nextStageId=="string"&&i.nextStageId!=="";){if(n.has(i.id))return r;n.add(i.id),i=t.get(i.nextStageId)}}return-1}function ox(e,t){return e.some(r=>r.id===t)}function ax(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(sx):[sx({id:(0,pr.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,pr.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 sx(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,pr.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 Yy(e,t,r,n){return`${Wy}<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="${Qk}" /></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="${Qk}" /></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 $Z(){return{adapter:new Pf,api:gZ.bpfApi,languageSensitive:!0}}Es.bpfRegistration=$Z});var kx=b(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});xf.buildRegistrations=void 0;var BZ=VP(),UZ=sO(),qZ=xR(),VZ=YR(),GZ=b1(),WZ=B1(),zZ=rk(),jZ=$k(),HZ=Rx();function KZ(e){let t=new Map;return t.set("form",(0,BZ.formRegistration)(e)),t.set("view",(0,UZ.viewRegistration)()),t.set("businessRule",(0,qZ.businessRuleRegistration)()),t.set("app",(0,VZ.appRegistration)(e)),t.set("command",(0,GZ.commandRegistration)()),t.set("chart",(0,WZ.chartRegistration)()),t.set("dashboard",(0,zZ.dashboardRegistration)(e)),t.set("genPage",(0,jZ.genPageRegistration)()),t.set("bpf",(0,HZ.bpfRegistration)()),t}xf.buildRegistrations=KZ});var jx=b(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE=_e.ROW_SUMMARY_MODEL_NOT_DELETED_CODE=_e.removeRowSummary=_e.configureRowSummary=_e.buildGptDynamicPrompt=_e.setAppAiFeatures=_e.getAiReadiness=_e.saveSettingValue=_e.retrieveSetting=_e.AI_GATE=void 0;var jr=we(),Me=ae(),xx=lt(),Dr=X();_e.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var Ux={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},JZ=new Set(Object.entries(_e.AI_GATE).filter(([e,t])=>Ux[e]===t).map(([e])=>e)),QZ={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function Xy(e){return QZ[e]}var Lf=1e6;function YZ(e,t){let r=Xy(t),n=()=>{throw new Dr.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Lf} (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>Lf?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(Lf).length||Number(s)>Lf?n():s}}return n()}function XZ(e,t){let r=Xy(t);return r?e===r.enabled:e!=="0"}async function ZZ(e,t){var r,n,i;let o=`/appmodules${(0,Me.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,Me.odataLiteral)(t)}'`]])}`,a=await e.get(o);return a.status>=200&&a.status<300?(i=((n=(r=a.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0])===null||i===void 0?void 0:i.appmoduleid:void 0}async function eee(e,t){var r,n;let i=`/appmodules${(0,Me.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,Me.odataLiteral)(t)}'`]])}`,o;try{o=await e.get(i)}catch(l){throw new Dr.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 Dr.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 Dr.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 Dr.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var Lx=new WeakMap;async function tee(e,t){var r,n,i;let o=Lx.get(e);if(o||(o=new Map,Lx.set(e,o)),o.has(t))return o.get(t);let a=`/settingdefinitions${(0,Me.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,Me.odataLiteral)(t)}'`]])}`,s=await e.get(a),l=s.status>=200&&s.status<300?(i=((n=(r=s.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0])===null||i===void 0?void 0:i.settingdefinitionid:void 0;return l&&o.set(t,l),l}async function ree(e,t,r){var n,i,o;let a=await tee(e,r);if(!t||!a)return;let s=`/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()${(0,Me.odataQuery)([["$select","value,componentstate"],["$filter",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${a}`]])}`,l=await e.get(s);if(l.status<200||l.status>=300)return;let u=(i=(n=l.body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[];if(u.length===0)return{exists:!1};let c=(o=u.find(d=>d?.componentstate===1))!==null&&o!==void 0?o:u[0];return{exists:!0,value:c.value,pendingPublish:c.componentstate===1}}var nee=4,iee=500,Fx=20,Mx=3e4;function oee(e){if(e===void 0)return nee;if(!Number.isFinite(e))throw new Dr.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${Fx}; got ${e}.`);return Math.min(Fx,Math.max(1,Math.floor(e)))}function aee(e){if(e===void 0)return iee;if(!Number.isFinite(e))throw new Dr.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${Mx}; got ${e}.`);return Math.min(Mx,Math.max(0,Math.floor(e)))}async function see(e,t,r,n,i,o,a){let s,l,u,c=!1;for(let d=0;d<o;d+=1){d>0&&await new Promise(p=>setTimeout(p,a*d));let f;try{let p=await t();p?(f=await ree(e,p,n),f===void 0&&(u="the app-scope override row could not be read (insufficient access or unresolvable ids)")):u=`the app '${r}' could not be resolved to an appmoduleid \u2014 a newly created app is not readable until it is published, so either publish it first or pass \`appModuleId\` in the options to verify without the lookup`}catch(p){f=void 0,u=p.message}c=f!==void 0,l=f?.exists;try{s=(await Ff(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 qx(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?Xy(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function Ff(e,t,r={}){var n,i;let o=[`SettingName='${(0,Me.odataPathLiteral)(t)}'`];r.appUniqueName&&o.push(`AppUniqueName='${(0,Me.odataPathLiteral)(r.appUniqueName)}'`);let a=`/RetrieveSetting(${o.join(",")})`,l=(i=(n=(0,jr.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.SettingDetail)!==null&&i!==void 0?i:{};return{value:l.Value,dataType:l.DataType}}_e.retrieveSetting=Ff;async function Vx(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,jr.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}_e.saveSettingValue=Vx;async function lee(e,t={}){let r={};for(let[n,i]of Object.entries(_e.AI_GATE)){let{value:o,dataType:a}=await Ff(e,i,t);r[n]={enabled:qx(o,a,n),setting:i,value:o}}return r}_e.getAiReadiness=lee;async function uee(e,t,r,n={}){var i,o;if(!t||!t.trim())throw new Dr.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let a=oee(n.verifyAttempts),s=aee(n.verifyDelayMs),l=[];for(let[h,g]of Object.entries(r)){if(g===void 0)continue;let v=Ux[h];v&&l.push({feature:h,setting:v,requestedValue:YZ(g,h)})}let u=[],c=n.appModuleId?(0,Me.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(c){let h=await eee(e,t);if(h&&(0,Me.normalizeGuid)(h,"appModuleId")!==c)throw new Dr.InvalidArgumentError(`setAppAiFeatures: appModuleId '${c}' does not belong to app '${t}' (which resolves to '${h}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let d,f=async()=>c||(d||(d=await ZZ(e,t)),d),p=new Map,m=async h=>{if(JZ.has(h))return;let g=_e.AI_GATE[h];if(g){if(!p.has(g))try{let{value:v,dataType:w}=await Ff(e,g);p.set(g,{enabled:qx(v,w,h),setting:g,value:v})}catch{p.set(g,void 0)}return p.get(g)}};for(let{feature:h,setting:g,requestedValue:v}of l)try{await Vx(e,g,v,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let w=await see(e,f,t,g,v,a,s),C={feature:h,setting:g,requestedValue:v,effectiveValue:w.effectiveValue,appOverrideExists:w.appOverrideExists};if(w.result==="proven")u.push({...C,status:"applied",...w.pendingPublish?{pendingPublish:!0}:{}});else if(w.result==="absent"){let E=XZ(v,h)?await m(h):void 0;E&&!E.enabled?u.push({...C,status:"skipped",reason:`the write was issued and no app-scope override holding '${v}' was observed for '${g}' after ${a} attempt(s); the org readiness gate '${E.setting}' reads '${E.value}', so an environment admin must enable it before this app can turn the feature on`}):u.push({...C,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${v}' was observed for '${g}' after ${a} attempt(s) \u2014 it reads '${(i=w.effectiveValue)!==null&&i!==void 0?i:""}' for this app (Dataverse can accept an app-scope write without storing it)`})}else u.push({...C,status:"unverified",reason:`the write was issued but could not be confirmed: ${(o=w.reason)!==null&&o!==void 0?o:"the app-scope override row could not be read"}. The value may or may not be in force \u2014 verify manually before relying on it.`})}catch(w){u.push({feature:h,setting:g,requestedValue:v,status:"failed",reason:w.message})}return{applied:u.filter(h=>h.status==="applied").map(h=>h.feature),skipped:u.filter(h=>h.status==="skipped").map(h=>h.feature),notPersisted:u.filter(h=>h.status==="notPersisted").map(h=>h.feature),unverified:u.filter(h=>h.status==="unverified").map(h=>h.feature),failed:u.filter(h=>h.status==="failed").map(h=>h.feature),outcomes:u}}_e.setAppAiFeatures=uee;var cee="GptPowerPrompt",dee='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function Gx(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:""}}_e.buildGptDynamicPrompt=Gx;async function fee(e,t){var r,n;let i=`/EntityDefinitions(LogicalName='${(0,Me.odataPathLiteral)(t)}')${(0,Me.odataQuery)([["$select","MetadataId"]])}`;return(n=(r=(0,jr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.MetadataId)!==null&&n!==void 0?n:""}async function Wx(e){var t,r,n;let i=`/msdyn_aitemplates${(0,Me.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${cee}'`],["$top",1]])}`;return((n=(r=(t=(0,jr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||t===void 0?void 0:t.value)===null||r===void 0?void 0:r[0])!==null&&n!==void 0?n:{}).msdyn_aitemplateid}function zx(e){return`${e} row summary`}async function pee(e,t,r){var n;let i=`/msdyn_aimodels(${t})${(0,Me.odataQuery)([["$select","msdyn_name,_msdyn_templateid_value"]])}`,o=await e.get(i);if(o.status===404)return!1;let a=(n=(0,jr.ensureSuccess)(o,e.apiUrl(i)).body)!==null&&n!==void 0?n:{},s=await Wx(e);return typeof a.msdyn_name=="string"&&a.msdyn_name.toLowerCase()===zx(r).toLowerCase()&&typeof a._msdyn_templateid_value=="string"&&s!==void 0&&a._msdyn_templateid_value.toLowerCase()===s.toLowerCase()}async function mee(e,t,r={}){var n,i;let o=`ais_RowSummary_${t.entityLogicalName}`,a=`/aiskillconfigs${(0,Me.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,Me.odataLiteral)(o)}'`],["$top",1]])}`,s=((i=(n=(0,jr.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[])[0];if(s)return{modelId:s._aimodel_value,aiSkillConfigId:s.aiskillconfigid};let l=await Wx(e),u=(0,xx.newId)(),c=(0,xx.newId)(),d=JSON.stringify(Gx(t)),f={ModelId:u,RunConfigurationId:c,ModelName:zx(t.entityLogicalName),TemplateId:l,CustomConfiguration:d,Source:dee,RunConfiguration:""};(0,jr.ensureSuccess)(await e.post("/AIModelPublish",f),e.apiUrl("/AIModelPublish"));try{let p=await fee(e,t.entityLogicalName),m={uniquename:o,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${p})`,"[email protected]":`/msdyn_aimodels(${u})`,aiskill:"RowSummary"},h=(0,jr.ensureSuccess)(await e.post("/aiskillconfigs",m),e.apiUrl("/aiskillconfigs")),g=(0,jr.requireCreatedId)(h,"aiskillconfigid","row-summary skill");return{modelId:u,aiSkillConfigId:g}}catch(p){try{await e.delete(`/msdyn_aimodels(${u})`)}catch{}throw p}}_e.configureRowSummary=mee;async function hee(e,t){var r,n;let i=`ais_RowSummary_${t.entityLogicalName}`,o=`/aiskillconfigs${(0,Me.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,Me.odataLiteral)(i)}'`],["$top",1]])}`,a=((n=(r=(0,jr.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!a)return;let s=(0,Me.normalizeGuid)(a.aiskillconfigid,"aiskillconfigid"),l=a._aimodel_value?(0,Me.normalizeGuid)(a._aimodel_value,"_aimodel_value"):void 0,u=l?await pee(e,l,t.entityLogicalName):!1,c=t.entityLogicalName,d=`/aiskillconfigs(${s})`,f=await $x(e,d,`${d}${(0,Me.odataQuery)([["$select","aiskillconfigid"]])}`);if(f.kind==="failed")throw f.stillThere===void 0&&l&&u?(0,Dr.attachCause)(new Dr.SdkError(_e.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE,`Removing the row summary of '${c}' could not be confirmed: deleting its skill row failed (${Bx(f.failure)}) and the row could not be read back. If it is gone, its AI model '${l}' is left behind, unreferenced. Retry removeRowSummary: while the skill row exists it removes both; once it is gone, delete that model.`),f.failure):f.failure;if(l&&u){let p=`/msdyn_aimodels(${l})`,m=await $x(e,p,`${p}${(0,Me.odataQuery)([["$select","msdyn_aimodelid"]])}`,yee);if(m.kind==="failed")throw(0,Dr.attachCause)(new Dr.SdkError(_e.ROW_SUMMARY_MODEL_NOT_DELETED_CODE,`The row summary of '${c}' was removed, but its AI model '${l}' ${m.stillThere?"was not deleted":"could not be confirmed deleted"} (${Bx(m.failure)}). The model is no longer used by the row summary; delete it before configuring a row summary for '${c}' again, which needs its name.`),m.failure)}}_e.removeRowSummary=hee;_e.ROW_SUMMARY_MODEL_NOT_DELETED_CODE="ROW_SUMMARY_MODEL_NOT_DELETED";_e.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE="ROW_SUMMARY_REMOVAL_UNCONFIRMED";var gee="0x8004f01f";function yee(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()===gee}function vee(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 $x(e,t,r,n=()=>!1){let i;try{let o=await(0,jr.resendWhile)(vee,()=>e.delete(t));if(o.status>=200&&o.status<300||o.status===404)return{kind:"gone"};if(n(o))return{kind:"kept"};try{(0,jr.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 Bx(e){return e instanceof Error?e.message:String(e)}});var Jx=b(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.findArtifact=Ss.resolveArtifact=void 0;var St=ae(),yi=bc(),bee=Oc(),wee=Mt(),Aee=we(),Hx=X();async function Kx(e,t,r){let n="/uxagentprojects"+(0,St.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,St.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,wee.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function Cee(e,t,r){var n,i,o,a,s,l,u,c,d,f,p,m,h;switch(t){case"app":{let g=(0,bee.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,St.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),w=(i=(0,Aee.ensureSuccess)(await e.get(g),e.apiUrl(g)).body)===null||i===void 0?void 0:i.value,C=w&&w[0];return C?[{id:String(C.appmoduleid),name:String(C.name),appModuleIdUnique:String(C.appmoduleidunique)}]:[]}case"dashboard":return(await(0,yi.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,St.odataLiteral)((o=r.name)!==null&&o!==void 0?o:"")}' and type eq 0`,top:10})||[]).map(v=>({id:String(v.formid),name:String(v.name)}));case"command":{let g=await(0,yi.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,St.odataLiteral)((a=r.entity)!==null&&a!==void 0?a:"")}'`,top:1});return g&&g.length?[{id:String(r.entity),entity:String(r.entity)}]:[]}case"form":return(await(0,yi.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,St.odataLiteral)((s=r.name)!==null&&s!==void 0?s:"")}' and objecttypecode eq '${(0,St.odataLiteral)((l=r.entity)!==null&&l!==void 0?l:"")}'`,top:10})||[]).map(v=>({id:String(v.formid),name:String(v.name)}));case"chart":return(await(0,yi.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,St.odataLiteral)((u=r.name)!==null&&u!==void 0?u:"")}' and primaryentitytypecode eq '${(0,St.odataLiteral)((c=r.entity)!==null&&c!==void 0?c:"")}'`,top:10})||[]).map(v=>({id:String(v.savedqueryvisualizationid),name:String(v.name)}));case"view":return(await(0,yi.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,St.odataLiteral)((d=r.name)!==null&&d!==void 0?d:"")}' and returnedtypecode eq '${(0,St.odataLiteral)((f=r.entity)!==null&&f!==void 0?f:"")}'`,top:10})||[]).map(v=>({id:String(v.savedqueryid),name:String(v.name)}));case"webResource":return(await(0,yi.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,St.odataLiteral)((p=r.name)!==null&&p!==void 0?p:"")}'`,top:1})||[]).map(v=>({id:String(v.webresourceid),name:String(v.name)}));case"solution":return(await(0,yi.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,St.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(v=>({id:String(v.solutionid),name:String(v.uniquename)}));case"genPage":return Kx(e,(h=r.name)!==null&&h!==void 0?h:"");default:return[]}}Ss.resolveArtifact=Cee;async function Eee(e,t,r){var n,i,o,a,s,l,u;let c=(0,St.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),d=(0,St.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){let g=await(0,yi.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,St.odataLiteral)((o=r.entity)!==null&&o!==void 0?o:"")}'`,top:1});return g&&g.length?String(r.entity):null}if(t==="genPage"){let g=await Kx(e,(a=r.name)!==null&&a!==void 0?a:"",2);if(g.length>1)throw new Hx.AmbiguousArtifactError(t,(s=r.name)!==null&&s!==void 0?s:"",g.length);return g.length===1?g[0].id:null}let f=See(t,c,d,r),p=t!=="app",m=await(0,yi.queryRecords)(e,f.set,{select:[f.idField],filter:f.filter,top:p?2:1});if(p&&m&&m.length>1)throw new Hx.AmbiguousArtifactError(t,(u=(l=r.name)!==null&&l!==void 0?l:r.uniqueName)!==null&&u!==void 0?u:"",m.length);let h=m&&m[0]&&m[0][f.idField];return h!=null?String(h):null}Ss.findArtifact=Eee;function See(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,St.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 Yx=b($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});$f.seedRecordGraph=void 0;var Qx=bc(),Nee=rc(),Mf=ae(),Dee=X();async function _ee(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,Nee.resolveEntitySetName)(e,f)),c={},d=f=>{var p;return(p=c[f])!==null&&p!==void 0?p:l[f]};for(let f of t){let p=f.entityLogical.toLowerCase(),m=(o=f.matchOn)===null||o===void 0?void 0:o.toLowerCase(),h=[];for(let R of f.records){let T={...R.body};for(let I of(a=R.binds)!==null&&a!==void 0?a:[]){let P=I.parentEntity.toLowerCase(),F=(s=d(P))===null||s===void 0?void 0:s[I.parentIndex];if(!F)throw new Dee.InvalidArgumentError(`Cannot resolve bind '${I.navProperty}' on a '${p}' record: parent '${I.parentEntity}'[${I.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let z=(0,Mf.assertODataName)(await u(P),`entity set for parent '${I.parentEntity}'`),Ie=(0,Mf.normalizeGuid)(F,`parent id for bind '${I.navProperty}'`);T[`${I.navProperty}@odata.bind`]=`/${z}(${Ie})`}h.push(T)}let g=m?h.map(R=>{let T=R[m];return T!=null&&T!==""?String(T):null}):h.map(()=>null),v=new Map;if(m){let R=(0,Mf.assertODataName)(m,"RecordGraph matchOn key"),T=[...new Set(g.filter(I=>I!==null))];if(T.length){let I=T.map(F=>`${R} eq '${(0,Mf.odataLiteral)(F)}'`).join(" or "),P=await(0,Qx.queryRecords)(e,p,{select:[R,`${p}id`],filter:I,top:5e3});for(let F of P??[]){let z=F[R];z!=null&&v.set(String(z).toLowerCase(),String(F[`${p}id`]))}}}let w=[],C=new Map,E=h.map((R,T)=>{let I=g[T];if(I&&v.has(I.toLowerCase()))return null;if(I){let P=I.toLowerCase(),F=C.get(P);if(F!==void 0)return F;let z=w.push(R)-1;return C.set(P,z),z}return w.push(R)-1}),k=w.length?await(0,Qx.createRecordsBulk)(e,p,w):[];c[p]=h.map((R,T)=>{let I=g[T];return I&&v.has(I.toLowerCase())?v.get(I.toLowerCase()):k[E[T]]})}return{createdIds:c}}$f.seedRecordGraph=_ee});var sL=b(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.getEntityPrivileges=Lt.addEntityPrivilegesToRole=Lt.deleteSecurityRole=Lt.createPersonaRole=Lt.createSecurityRole=Lt.SDK_ROLE_MARKER=void 0;var un=we(),ht=ae(),_r=X(),Bf={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},ev={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},Xx={user:1,businessUnit:2,parentChild:3,organization:4},Zy={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};Lt.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function Iee(e){return Object.prototype.hasOwnProperty.call(Bf,e)?Bf[e]:void 0}function Tee(e){return Object.prototype.hasOwnProperty.call(ev,e)}var Zx=new WeakMap,eL=new WeakMap;async function nL(e,t){var r,n;(0,ht.assertODataName)(t,"entity logical name");let i=Zx.get(e);i||(i=new Map,Zx.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,ht.odataPathLiteral)(t)}')${(0,ht.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,un.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 _r.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function Pee(e){var t,r,n;let i=eL.get(e);if(i)return i;let o=`/businessunits${(0,ht.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,un.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 _r.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,ht.normalizeGuid)(l,"businessUnitId");return eL.set(e,u),u}async function iL(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new _r.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let o=(r=i.scope)!==null&&r!==void 0?r:"user";if(!Tee(o))throw new _r.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await nL(e,i.entity);for(let s of i.access){let l=Iee(s);if(!l)throw new _r.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=a.find(m=>m.PrivilegeType===l);if(!u)throw new _r.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=Zy[o];if(u[c]===!1)throw new _r.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,ht.normalizeGuid)(u.PrivilegeId,"PrivilegeId"),f=n.get(d);if(!f){n.set(d,{privilegeName:u.Name,privilegeType:l,scope:o,entities:new Set([i.entity])});continue}if(f.scope===o){f.entities.add(i.entity);continue}if(!(f.entities.size===1&&f.entities.has(i.entity))){let m=[...f.entities].sort().join(", ");throw new _r.InvalidArgumentError(`Entities '${m}' and '${i.entity}' share the Dataverse privilege '${u.Name}' but request different scopes; a role holds one depth per privilege. Use the same scope for all entities that share this privilege, or split them.`)}f.scope=Xx[o]>Xx[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 Oee(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(a=>({Depth:ev[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,un.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function tL(e,t,r,n,i){var o,a;let s=`/${t}(${r})/${n}${(0,ht.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((a=(o=(0,un.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 Ree(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,ht.normalizeGuid)(l,"teamId");if(!await tL(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,un.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,ht.normalizeGuid)(l,"userId");if(!await tL(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,un.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}return{teams:o,users:a}}async function rL(e,t,r){var n,i;let o=`/roles${(0,ht.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,ht.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,un.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:"")===Lt.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new _r.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 _r.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,ht.normalizeGuid)(c,"roleId"):void 0}function kee(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,ht.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,ht.normalizeGuid)(n,"userId"))}}function oL(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function aL(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new _r.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,ht.normalizeGuid)(t.businessUnitId,"businessUnitId"):await Pee(e),a=await iL(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=kee(t.assignTo),l=await rL(e,i,o),u=l!==void 0;if(!l){let d="/roles",f={name:i,description:Lt.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let p=(0,un.ensureSuccess)(await e.post(d,f),e.apiUrl(d));l=(0,ht.normalizeGuid)((0,un.requireCreatedId)(p,"roleid","role"),"roleId")}catch(p){let m;try{m=await rL(e,i,o)}catch{m=void 0}if(!m)throw p;l=m}}await Oee(e,l,a,u);let c=await Ree(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:oL(a),assignedTeams:c.teams,assignedUsers:c.users}}Lt.createSecurityRole=aL;async function xee(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new _r.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 aL(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}Lt.createPersonaRole=xee;async function Lee(e,t){let n=`/roles(${(0,ht.normalizeGuid)(t,"roleId")})`;(0,un.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Lt.deleteSecurityRole=Lee;async function Fee(e,t,r){let n=(0,ht.normalizeGuid)(t,"roleId");if(r.length===0)throw new _r.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await iL(e,r),o={Privileges:i.map(s=>({Depth:ev[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,un.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),oL(i)}Lt.addEntityPrivilegesToRole=Fee;var Mee=new Map(Object.keys(Bf).map(e=>[Bf[e],e]));async function $ee(e,t){return(await nL(e,t)).map(n=>{let i=Object.keys(Zy).filter(a=>n[Zy[a]]!==!1),o=Mee.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...o?{access:o}:{},scopes:i}})}Lt.getEntityPrivileges=$ee});var SL=b(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.createMakerSdk=jt.MakerSdk=jt.PUSH_NOT_ATTEMPTED_CODE=jt.ALREADY_EXISTS_CODE=void 0;var lL=fp(),uL=Tr(),J=X(),Hr=ra(),Bee=Fb(),wL=Gb(),Ns=Jb(),Uee=mp(),qee=gw(),gu=vw(),Vee=Rw(),Gee=$w(),cL=kA(),gt=rc(),tv=Lm(),dL=FC(),Uf=ol(),vi=bc(),qf=GC(),Ds=Ec(),Wee=Nc(),Wt=Fm(),zee=Gm(),jee=Ym(),fL=Wm(),Hee=kx(),Vf=lt(),Kee=ho(),$n=j0(),Kr=bp(),rv=Oy(),Jee=3e5,zt=we(),Qo=ae(),_s=jx(),pL=Jx(),Qee=Yx(),Yee=l0(),yu=sL(),AL=Symbol("cds-maker-sdk.committedWrite");function Xee(e){return typeof e=="object"&&e!==null&&(e[AL]=!0),e}function Zee(e){return typeof e=="object"&&e!==null&&e[AL]===!0}var ete={fileConcurrency:1},nv="SOLUTION_COMPONENT_UNCLASSIFIED",tte=2,rte=4,nte="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 mL(e){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"unsupported",...e.includesAllSubcomponents?{detail:nte}:{}}}function hL(e,t){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"failed",error:eo(t)}}function gL(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,zt.nowIso)(),isDirty:!1}}var ite=new Set(["entity","appmodule","dashboard","uxagentproject"]);function ote(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,Qo.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 ate(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 wL.WorkspaceManager(lte,e.instanceUrl,(0,Uee.assertStorageContract)(t))}jt.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var ste="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";jt.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var lte="<injected workspaceStorage>",Gf=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 J.InvalidArgumentError(`createRecovery must be 'adoptExact' or omitted (got '${String(t.createRecovery)}').`);this.createRecovery=t.createRecovery,this.readConcurrency=(0,rv.resolveReadConcurrency)(t.readConcurrency),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:Kee.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:Jee,this.compiler={load:(0,zee.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=ate(t),this.versions=new Ns.VersionManager(this.workspace),this.dataverse=new qee.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName,this.readConcurrency),this.registrations=(0,Hee.buildRegistrations)(this.languageCode)}async initWorkspace(){await this.workspace.init()}async getManifest(){return this.workspace.getManifest()}async cleanWorkspace(){await this.workspace.clean()}withArtifactLock(t,r,n){var i;let o=this.artifactKey(t,r),s=((i=this.artifactLocks.get(o))!==null&&i!==void 0?i:Promise.resolve()).then(n,n),l=s.then(()=>{},()=>{});return this.artifactLocks.set(o,l),l.then(()=>{this.artifactLocks.get(o)===l&&this.artifactLocks.delete(o)}),s}async fetchArtifact(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.fetchArtifactUnlocked(t,r,n);return await this.acknowledgeRefresh(t,r),i})}async fetchArtifactUnlocked(t,r,n){let i=this.requireRegistration(t,"fetchArtifact"),o=await i.api.get(this.dataverse,r);return this.applyFetchedArtifactUnlocked(t,r,i,o,n)}async applyFetchedArtifactUnlocked(t,r,n,i,o){var a,s,l;let{raw:u,etag:c,memberEtags:d,siblingEtags:f}=i,p=n.adapter.fromApiResponse(u);if(!o?.overwrite&&await this.versions.isDirty(t,r)){let h=(s=(a=await this.versions.getMeta(t,r))===null||a===void 0?void 0:a.etag)!==null&&s!==void 0?s:null;if(h&&c&&h!==c)throw new J.LocalEditsWouldBeLostError(t,r,h,c);let g=await this.workspace.readArtifact(t,r);if(g){let v=await this.versions.getMeta(t,r);if(v&&!v.etag&&c){if(!(0,Kr.deepEqual)(v.snapshot,p))throw new J.LocalEditsWouldBeLostError(t,r,h,c);await this.versions.storeMeta(t,r,{...v,etag:c,fetchedAt:(0,zt.nowIso)()},v)}return(0,$n.cloneJson)(g)}}await this.workspace.writeArtifact(t,r,p);let m=await this.versions.getMeta(t,r);return await this.versions.storeMeta(t,r,{etag:c,languageCode:this.languageCode,projectionVersion:Ns.PROJECTION_VERSION,fetchedAt:(0,zt.nowIso)(),snapshot:(0,$n.cloneJson)(p),...d?{memberEtags:d}:{},...f?{siblingEtags:f}:{},...m?.refreshGeneration?{refreshGeneration:m.refreshGeneration,observedGeneration:(l=m.observedGeneration)!==null&&l!==void 0?l:0}:{}},m),(0,$n.cloneJson)(p)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){await this.workspace.ensureReady();let r=await(0,Wt.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(mL(o));continue}let s=await this.fetchArtifact(a,o.objectId);n.push(gL(a,o,s))}catch(a){i.push(hL(o,a))}return await this.workspace.updateManifest({lastSyncAt:(0,zt.nowIso)()}),{summaries:n,skipped:i}}async fetchComponentsOverlapped(t,r,n){await(0,rv.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(mL(o));return}let s=await this.applyFetchedArtifactUnlocked(a.type,o.objectId,a.reg,a.fetched);await this.acknowledgeRefresh(a.type,o.objectId),r.push(gL(a.type,o,s))}catch(a){n.push(hL(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,ete);return{kind:"artifact",type:r,reg:n,fetched:i}}):(0,rv.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,gu.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 J.WorkspaceNotInitializedError||r instanceof J.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,Vee.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,gu.findTables)(this.dataverse,t,r)}getEnvironmentLanguages(){return(0,Gee.getEnvironmentLanguages)(this.dataverse)}findColumns(t,r,n){return(0,gu.findColumns)(this.dataverse,t,r,n)}createTable(t){return this.schemaWrite([t.schemaName],()=>(0,gt.createTable)(this.dataverse,t))}createColumn(t,r){return this.schemaWrite([t],()=>(0,gt.createColumn)(this.dataverse,t,r))}createColumns(t,r){return this.schemaWrite([t],()=>(0,gt.createColumns)(this.dataverse,t,r))}updateColumn(t,r,n){return this.schemaWrite([t],()=>(0,gt.updateColumn)(this.dataverse,t,r,n))}deleteColumn(t,r){return this.schemaWrite([t],()=>(0,gt.deleteColumn)(this.dataverse,t,r))}setFormSecurityRoles(t,r){return(0,tv.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,tv.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,gt.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,gt.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return this.schemaWrite([t,"account","contact"],()=>(0,gt.createCustomerColumn)(this.dataverse,t,r))}insertStatusValue(t,r){return this.schemaWrite([t],()=>(0,gt.insertStatusValue)(this.dataverse,t,r))}updateTable(t,r){return this.schemaWrite([t],()=>(0,gt.updateTable)(this.dataverse,t,r))}async setEntityIcon(t,r){if(await this.schemaWrite([t],()=>(0,gt.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,Qo.xmlText)(t)}</entity></entities></importexportxml>`;(0,zt.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,gt.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,gt.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,gt.createRelationship)(this.dataverse,t))}deleteRelationship(t){return this.schemaWrite(void 0,()=>(0,gt.deleteRelationship)(this.dataverse,t))}createGlobalOptionSet(t){return(0,gt.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,gt.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return this.schemaWrite(void 0,()=>(0,gt.deleteTable)(this.dataverse,t))}createSecurityRole(t){return(0,yu.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,yu.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,yu.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,yu.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,yu.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,vi.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,vi.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,vi.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,vi.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,vi.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,vi.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,vi.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,Qee.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,pL.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,pL.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){await this.workspace.ensureReady();let n=await(0,jee.deleteAppCascade)(this.dataverse,t,r),i=(0,Qo.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,vi.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,vi.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,qf.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,qf.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,qf.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,qf.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,Ds.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,Ds.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new J.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:Wee.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,Ds.setAppSetting)(this.dataverse,t,Ds.HEADER_AND_NAVIGATION_REFRESH,r?Ds.APP_SETTING_ON:Ds.APP_SETTING_OFF)}getSolution(t){return(0,Wt.getSolution)(this.dataverse,t)}createPublisher(t){return(0,Wt.createPublisher)(this.dataverse,t)}createSolution(t){return(0,Wt.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,Wt.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,Wt.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,Wt.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,Wt.exportSolution)(this.dataverse,t)}importSolution(t){return this.schemaWrite(void 0,()=>(0,Wt.importSolution)(this.dataverse,t))}deleteSolution(t){return this.schemaWrite(void 0,()=>(0,Wt.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,wL.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 J.StaleArtifactError(t,r,n,"pushed");if(await this.revalidateIfStale(t,r)==="refreshed-changed")throw new J.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 J.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,Kr.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=Hr.JsonPointer.resolve(i,n);if(a===void 0)throw new J.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,Bee.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 J.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 J.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=Hr.JsonPointer.resolve(a,n);if(s===void 0)throw new J.PathNotFoundError(t,r,n);let l=bi(s)&&bi(i)?{...s,...i}:i;return Hr.JsonPointer.set(a,n,(0,$n.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=Hr.JsonPointer.resolve(s,n);if(l===void 0)throw new J.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!bi(l)||!bi(i))throw new J.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 J.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 J.ValidationError(t,r,n,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let p=(0,$n.cloneJson)(i[f]),m=(0,Vf.isValueMapKey)(f)||(0,Vf.pointerTouchesValueMap)(n);d[f]=m?p:Array.isArray(p)?p.map(h=>bi(h)?this.assignMissingIds(t,h):h):bi(p)?this.assignMissingIds(t,p):p}for(let f of Object.keys(d))Hr.JsonPointer.set(s,Hr.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,Vf.pointerTouchesValueMap)(n)?(0,$n.cloneJson)(i):this.assignMissingIds(t,(0,$n.cloneJson)(i)),c=fte(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=Hr.JsonPointer.resolve(l,n);if(u===void 0)throw new J.PathNotFoundError(t,r,n);let c=Hr.JsonPointer.resolve(l,i);if(c===void 0)throw new J.PathNotFoundError(t,r,i);if(!Array.isArray(c))throw new J.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new J.ValidationError(t,r,i,"cannot move an element into its own subtree");Hr.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),bL(c);let f=Hr.JsonPointer.resolve(l,vL(n));return Array.isArray(f)&&f!==c&&bL(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(Hr.JsonPointer.resolve(o,n)===void 0)throw new J.PathNotFoundError(t,r,n);return Hr.JsonPointer.remove(o,n),this.assertStructurallyValid(t,r,o,vL(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 J.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,_s.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,_s.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,_s.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,_s.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,_s.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,_s.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,Yee.findDefaultViews)(this.dataverse,t,{excludeViewIds:n.excludeViewIds}),o=n.publish===!1,a=[],s=[],l=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,uL.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&&Zee(c)&&a.push(u),o?(0,J.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 J.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 J.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,o,async()=>(await this.workspace.writeArtifact(t,o,i),(0,$n.cloneJson)(i)))}async deleteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.workspace.deleteArtifact(t,r)})}async deleteRemoteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let n=this.requireRegistration(t,"deleteRemoteArtifact");await this.workspace.ensureReady(),await n.api.delete(this.dataverse,r),await this.workspace.readArtifact(t,r)&&await this.workspace.deleteArtifact(t,r)})}async publishArtifact(t,r,n){let{result:i,siblings:o}=await this.withArtifactLock(t,r,()=>this.publishArtifactUnlocked(t,r,n));for(let a of o)await this.withArtifactLock(a.type,a.id,()=>this.adoptBracket(a));return i}async publishArtifacts(t,r){var n,i;let o=new Map;for(let m of t){let h=this.artifactKey(m.type,m.id);o.has(h)||o.set(h,{type:m.type,id:m.id})}let a=[];for(let[m,h]of o)a.push(await this.withArtifactLock(h.type,h.id,()=>this.preparePublish(m,h.type,h.id)));let s=new Set(o.keys()),l=[],u=new Set;for(let m of a){let h=((n=m.scope)===null||n===void 0?void 0:n.envelope)==="entity"?(i=m.scope.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;m.scope&&h&&!u.has(h)&&(u.add(h),l.push(m.scope))}let c=await this.captureSiblings(l,s),d=ote(a),f;if(d)try{await(0,uL.publishXml)(this.dataverse,d)}catch(m){f=eo(m)}let p=new Map;for(let m of a)p.set(m.key,await this.withArtifactLock(m.type,m.id,()=>this.settlePublish(m,f,r)));for(let m of c)await this.withArtifactLock(m.type,m.id,()=>this.adoptBracket(m));return t.map(m=>({...p.get(this.artifactKey(m.type,m.id))}))}async preparePublish(t,r,n){var i;let o=await this.readRaw(r,n),a=this.registrations.get(r);if(!a?.publish)return{key:t,type:r,id:n,artifact:o,notApplicable:!0};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,n,o);if(!s||!ite.has(s.envelope))throw new J.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,Kr.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:eo(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,zt.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||!cte(u,l)?void 0:{type:r,id:n,reg:t,heldEtag:o,...u?{heldSiblings:u}:{},content:this.bracketContent(t,a)}}catch{return}}async captureSiblings(t,r){var n,i,o;let a=new Map;for(let u of t){let c=u.envelope==="entity"?(n=u.entityLogicalName)===null||n===void 0?void 0:n.toLowerCase():void 0;c&&!a.has(c)&&a.set(c,[])}if(a.size===0)return[];let s;try{s=await this.workspace.listArtifacts()}catch{return[]}for(let u of s){let c=this.registrations.get(u.type);if(!(r.has(this.artifactKey(u.type,u.id))||c?.rebaselineAfterPublish!=="bracket"||!c.publishScope))try{let d=await this.workspace.readArtifact(u.type,u.id),f=d?c.publishScope(u.id,d):void 0,p=f?.envelope==="entity"?(i=f.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;p!==void 0&&((o=a.get(p))===null||o===void 0||o.push(u))}catch{continue}}let l=[];for(let u of a.values())for(let c of u){let d=this.registrations.get(c.type),f=d?await this.captureBracket(d,c.type,c.id):void 0;f&&l.push(f)}return l}async adoptBracket(t){var r;try{let n=await this.versions.getMeta(t.type,t.id);if(!n||n.etag!==t.heldEtag||!(0,Kr.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,zt.isVersionToken)(o)||!CL(a,t.heldSiblings)||!EL(a)||!(o!==t.heldEtag||!(0,Kr.deepEqual)(a??void 0,t.heldSiblings))||!(0,Kr.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,zt.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 (${eo(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,Kr.deepEqual)(r,a)}catch{return!1}}async rebaselineAfterPublish(t,r,n){try{let i=await this.versions.getMeta(r,n);if(!i)return;let{raw:o,etag:a,memberEtags:s,siblingEtags:l}=t.api.getForRebaseline?await t.api.getForRebaseline(this.dataverse,n):await t.api.get(this.dataverse,n),u=t.adapter.fromApiResponse(o),c=d=>{var f,p,m;return(m=(p=(f=t.adapter).baselineContent)===null||p===void 0?void 0:p.call(f,d))!==null&&m!==void 0?m:d};if(!a||!(0,Kr.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:a,fetchedAt:(0,zt.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,Qo.normalizeGuid)(r,"id")})${(0,Qo.odataQuery)([["$select","appmoduleid,name,description"]])}`,c=await this.dataverse.get(u);if(c.status>=200&&c.status<300){let d=(i=c.body)!==null&&i!==void 0?i:{},f=n;if(!f)return{kind:"unverifiable",reason:"there is no local copy of the app to compare the published projection with"};let p=[];return((o=f.name)!==null&&o!==void 0?o:"")!==((a=d.name)!==null&&a!==void 0?a:"")&&p.push("name"),((s=f.description)!==null&&s!==void 0?s:"")!==((l=d.description)!==null&&l!==void 0?l:"")&&p.push("description"),p.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${p.join(", ")} still differ). PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}:{kind:"verified"}}return{kind:"unverifiable",reason:`the published projection answered HTTP ${c.status}`}}catch(u){return{kind:"unverifiable",reason:eo(u).message}}}async verifyPublishedContent(t,r,n,i){var o,a,s;try{let l=f=>{var p,m,h;return(h=(m=(p=t.adapter).baselineContent)===null||m===void 0?void 0:m.call(p,f))!==null&&h!==void 0?h:f},u=l(i),c=(o=await this.versions.getMeta(r,n))===null||o===void 0?void 0:o.snapshot;if(c===void 0||!(0,Kr.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,Kr.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:eo(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 J.ArtifactNotFoundError(t,r);let l=s.artifact,u=s.text,c=(o=(i=a.adapter).normalize)===null||o===void 0?void 0:o.call(i,l);c&&c!==l&&(await this.workspace.writeArtifact(t,r,c),l=c,u=void 0);let d=await this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,d,a),this.assertProjectionMatches(t,r,d);let f=await this.buildMetadataContext(a.adapter,l,d?.snapshot),p=await a.adapter.toApiPayload(l,d?.snapshot,f);return await this.assertSemanticallyComplete(a,t,r,l,d===null,d?.everActivated,n),{type:t,id:r,reg:a,json:l,...u!==void 0?{storedText:u}:{},meta:d,payload:p}}async assertSemanticallyComplete(t,r,n,i,o,a,s){let l=t.adapter.issuesBlockingPush;if(!l)return;let u=i.entityLogicalName,d=(u?await this.columnsForCheck(t,u,i,s):[]).map(p=>({logicalName:p.logicalName,displayName:p.displayName,attributeType:p.attributeType,isCustomAttribute:p.isCustomAttribute,...p.maxLength!==void 0?{maxLength:p.maxLength}:{},...p.options?{options:p.options.map(m=>({value:m.value,label:m.label}))}:{},...p.targets?{targets:p.targets}:{}})),f=l.call(t.adapter,i,d,{isCreate:o,everActivated:a});if(f.length>0)throw new J.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,gu.readCheckColumns)(this.dataverse,r,l)}catch{return[]}};if(!i)return u();let c=[r,...[...new Set(l)].sort()].join("\0"),d=i.get(c);return d||(d=u(),i.set(c,d)),d}async pushArtifactUnlocked(t,r,n){return this.executePrepared(await this.prepareArtifactUnlocked(t,r,n))}async executePrepared(t){var r,n,i,o,a,s,l,u,c;let{type:d,id:f,reg:p,json:m,meta:h,payload:g}=t,v=!1;try{let w;if(h)w=await p.api.update(this.dataverse,f,g,h.etag,h.memberEtags,h.siblingEtags);else{let P=await this.createWithMintedId(p,d,f,g,m);if("adopted"in P)return await this.persistAdoption(d,f,m,P.adopted);w=P.written}v=!0;let C=f;h||(w.serverIdentity&&p.adapter.applyServerIdentity&&p.adapter.applyServerIdentity(m,w.serverIdentity),w.id&&w.id!==f&&(m.id=w.id,await this.workspace.deleteArtifact(d,f),C=w.id));let E=h&&w.readBack!==void 0?this.adoptReadBack(p,w.readBack):void 0,k=E?.artifact?{artifact:E.artifact,baseline:E.artifact}:p.adapter.committed?p.adapter.committed(m,g,{intentPending:w.intentPending===!0}):{artifact:m,baseline:m};await this.workspace.writeArtifact(d,C,k.artifact,h&&C===f?t.storedText:void 0);let R=E?.artifact!==void 0&&!(0,Kr.deepEqual)(E.artifact,m),T=R?this.nextRefreshGeneration(d,C,h):(r=h?.refreshGeneration)!==null&&r!==void 0?r:0,I=[...(n=w.warnings)!==null&&n!==void 0?n:[],...E?.warning?[E.warning]:[],...E?.artifact!==void 0&&!this.adoptedAsSent(p,E.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:E&&!E.artifact?null:w.etag,...T>0?{refreshGeneration:T,observedGeneration:(i=h?.observedGeneration)!==null&&i!==void 0?i:0}:{},languageCode:this.languageCode,projectionVersion:Ns.PROJECTION_VERSION,fetchedAt:(0,zt.nowIso)(),snapshot:(0,$n.cloneJson)(k.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 F=(P=p.publishScope)===null||P===void 0?void 0:P.call(p,C,m);return F?{publishScope:F}:{}})():{},...R?{refreshed:!0}:{},...I.length>0?{warnings:I}:{}}}catch(w){let C=(0,J.readPartialTokens)(w);if(C&&h){let E={...(a=h.memberEtags)!==null&&a!==void 0?a:{},...(s=C.memberEtags)!==null&&s!==void 0?s:{}},k={...(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(E).length>0?{memberEtags:E}:{},...Object.keys(k).length>0?{siblingEtags:k}:{}},h)}if(w instanceof J.SdkError&&w.code===jt.ALREADY_EXISTS_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof J.SdkError&&w.code===lL.WFOM_API_UNAVAILABLE_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof J.SdkError&&w.code===lL.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof J.SdkError&&w.code===zt.VERSION_CONFLICT_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,fL.isFailureAfterPrimaryWrite)(w)?w:new J.VersionConflictError(d,f,(c=h?.etag)!==null&&c!==void 0?c:null,null,w.message)};throw v?Xee(w):w}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new J.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!==Ns.PROJECTION_VERSION)throw new J.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 ${Ns.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,tv.readPrimaryCreateRefusal)(a):void 0;if(s?.status===404&&await(0,dL.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,J.attachCause)(new J.SdkError(jt.ALREADY_EXISTS_CODE,iv(r,n,u)+(this.createRecovery==="adoptExact"?` ${yL(ste)}`:"")),a)}if(!(a instanceof J.SdkError)||a.code!==zt.VERSION_CONFLICT_CODE||(0,fL.isFailureAfterPrimaryWrite)(a))throw a;if(this.createRecovery==="adoptExact"&&s?.status===412){let l=await(0,dL.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 J.SdkError(jt.ALREADY_EXISTS_CODE,`${iv(r,n)} ${yL(l.refused)}`)}throw new J.SdkError(jt.ALREADY_EXISTS_CODE,iv(r,n))}}async persistAdoption(t,r,n,i){let{artifact:o,etag:a}=i,s=!(0,Kr.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:Ns.PROJECTION_VERSION,fetchedAt:(0,zt.nowIso)(),snapshot:(0,$n.cloneJson)(o)},null),s&&await this.workspace.writeArtifact(t,r,o),{type:t,id:r,saved:!1,adoptedExisting:!0,shipped:!1,publish:{kind:"notRequested"},...s?{refreshed:!0}:{}}}async buildMetadataContext(t,r,n){var i,o,a,s;let l=(o=(i=t.metadataNeeds)===null||i===void 0?void 0:i.call(t,r,n))!==null&&o!==void 0?o:[],u=new Set(l.map(R=>R.entityLogicalName).filter(R=>!!R)),c=new Set(l.filter(R=>R.needsColumnDetail).map(R=>R.entityLogicalName)),d=new Set(l.filter(R=>R.needsColumnDetail||!R.fieldName).map(R=>R.entityLogicalName)),f=R=>l.filter(T=>T.entityLogicalName===R).every(T=>T.fetchRequired===!1),p=new Map,m=new Map;for(let R of u){let T=await this.readCachedEntityMetadata(R);if(T&&c.has(R)&&(T.columnDetailComplete!==!0||T.attributes.some(I=>typeof I.attributeTypeName!="string"))&&(T=null),!T&&!d.has(R)){if(!f(R)){let I=l.filter(P=>P.entityLogicalName===R).map(P=>P.fieldName);try{let P=await(0,gu.readColumnHints)(this.dataverse,R,I);m.set(R,new Map(P.map(F=>[F.logicalName,F])))}catch{}}continue}if(!T&&!f(R))try{await this.loadMissedEntityMetadata(R),T=await this.readCachedEntityMetadata(R)}catch{}T&&p.set(R,T)}let h=(R,T)=>{var I,P,F;return(P=(I=p.get(R))===null||I===void 0?void 0:I.attributes.find(z=>z.logicalName===T))!==null&&P!==void 0?P:(F=m.get(R))===null||F===void 0?void 0:F.get(T)},g=this.languageCode,w=l.some(R=>{if(!R.needsLabel||!R.fieldName)return!1;let T=h(R.entityLogicalName,R.fieldName);return T?.localizedDisplayName!==void 0&&!T.localizedDisplayName[g]})?await this.readBaseLanguage():void 0,C=!((a=t.needsBaseLanguage)===null||a===void 0)&&a.call(t,r)?await this.readBaseLanguage():void 0,E=(s=t.customControlNeeds)===null||s===void 0?void 0:s.call(t,r,n),k=E&&(E.controls.length>0||E.columns.length>0)?await this.readPcfNeeds(E):void 0;return{resolveField:(R,T)=>{let I=h(R,T);return I?{displayName:dte(I,g,w),attributeType:I.attributeType}:void 0},resolveEntity:R=>p.get(R),loadTypeScript:()=>this.compiler.load(),...C!==void 0?{baseLanguageCode:C}:{},...k?{pcf:k}:{}}}async readPcfNeeds(t){let r=new Map;for(let i of t.controls)r.set(i,await(0,cL.readControlManifest)(this.dataverse,i));let n=new Map;for(let i of t.columns)n.set(i,await(0,cL.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:eo(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 J.SdkError(jt.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:eo(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,Vf.assignMissingIds)(r)}async resolveComponentType(t){if(t.genPage)return"genPage";switch(t.componentType){case Wt.SolutionComponentType.SavedQuery:return"view";case Wt.SolutionComponentType.SavedQueryVisualization:return"chart";case Wt.SolutionComponentType.AppModule:return"app";case Wt.SolutionComponentType.Workflow:return this.workflowArtifactType(t);case Wt.SolutionComponentType.SystemForm:return this.systemFormArtifactType(t.objectId);default:return}}async systemFormArtifactType(t){let r=await(0,Uf.readSystemFormType)(this.dataverse,t);if(Number.isNaN(r))throw new J.SdkError(nv,`System form '${t}' answered without a readable type, so whether it is a form or a dashboard cannot be told.`);return(0,Uf.systemFormKindOf)(r)}async workflowArtifactType(t){let r=(0,Qo.normalizeGuid)(t.objectId,"workflowId"),n=`/workflows(${r})${(0,Qo.odataQuery)([["$select","category,businessprocesstype"]])}`,o=(0,zt.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)).body,a=(0,Uf.decodeCode)(o?.category);if(Number.isNaN(a))throw new J.SdkError(nv,`Workflow '${r}' answered without a readable category, so its kind cannot be told.`);if(t.workflowCategory=a,a===tte)return"businessRule";if(a===rte){let s=(0,Uf.decodeCode)(o?.businessprocesstype);if(Number.isNaN(s))throw new J.SdkError(nv,`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 J.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};jt.MakerSdk=Gf;function ute(e){return new Gf(e)}jt.createMakerSdk=ute;function eo(e){return e instanceof Error?e:new Error(String(e))}function CL(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 EL(e){return Object.values(e??{}).every(zt.isVersionToken)}function cte(e,t){return CL(e,t)&&EL(e)&&Object.keys(e??{}).every(r=>t?.[r]===e?.[r])}function yL(e){return`createRecovery 'adoptExact' did not adopt it: ${e}.`}function iv(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 dte(e,t,r){let n=e.localizedDisplayName;return n?.[t]||(r===void 0?void 0:n?.[r])||e.displayName}function bi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function vL(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function bL(e){e.length===0||!e.every(t=>bi(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function fte(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=>bi(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>bi(n)&&n.id===t.after);return r<0?e.length:r+1}});var NL=b(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});Wf.ARTIFACT_TYPES=void 0;Wf.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var _L=b(DL=>{"use strict";Object.defineProperty(DL,"__esModule",{value:!0})});var TL=b(IL=>{"use strict";Object.defineProperty(IL,"__esModule",{value:!0})});var OL=b(PL=>{"use strict";Object.defineProperty(PL,"__esModule",{value:!0})});var kL=b(RL=>{"use strict";Object.defineProperty(RL,"__esModule",{value:!0})});var LL=b(xL=>{"use strict";Object.defineProperty(xL,"__esModule",{value:!0})});var ML=b(FL=>{"use strict";Object.defineProperty(FL,"__esModule",{value:!0})});var BL=b($L=>{"use strict";Object.defineProperty($L,"__esModule",{value:!0})});var qL=b(UL=>{"use strict";Object.defineProperty(UL,"__esModule",{value:!0})});var GL=b(VL=>{"use strict";Object.defineProperty(VL,"__esModule",{value:!0})});var zL=b(WL=>{"use strict";Object.defineProperty(WL,"__esModule",{value:!0})});var HL=b(jL=>{"use strict";Object.defineProperty(jL,"__esModule",{value:!0})});var JL=b(KL=>{"use strict";Object.defineProperty(KL,"__esModule",{value:!0})});var YL=b(QL=>{"use strict";Object.defineProperty(QL,"__esModule",{value:!0})});var ZL=b(XL=>{"use strict";Object.defineProperty(XL,"__esModule",{value:!0})});var tF=b(eF=>{"use strict";Object.defineProperty(eF,"__esModule",{value:!0})});var nF=b(rF=>{"use strict";Object.defineProperty(rF,"__esModule",{value:!0})});var oF=b(iF=>{"use strict";Object.defineProperty(iF,"__esModule",{value:!0})});var sF=b(aF=>{"use strict";Object.defineProperty(aF,"__esModule",{value:!0})});var uF=b(lF=>{"use strict";Object.defineProperty(lF,"__esModule",{value:!0})});var dF=b(cF=>{"use strict";Object.defineProperty(cF,"__esModule",{value:!0})});var fF=b(ge=>{"use strict";var pte=ge&&ge.__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]})),$e=ge&&ge.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&pte(t,e,r)};Object.defineProperty(ge,"__esModule",{value:!0});ge.createMakerSdk=void 0;var mte=SL();Object.defineProperty(ge,"createMakerSdk",{enumerable:!0,get:function(){return mte.createMakerSdk}});$e(NL(),ge);$e(_L(),ge);$e(TL(),ge);$e(OL(),ge);$e(kL(),ge);$e(LL(),ge);$e(ML(),ge);$e(BL(),ge);$e(qL(),ge);$e(GL(),ge);$e(zL(),ge);$e(HL(),ge);$e(JL(),ge);$e(YL(),ge);$e(Nc(),ge);$e(ZL(),ge);$e(tF(),ge);$e(nF(),ge);$e(oF(),ge);$e(sF(),ge);$e(uF(),ge);$e(dF(),ge);$e(X(),ge)});var av=b(Bn=>{"use strict";var hte=Bn&&Bn.__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]})),gte=Bn&&Bn.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),hF=Bn&&Bn.__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)&&hte(t,e,r);return gte(t,e),t};Object.defineProperty(Bn,"__esModule",{value:!0});Bn.NodeFileSystemStorage=void 0;var rt=hF(require("fs")),Ft=hF(require("path")),pF=X(),mF=hp();async function gF(e){let t;try{t=await rt.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await rt.promises.unlink(e)}catch{await rt.promises.rmdir(e)}return}if(!t.isDirectory()){await rt.promises.unlink(e);return}for(let r of await rt.promises.readdir(e))await gF(Ft.join(e,r));await rt.promises.rmdir(e)}var ov=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(Ft.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!rt.existsSync(r);){n.unshift(Ft.basename(r));let i=Ft.dirname(r);if(i===r)return Ft.resolve(t);r=i}return Ft.resolve(rt.realpathSync(r),...n)}assertWithinRoot(t,r){let n=Ft.resolve(this.root),i=Ft.resolve(t);if(i!==n&&!i.startsWith(n+Ft.sep))throw new pF.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(n),a=r?this.realPathThroughNearestAncestor(i):Ft.resolve(this.realPathThroughNearestAncestor(Ft.dirname(i)),Ft.basename(i));if(a!==o&&!a.startsWith(o+Ft.sep))throw new pF.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!rt.existsSync(r))return null;try{return await(0,mF.retryTransientIoAsync)(()=>rt.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=Ft.dirname(n);await rt.promises.mkdir(i,{recursive:!0});let o=Ft.join(i,`.${Ft.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await rt.promises.writeFile(o,r,"utf8"),await(0,mF.retryTransientIoAsync)(()=>rt.promises.rename(o,n))}catch(a){try{rt.existsSync(o)&&await rt.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let r=this.pathFor(t);rt.existsSync(r)&&await rt.promises.unlink(r)}async deleteByPrefix(t){await gF(this.pathFor(t,!1))}async ensureContainer(t){await rt.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return rt.existsSync(this.pathFor(t))}};Bn.NodeFileSystemStorage=ov});var yF=b(mr=>{"use strict";var yte=mr&&mr.__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]})),vte=mr&&mr.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),bte=mr&&mr.__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)&&yte(t,e,r);return vte(t,e),t};Object.defineProperty(mr,"__esModule",{value:!0});mr.loadNodeTypeScript=mr.createNodeWorkspaceStorage=mr.NodeFileSystemStorage=void 0;var wte=av(),Ate=av();Object.defineProperty(mr,"NodeFileSystemStorage",{enumerable:!0,get:function(){return Ate.NodeFileSystemStorage}});function Cte(e){return new wte.NodeFileSystemStorage(e)}mr.createNodeWorkspaceStorage=Cte;async function Ete(){return await Promise.resolve().then(()=>bte(require("typescript")))}mr.loadNodeTypeScript=Ete});var wi={};module.exports=hr(wi);Ai(wi,ye(fF()),module.exports);Ai(wi,ye(yF()),module.exports);
diff --git a/plugins/model-apps/scripts/verify-model-app.js b/plugins/model-apps/scripts/verify-model-app.js
index d19c2f831..0a81bef38 100644
--- a/plugins/model-apps/scripts/verify-model-app.js
+++ b/plugins/model-apps/scripts/verify-model-app.js
@@ -1,10 +1,12 @@
#!/usr/bin/env node
'use strict';
// verify-model-app: reconcile an App Spec against the DEPLOYED app and report any missing artifacts
-// (entities/columns/views/charts/forms/sitemap subareas + icons). Read-only WITH RESPECT TO DATAVERSE
-// (it only READS the org — no create/update/delete), though it does write a local SDK workspace/cache
-// directory (--workspace, default <spec-dir>/.maker-workspace). Exit non-zero if anything declared is
-// missing — catches silent partial builds.
+// (entities/columns/views/charts/forms/sitemap subareas + icons). Read-only: it only READS the org — no
+// create/update/delete — and writes nothing into the app folder. Its SDK works in a throwaway temporary
+// workspace, removed when the run ends, so it never opens the folder's persistent `.maker-workspace` (which belongs
+// to the environment it was first opened for, and is the build's). `--workspace` (default
+// <spec-dir>/.maker-workspace) names only where the build's baseline, `last-applied.json`, is READ from.
+// Exit non-zero if anything declared is missing — catches silent partial builds.
//
// Usage: node verify-model-app.js --env <orgUrl> --spec @<app-folder>/app-spec.json [--workspace <dir>]
@@ -23,28 +25,39 @@ const { makeGenpageCli } = require('./lib/genpage-cli.js');
const { assertSafeOutputDir } = require('./lib/safe-fs.js');
const { depthFromMask } = require('./lib/role-privileges.js');
const { appEntityComponentsFor, appMainFormsFor, appComponentRows } = require('./lib/app-components.js');
+const { readChoiceAttributes } = require('./lib/view-filter-labels.js');
-// A throwaway SDK workspace for ONE dashboard read (readerFor's dashboardComponents), deleted after it. The tiles
-// verify checks must be the server's: read through the build's own workspace, a copy holding unpushed edits — or
-// one another writer changed mid-read — was what got verified, and a forced refresh there could discard a
-// concurrent writer's edit. A fresh workspace has no local copy to read, discard or race with, and a fresh SDK no
-// cached read to hand back. One per read, not per run: a second read of the same dashboard must not come from
-// the first one's cache. The HTTP client — and with it the Azure CLI token — is shared: `opts.httpClient` (the
-// run's own), else one made on the first read. A client per read ran `az account get-access-token` once per
-// dashboard. `opts.makeClient` is a test seam.
+// An SDK on a THROWAWAY workspace — a temporary folder `dispose()` removes — and never on the app folder's own.
+//
+// For the run's own reads: every one of them goes to the server (queries, catalog and relationship reads,
+// the privilege and setting reads), so nothing in the app folder's workspace could answer them, and opening it
+// would only tie a read-only verify to the environment that workspace was first opened for (the SDK refuses a
+// workspace for another one, WORKSPACE_ORG_MISMATCH) — a folder built in one environment and imported into another
+// could not be verified there — and bind a folder that has no workspace yet to whichever environment verified first.
+//
+// For a dashboard read (readerFor's dashboardComponents) the tiles verify checks must be the server's: read
+// through the build's own workspace, a copy holding unpushed edits — or one another writer changed mid-read — was
+// what got verified, and a forced refresh there could discard a concurrent writer's edit. A fresh workspace has no
+// local copy to read, discard or race with, and a fresh SDK no cached read to hand back. One per read, not per run:
+// a second read of the same dashboard must not come from the first one's cache.
+async function throwawaySdk(env, httpClient, prefix) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
+ const dispose = () => { try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* best-effort */ } };
+ try {
+ return { sdk: await makeProvision(env, dir, httpClient), dispose };
+ } catch (e) {
+ dispose();
+ throw e;
+ }
+}
+
+// The reader for ONE dashboard read: a throwaway SDK (throwawaySdk), deleted after it. The HTTP client — and with it
+// the Azure CLI token — is shared: `opts.httpClient` (the run's own), else one made on the first read. A client per
+// read ran `az account get-access-token` once per dashboard. `opts.makeClient` is a test seam.
function isolatedReaderFor(env, opts = {}) {
let client = opts.httpClient || null;
const makeClient = opts.makeClient || createAzHttpClient;
- return async () => {
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'verify-dashboard-'));
- try {
- const sdk = await makeProvision(env, dir, client || (client = makeClient(env)));
- return { sdk, dispose: () => { try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* best-effort */ } } };
- } catch (e) {
- try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* best-effort */ }
- throw e;
- }
- };
+ return async () => throwawaySdk(env, client || (client = makeClient(env)), 'verify-dashboard-');
}
async function makeProvision(env, workspaceDir, httpClient = createAzHttpClient(env)) {
@@ -106,8 +119,53 @@ async function appRoleIdsFor(sdk, appUnique) {
}
}
+// Page ids per `pac model genpage download` run in readerFor's pageCodes. pac takes them as ONE comma-joined
+// argument: 25 GUIDs are under a kilobyte, far below the command-line limit of the pac.cmd shim on Windows,
+// and an app with more pages than that is rare — so an app's pages go in one run, an unusual one in a few.
+const PAGE_DOWNLOAD_CHUNK = 25;
+
+// The longest readerFor's endPageReads waits for the downloads it has just ended to remove their folders. Killing pac
+// answers them at once; this only bounds a reader whose pac client cannot end its runs.
+const PAGE_READS_END_WAIT_MS = 10000;
+
+// The SDK resolves a table's EntitySetName with one metadata GET before the table's first record read, and
+// remembers only the ANSWER — so reads of one table that start together each ask for it. Verify's checks
+// overlap, and many of them read the same table (every view reads `savedquery`, every persona `role`), so
+// the first read of each table goes by itself and the others start when its answer is cached: the same
+// requests as when the checks ran one after another, not one extra per overlapping read.
+//
+// A first read that FAILS cached nothing, so the next waiting read becomes the first and the failure is
+// never shared — each check still reports the outcome of its own read. Everything but `queryRecords`
+// is the SDK's own, bound to it.
+function singleFlightFirstReads(sdk) {
+ if (!sdk || typeof sdk.queryRecords !== 'function') return sdk;
+ const cached = new Set();
+ const firstReads = new Map();
+ const queryRecords = async (set, query) => {
+ const table = String(set);
+ while (!cached.has(table)) {
+ const inFlight = firstReads.get(table);
+ if (!inFlight) {
+ const read = sdk.queryRecords(set, query);
+ firstReads.set(table, Promise.resolve(read).then(() => { cached.add(table); }, () => {}).then(() => { firstReads.delete(table); }));
+ return read;
+ }
+ await inFlight;
+ }
+ return sdk.queryRecords(set, query);
+ };
+ return new Proxy(sdk, {
+ get(target, prop) {
+ if (prop === 'queryRecords') return queryRecords;
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+}
+
function readerFor(sdk, appUnique, opts) {
opts = opts || {};
+ sdk = singleFlightFirstReads(sdk);
const genpageCli = opts.genpageCli;
const workspaceDir = opts.workspaceDir;
const { fetchSitemap: _fetchSitemap, sitemapGenPageIds: _sitemapGenPageIds } = require('./lib/sitemap-pages.js');
@@ -141,7 +199,10 @@ function readerFor(sdk, appUnique, opts) {
// keeping the first scan would report a table created between passes as missing, and a rejected
// scan would fail every later pass. verifySpec calls beginVerificationPass at the start of each.
let catalogP;
- const beginVerificationPass = () => { catalogP = null; };
+ // Set once verifySpec has ended this reader's page reads (endPageReads, below): nothing that runs pac, or makes a temporary
+ // download folder, starts again until the next pass begins.
+ let pageReadsEnded = false;
+ const beginVerificationPass = () => { catalogP = null; pageReadsEnded = false; };
const catalog = () => {
if (!catalogP) {
catalogP = Promise.resolve().then(() => sdk.findTables('')).catch((err) => {
@@ -168,6 +229,12 @@ function readerFor(sdk, appUnique, opts) {
// 404 the SDK emits on an environment where the preview is not provisioned, which verify-spec
// interprets (it must stay distinguishable from the legitimate 'None' answer).
columnVisualization: async (logical, columnLogical) => sdk.getColumnVisualization(String(logical).toLowerCase(), String(columnLogical).toLowerCase()),
+ // choiceAttributes(entity, { languageCode }): the table's choice columns with every option and every
+ // language of its labels — what the build resolves a view filter's option LABEL against, so verify expects
+ // the value the build wrote (lib/view-filter-labels.js). Raw client like the relationship reads below, for
+ // the reason that module gives. It never throws: a read that fails answers { state: 'error' }, which verify
+ // reports as a label it could not resolve.
+ choiceAttributes: (logical, o) => readChoiceAttributes(sdk.dataverse, logical, o || {}),
queryRecords: (set, o) => sdk.queryRecords(set, o),
// entityRelationships(childLogical): detailed rows for the relationship check. ManyToOne is
// the 1:N seen from the child; ManyToMany is read from entity1. A failed read throws so
@@ -398,7 +465,24 @@ function readerFor(sdk, appUnique, opts) {
// for a page-bearing spec (Imp7/C6: missing methods → unableToRun).
if (genpageCli) {
let existenceP;
+ let existenceRunning = false;
let manifestP;
+ // The downloads in flight, each as the promise of the WHOLE call: the temporary folder it made is removed when that
+ // settles, which is what endPageReads waits for.
+ const downloading = new Set();
+ const tracked = (work) => {
+ const call = work();
+ downloading.add(call);
+ const forget = () => downloading.delete(call);
+ call.then(forget, forget);
+ return call;
+ };
+ const PAGE_READS_ENDED = 'the page reads were ended: the verification pass no longer needs them';
+ // The folder is removed the moment its download ends, and a download that was just ended — pac killed — can still be
+ // letting go of it for a moment (Windows answers EBUSY/EPERM while a handle is open), so removal is retried briefly.
+ const removeDownloadDir = (dir) => {
+ try { fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); } catch { /* leave the temp dir */ }
+ };
// MEMBERSHIP: the app's live sitemap page ids. Fail-closed: throw when the sitemap is unreadable.
// verifySpec catches reader-incapacity via the method-presence check, not a try/catch here; a throw
@@ -411,10 +495,15 @@ function readerFor(sdk, appUnique, opts) {
// EXISTENCE: env-wide generative-page id set. Memoized (one enumerateEnv per verify run). Throw on
// failure — fail-closed: an unknown environment means we cannot tell deployed from absent.
- base.existenceIds = () => (existenceP || (existenceP = (async () => {
- const e = await genpageCli.enumerateEnv();
- if (!e.ok) throw new Error(e.error);
- return e.ids;
+ base.existenceIds = () => existenceP || (pageReadsEnded ? Promise.reject(new Error(PAGE_READS_ENDED)) : (existenceP = (async () => {
+ existenceRunning = true;
+ try {
+ const e = await genpageCli.enumerateEnv();
+ if (!e.ok) throw new Error(e.error);
+ return e.ids;
+ } finally {
+ existenceRunning = false;
+ }
})()));
// IDENTITY: the durable page manifest web resource. Returns null when absent OR corrupt — verifySpec
@@ -431,10 +520,13 @@ function readerFor(sdk, appUnique, opts) {
// pageCode(id): download THAT page by id (pageIds:[id]) into a per-id cached directory. Caches result
// so repeated calls for the same id never re-download. Fail-closed: a download failure rejects (throws)
// so the caller receives a page-code miss rather than silently receiving empty code.
- base.pageCode = async (pageId) => {
+ base.pageCode = (pageId) => tracked(async () => {
const key = String(pageId).toLowerCase();
if (codeById.has(key)) return codeById.get(key);
const id = await appId();
+ // Checked after the wait for the app id, right before the folder is made and pac started: a pass that ended these
+ // reads while this one waited must not have a download begin behind it.
+ if (pageReadsEnded) throw new Error(PAGE_READS_ENDED);
// A fixed name under the workspace (verify-pages/<id>) is a place a link can be left.
// pac follows links, and removing that name would delete through the link. The download
// therefore goes to a private temp directory this call creates and always removes.
@@ -451,7 +543,82 @@ function readerFor(sdk, appUnique, opts) {
codeById.set(key, code);
return code;
} finally {
- try { fs.rmSync(outDir, { recursive: true, force: true }); } catch { /* leave the temp dir */ }
+ removeDownloadDir(outDir);
+ }
+ });
+
+ // pageCodes(ids): the code of SEVERAL pages from one pac download per chunk of ids, where pageCode(id) runs
+ // pac once per page — a process start, an auth and a round trip each, seconds apiece. Answers a Map of
+ // lower-cased id -> `{ code }` or `{ error }`: what pageCode(id) would have returned or thrown, so a caller
+ // reports every page exactly as it always has.
+ //
+ // pac writes each page of a multi-id download to <outDir>/<pageId>/page.tsx (the layout download-model-app
+ // reads too), so a page is found by the NAME of its directory, matched case-insensitively. A page that
+ // cannot be answered from the batch — a lone page, a batch pac failed, or an id with no directory in a batch
+ // that succeeded — is asked for by itself, the way it always was: one bad page then costs its own miss,
+ // never its neighbours', and nothing is guessed from another page's files.
+ const downloadPageCodes = (ids) => tracked(async () => {
+ // The app id first, then the folder: a pass that ended these reads while the id was being read has nothing to download for.
+ let id;
+ try { id = await appId(); } catch { return null; }
+ if (pageReadsEnded) return null;
+ const outDir = fs.mkdtempSync(path.join(os.tmpdir(), 'verify-page-'));
+ try {
+ await genpageCli.download({ appId: id, outputDir: outDir, pageIds: ids });
+ const codeByDir = new Map();
+ for (const entry of fs.readdirSync(outDir)) {
+ const dir = path.join(outDir, entry);
+ if (!fs.statSync(dir).isDirectory()) continue;
+ const tsx = path.join(dir, 'page.tsx');
+ codeByDir.set(entry.toLowerCase(), fs.existsSync(tsx) ? fs.readFileSync(tsx, 'utf8') : '');
+ }
+ return codeByDir;
+ } catch {
+ return null;
+ } finally {
+ removeDownloadDir(outDir);
+ }
+ });
+ base.pageCodes = async (pageIds) => {
+ const answers = new Map();
+ const wanted = [];
+ for (const id of pageIds || []) {
+ const key = String(id).toLowerCase();
+ if (answers.has(key) || wanted.some((w) => w.key === key)) continue;
+ if (codeById.has(key)) answers.set(key, { code: codeById.get(key) });
+ else wanted.push({ id, key });
+ }
+ for (let i = 0; i < wanted.length; i += PAGE_DOWNLOAD_CHUNK) {
+ const chunk = wanted.slice(i, i + PAGE_DOWNLOAD_CHUNK);
+ const fetched = chunk.length > 1 ? await downloadPageCodes(chunk.map((c) => c.id)) : null;
+ for (const { id, key } of chunk) {
+ if (fetched && fetched.has(key)) {
+ codeById.set(key, fetched.get(key));
+ answers.set(key, { code: fetched.get(key) });
+ continue;
+ }
+ try { answers.set(key, { code: await base.pageCode(id) }); } catch (error) { answers.set(key, { error }); }
+ }
+ }
+ return answers;
+ };
+
+ // Ends the page reads that run pac, for a verify pass that has stopped needing their answers (verifySpec calls this when
+ // it gave up on them): every pac run still in flight is ended, process tree and all; no new one starts, and no download
+ // folder is made, until the next pass begins; and it answers once the downloads that were in flight have removed their
+ // folders — so a verify CLI that exits right after has left neither a pac nor a `verify-page-*` folder behind. The wait is
+ // bounded, and never throws: it may delay the end of a pass for a moment, not hold it.
+ base.endPageReads = async () => {
+ pageReadsEnded = true;
+ // A listing that was cut short is not the answer to remember for a later pass.
+ if (existenceRunning) existenceP = undefined;
+ if (typeof genpageCli.abort === 'function') genpageCli.abort();
+ let timer;
+ const bound = new Promise((resolve) => { timer = setTimeout(resolve, Number.isInteger(opts.endWaitMs) ? opts.endWaitMs : PAGE_READS_END_WAIT_MS); });
+ try {
+ await Promise.race([Promise.allSettled([...downloading]), bound]);
+ } finally {
+ clearTimeout(timer);
}
};
}
@@ -489,21 +656,33 @@ async function main() {
if (!v.ok) { emitResult(false, { ok: false, errors: v.errors }); return; }
for (const w of v.warnings || []) process.stderr.write(`WARNING: ${w}\n`);
const workspaceDir = workspaceArg || path.join(path.dirname(specPath), '.maker-workspace');
- // Before the SDK. A link planted as the workspace root is refused here so the factory
- // is never called; a real directory is allowed.
+ // 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
+ // takes a workspace — the baseline would be read from wherever the link points.
try {
- assertSafeOutputDir(workspaceDir, { create: true, fs });
+ assertSafeOutputDir(workspaceDir, { fs });
} catch (err) {
- emitResult(false, err instanceof Error ? err : new Error(String(err)));
- return;
+ if (!(err && err.reason === 'uninspectable')) {
+ emitResult(false, err instanceof Error ? err : new Error(String(err)));
+ return;
+ }
}
const httpClient = createAzHttpClient(env);
- const sdk = await makeProvision(env, workspaceDir, httpClient);
- const genpageCli = makeGenpageCli(env);
- // The spec's baseline for this environment and app, when the workspace has one: an icon the build
- // kept because it was changed in the designer since then is not a failure (AB#6726727).
- const baselineSpec = readBaseline(workspaceDir, { environment: dataverseOrigin(env), appUniqueName: appUniqueName(spec) }) || undefined;
- const r = await verifySpec(spec, readerFor(sdk, appUniqueName(spec), { genpageCli, workspaceDir, isolatedReader: isolatedReaderFor(env, { httpClient }) }), { baselineSpec });
+ // 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-');
+ let r;
+ try {
+ const genpageCli = makeGenpageCli(env);
+ // The spec's baseline for this environment and app, when the workspace has one: an icon the build
+ // kept because it was changed in the designer since then is not a failure (AB#6726727). It is keyed by
+ // environment, so a folder built against another one yields none.
+ const baselineSpec = readBaseline(workspaceDir, { environment: dataverseOrigin(env), appUniqueName: appUniqueName(spec) }) || undefined;
+ r = await verifySpec(spec, readerFor(session.sdk, appUniqueName(spec), { genpageCli, workspaceDir, isolatedReader: isolatedReaderFor(env, { httpClient }) }), { baselineSpec });
+ } finally {
+ // Before the result is printed: emitResult ends the process, so a cleanup placed after it never ran.
+ session.dispose();
+ }
// 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.
diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.md
index 2958eafd3..c862bb924 100644
--- a/plugins/model-apps/skills/app-builder/SKILL.md
+++ b/plugins/model-apps/skills/app-builder/SKILL.md
@@ -323,7 +323,37 @@ After plan-mode approval (before the full build):
rather than omitted — the page-builder treats a missing line as the same fail-closed value, but
an explicit line is what makes the dispatch contract checkable.
-5. **Validate + commit the transition (transactional)** — never flip `source` by hand, and never
+5. **Check styles, then validate + commit the transition (transactional)** — the workers have no
+ shell, so first check every generated page for the Griffel shorthands that `makeStyles` drops at
+ runtime, one command per page (`<file>` is the page's file from step 3):
+ ```bash
+ node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file <working-dir>/<file>
+ ```
+ Griffel does not support ten CSS shorthands, and `makeStyles` drops them at runtime: the page
+ type-checks, transpiles and deploys, then renders without the border, color or reset. They are
+ `all`, `borderColor`, `borderStyle`, `borderWidth`, `borderBlock`, `borderBlockStart`,
+ `borderBlockEnd`, `borderInline`, `borderInlineStart` and `borderInlineEnd`. Write longhands
+ instead: `borderColor`, `borderStyle` and `borderWidth` become one longhand per side, `border` +
+ `Top`, `Right`, `Bottom` or `Left` + `Color`, `Style` or `Width` (`borderWidth` →
+ `borderTopWidth`, `borderRightWidth`, `borderBottomWidth`, `borderLeftWidth`); `borderBlock`,
+ `borderInline` and their `Start` and `End` forms become the `Width`, `Style` and `Color` longhands
+ of the sides they name (`borderBlockStart` → `borderBlockStartWidth`, `borderBlockStartStyle`,
+ `borderBlockStartColor`; `borderBlock` → those and the three `borderBlockEnd…` ones); `all` has no
+ longhands, so set the properties you need one by one. Every other shorthand (`padding`, `margin`,
+ `border`, `borderRadius`, `gap`, `outline`) is supported, and an inline `style={{ … }}` is not
+ Griffel at all.
+
+ `check-griffel-styles.js` prints each problem it finds — a key Griffel drops in a `makeStyles`
+ call, at any depth, with its line, column and longhands, or a call or a style object it cannot
+ read, with what to change — and exits 3 while any is left: fix what it reports and run it again,
+ and do not transpile or upload the page until it exits 0. It reads the style objects written
+ inline in the call, `makeStyles({ … })`, so write them there: one passed or spread in from
+ elsewhere (`makeStyles(styles)`, `...base`) is reported, because the check cannot see its keys,
+ and so is a key computed from an expression (`[key]: …`), whose name it cannot see (a template
+ that starts with `--`, `&`, `:` or `@` is read); Fluent's `...shorthands.*(…)` and
+ `...typographyStyles.*` may be spread as they are.
+
+ Then validate and commit the transition — never flip `source` by hand, and never
flip pages one at a time as workers return. Run:
```bash
node "${PLUGIN_ROOT}/scripts/promote-intent-pages.js" \
@@ -404,14 +434,40 @@ deadlock, concurrent-op guards) are **auto-retried** with backoff on `--apply` (
retry reuses what's already created). If the build still **halts** (`BuildHalt`) on an
unrecoverable error, surface it and ask the user how to proceed via `AskUserQuestion` (adjust the
spec / cancel), then re-run. Everything is scoped to a dedicated unmanaged solution; **`--publish`
-gates the final *bulk* publish** — edit/finalize paths still publish their one targeted artifact so the
-change takes effect (see *Notes & limits*).
+gates the final *bulk* publish**, which also carries the edits made to existing views and forms.
+Without it those edits — and always an existing app's sitemap re-sync — still publish their one
+targeted artifact so the change takes effect (see *Notes & limits*).
**Recovery from a failed or halted build: run the full build again.** The build is idempotent — every
phase re-uses what's already created and only fills the gaps. SDK metadata is persisted under
`<working-dir>/.maker-workspace/` (override with `--workspace`). There is no apply-safe
`--from <phase>` shortcut; a full rerun is the correct and safe recovery path. One exception: an
`already-exists` halt recurs on a rerun until that workspace directory is deleted — follow its message.
+Another: that workspace belongs to the environment it was first opened for. Only `--apply` opens it — a dry
+run works in a temporary workspace, so it binds nothing, previews from any folder, and warns when an `--apply`
+there would be stopped. A build pointed at a different `--env` **halts before reading or writing anything in
+it** and names both environments. It is never cleared or re-bound for you — that discards the SDK's saved copies
+of the other environment's artifacts, including any edit made in them that was never pushed, and the
+page-ownership receipts and baseline kept beside them are that environment's too. Build against the
+environment the halt names, or use a fresh app folder (copy `app-spec.json` and the files it names) or a new
+`--workspace`. Only if that environment's copy of the app is no longer wanted, tear it down there with the
+`--clear-workspace` command the halt prints, which keeps the folder while a page-ownership receipt remains. The
+halt prints the folder on a line of its own, and that command takes it as `--workspace` — pass it exactly as
+printed, quoted for your shell (inside double quotes PowerShell and bash expand a `$` in the path). A folder that
+holds nothing a build saved — the SDK's empty folders only, which an earlier preview or a build that stopped at
+its start leaves — is described as exactly that: nothing was built in that environment, so there is nothing to go
+back to or tear down, and the folder can simply be deleted or moved aside. A folder whose `manifest.json` names
+no usable environment, or is not valid JSON, halts too: move it aside (rename it rather than delete it — it can
+hold page-ownership receipts and the baseline) and run again. The same environment under its other host name
+(`<org>.api.crm…` against `<org>.crm…`) also halts: re-run with the host the halt names. The standalone verifier
+never opens that workspace either, so it verifies any environment the app is deployed to.
+
+With `--publish`, the edits a build makes to existing views and forms go live in one publish of their tables, made
+before the build publishes the app, and the final publish covers them again.
+A build that **halts with an error** publishes what it had already saved before it stops (best effort).
+One that is **killed** — Ctrl-C, a crash, a closed terminal — after those edits are saved but before
+that publish cannot, so they stay saved but not live until the next build. Run the same full build
+again: it publishes them without writing them again.
### Phase 3 — Verify & iterate
**`--apply --verify` already reconciled the spec against what deployed** (Phase 2) — the build appends a
@@ -476,11 +532,21 @@ node "${PLUGIN_ROOT}/scripts/teardown-model-app.js" \
the manifest web resource and rebuild from scratch.
- `pages-removed` — a live page was dropped from the spec. Re-add it, or pass `--allow-destructive`
to detach it from the nav (the page record stays deployed; rebuild finalizes the sitemap).
- - `pages-shared-across-apps` — the page appears in another app's sitemap. Detach it in Maker.
- `--allow-destructive` does **not** bypass this halt.
+ - `pages-shared-across-apps` — the page appears in another app's sitemap, published or only saved (not yet
+ published — an app that was never published counts). Detach it in Maker. `--allow-destructive` does **not** bypass this halt.
+ The build checks again right before it updates pages in place, so a page another app takes in while the build runs halts it
+ there too ("became shared across apps while this build ran"); one taken in while the pages upload is reported after them as a
+ warning naming the app, since it is written by then.
- `pages-shared-check-failed` / `pages-existence-failed` / `pages-sitemap-read-failed` — a
prerequisite read failed; the build can't proceed safely. Retry on a transient error; check
permissions on a persistent one.
+ - `pages-griffel-shorthand` — a page's `makeStyles` writes a CSS shorthand Griffel drops at runtime, so the page
+ would deploy without its border, color or reset. The message names the page, each key's line and column, and the
+ longhands to write; fix the page's source and re-run. Nothing was uploaded. It is raised for a page the build would
+ create and for a page whose source changed since the last build; a page you did not touch that already has one is sent
+ again as it is, with a warning (it renders without the key today). Deleting a key keeps the page looking as it does;
+ writing the longhands makes the style start to render. The same halt reports a `makeStyles` call the check cannot read
+ for certain as that — not as CSS Griffel drops — and says what to change in the code.
- **`--non-interactive`** — suppress interactive prompts (for automation / CI). A non-interactive
build that encounters an existing app **fails** instead of warning-and-proceeding, unless
`--allow-destructive` is also set. Does **not** grant destructive authority on its own — only
@@ -560,7 +626,19 @@ Then:
1. **Always pull fresh at the start of an edit session** — someone may have changed the app in Maker. The
build reads an etag when it hydrates, so a write against an artifact changed since the pull throws a
version conflict → **re-pull and retry**, never clobber.
-2. Edit `app-spec.json` (and any page `.tsx`) for the requested change.
+2. Edit `app-spec.json` (and any page `.tsx`) for the requested change. A page you edit by hand is
+ checked like a generated one: run `node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file <page.tsx>`
+ on it before you rebuild (the rule and the ten shorthands are in Phase 1.5, step 5) and fix what it
+ reports. A key the page already had when it was downloaded is reported too: the deployed page renders
+ without it today, so deleting it keeps the page looking as it does, while writing the longhands makes
+ the style start to render — delete it unless the user wants that change. The build runs the same
+ check on every page it uploads that is new or that you changed since the last successful apply of this app, and halts as
+ `pages-griffel-shorthand` — naming the page, each key's line and column, and the longhands — so a page
+ you changed does not reach the app with one. "Changed" is measured against the source that apply recorded for the page in
+ `.maker-workspace/last-applied.json` (a successful full or changed-only apply, or a download, writes it; a failed or partial build records nothing).
+ A page you did not touch is sent again as it is, and a
+ key it already has only draws a warning — and so does a page you changed in a workspace that holds no record of it (a new or moved one, or
+ another environment), where the build cannot tell what was sent: run the checker on that page yourself.
3. **If the edit ADDS a page** (or resets a page's `source` back to `intent` to regenerate it),
**re-run Phase 1.5 before Phase 2** — a downloaded spec contains only `kind: "tsx"` pages, so an
added `intent` page has no code and Phase 2's `deploy` profile rejects it. Phase 1.5 is safe to
@@ -612,12 +690,16 @@ child view id. Each step emits `[n/total]`.
the Web API using an `az`-token HttpClient. No relay, no designer tab.
- **Dedicated unmanaged solution per app** (review / teardown). **`--publish` gates the final
*bulk* publish** of the app's entity + app customizations (one `PublishXml` for every entity and the
- app, which also carries the default-view enrichment's publish, deferred to it). It
+ app). With `--publish` that one publish also carries the default-view enrichment, and the tables touched
+ by the reconcile of an existing form or view, form events and quick-view placement are published
+ together once more, before the app is, so none of them publishes on its own. It
does **not** suppress the small **targeted** publishes that edit/finalize paths must run so the change
- takes effect — reconciling an existing form or view, wiring form events, placing quick-views,
- re-syncing an existing app's sitemap, and finalizing the sitemap after generative pages each publish
- that one artifact (an unpublished edit to a live artifact is invisible). A fresh build without
- `--publish` still leaves new tables/columns/relationships staged-but-unpublished in the solution.
+ takes effect: without `--publish`, reconciling an existing form or view, wiring form events and
+ placing quick-views each publish that one artifact, and with or without it, re-syncing an existing
+ app's sitemap and finalizing the sitemap after generative pages publish the app, and repairing a
+ lookup column still labelled with an old default publishes its table (an unpublished edit
+ to a live artifact is invisible). A fresh build without `--publish` still leaves new
+ tables/columns/relationships staged-but-unpublished in the solution.
- **Idempotent — but not full desired-state convergence.** Existing
solution/tables/columns/relationships/views/charts/forms/commands/dashboards are detected and
**reused**, so re-runs and existing-table envs work without collisions. **The caveat for EDITS:** a
@@ -656,7 +738,8 @@ child view id. Each step emits `[n/total]`.
**Boolean `defaultValue`**, whole-number **`integerFormat`** (incl. `Duration`), and per-column
**write permissions** (`isValidForCreate` / `isValidForUpdate` / `isValidForRead` — this is how you
make a column read-only), all applied on **create and on rebuild**; adaptive
- main forms with **1:N / N:N sub-grids**; **per-field form control** (`readOnly` / `hidden` /
+ main forms with **1:N / N:N sub-grids** (placed between sections or in a tab / form-column with
+ `tab` / `column` / `after` / `before`, and moved into place on rebuild); **per-field form control** (`readOnly` / `hidden` /
`after` positioning, plus `prune: false` to edit a subset of a form non-destructively);
**quick-create / quick-view forms** (`formType`) + **quick-view placement**
(`forms[].quickViews[]`); **per-form security roles** (`forms[].securityRoles` — name the
diff --git a/plugins/model-apps/skills/genpage/SKILL.md b/plugins/model-apps/skills/genpage/SKILL.md
index 04b2a64ed..f8f016e29 100644
--- a/plugins/model-apps/skills/genpage/SKILL.md
+++ b/plugins/model-apps/skills/genpage/SKILL.md
@@ -153,7 +153,8 @@ node "${PLUGIN_ROOT}/scripts/generate-page-manifest.js" '<working-dir>' '<kebab-
> 1. Prerequisite validation (`node --version`, `pac help` version > 2.10.0)
> 2. Auth verification (`pac auth list`, environment selection)
> 3. The structured "Create new / Edit existing" question (`AskUserQuestion`)
-> 4. Language detection (`pac model list-languages`) — only on new-page path
+> 4. Language detection (`node "${PLUGIN_ROOT}/scripts/list-languages.js" --env '<envUrl>'`; when that exits
+> non-zero, `pac model list-languages --environment '<envUrl>'` — the Azure CLI is not needed here) — only on new-page path
> 5. Entity existence detection (`pac model list-tables --search`)
> 6. App detection (`pac model list`) with proper selection prompts
> 7. Plan-mode presentation and approval (`EnterPlanMode` / `ExitPlanMode`)
@@ -746,10 +747,39 @@ subagent. Inline the page-builder workflow directly in the orchestrator:
`${PLUGIN_ROOT}/references/verified-icons.txt` (one Grep per name).
Rewrite any unverified names with the closest verified alternative; do not
load the full icon list into context
-9. Grep the generated file with `['"]?borderWidth['"]?\s*:`. Griffel rejects
- that shorthand only at runtime; the regex catches unquoted, quoted, and
- whitespace-separated property syntax. Replace every match with the four
- explicit border-side widths before deployment.
+9. Check the generated file for the Griffel shorthands that `makeStyles` drops at
+ runtime:
+
+ ```powershell
+ node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file '<working-dir>/<filename>.tsx'
+ ```
+
+ Griffel does not support ten CSS shorthands, and `makeStyles` drops them at
+ runtime: the page type-checks, transpiles and deploys, then renders without the
+ border, color or reset. They are `all`, `borderColor`, `borderStyle`,
+ `borderWidth`, `borderBlock`, `borderBlockStart`, `borderBlockEnd`,
+ `borderInline`, `borderInlineStart` and `borderInlineEnd`. Write longhands
+ instead: `borderColor`, `borderStyle` and `borderWidth` become one longhand per
+ side, `border` + `Top`, `Right`, `Bottom` or `Left` + `Color`, `Style` or `Width`
+ (`borderWidth` → `borderTopWidth`, `borderRightWidth`, `borderBottomWidth`,
+ `borderLeftWidth`); `borderBlock`, `borderInline` and their `Start` and `End`
+ forms become the `Width`, `Style` and `Color` longhands of the sides they name
+ (`borderBlockStart` → `borderBlockStartWidth`, `borderBlockStartStyle`,
+ `borderBlockStartColor`; `borderBlock` → those and the three `borderBlockEnd…`
+ ones); `all` has no longhands, so set the properties you need one by one. Every
+ other shorthand (`padding`, `margin`, `border`, `borderRadius`, `gap`,
+ `outline`) is supported, and an inline `style={{ … }}` is not Griffel at all.
+
+ `check-griffel-styles.js` prints each problem it finds — a key Griffel drops in a
+ `makeStyles` call, at any depth, with its line, column and longhands, or a call
+ or a style object it cannot read, with what to change — and exits 3 while any is
+ left: fix what it reports and run it again, and do not transpile or upload the
+ page until it exits 0. It reads the style objects written inline in the call,
+ `makeStyles({ … })`, so write them there: one passed or spread in from elsewhere
+ (`makeStyles(styles)`, `...base`) is reported, because the check cannot see its
+ keys, and so is a key computed from an expression (`[key]: …`), whose name it
+ cannot see (a template that starts with `--`, `&`, `:` or `@` is read); Fluent's
+ `...shorthands.*(…)` and `...typographyStyles.*` may be spread as they are.
10. Run the completeness gate on the page you wrote — the same one 5c runs on a
worker's page, and this is also the page a 5c fallback produces:
@@ -842,8 +872,15 @@ recorded it: the worker wrote nothing, and what is there is an earlier attempt's
or `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, preserving
the same plan and dispatch inputs. This is the same inline fallback path for missing
-and invalid worker output. Then Grep every generated page with
-`['"]?borderWidth['"]?\s*:` and replace the unsupported Griffel shorthand before Phase 6.
+and invalid worker output. The workers have no shell, so they cannot run the Griffel
+check themselves; run it on every generated page, exactly as in step 9 of Phase 5b,
+
+```powershell
+node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file '<working-dir>/<filename>.tsx'
+```
+
+and fix what it reports in the page yourself before Phase 6. A page that has not
+exited 0 is not deployed.
### Phase 6: Deploy
@@ -966,6 +1003,27 @@ node "${PLUGIN_ROOT}/scripts/genpage-upload.js" `
Omit the `--connectors` line when Phase 4.5 did not write `connectors.json`, and the
`--actions` line when Phase 4.6 did not write `actions.json`.
+`genpage-upload.js` reads the code file and refuses a page whose `makeStyles` writes one of the ten Griffel shorthands
+(Phase 5b step 9): a create outright, before it lists, reads or writes anything, and an update for any key the deployed page
+did not already have (below). The result is `"code":"griffel-shorthand"`, with each key's `file:line:column`, its longhands
+and what each way out does in `error` (and the same list in `problems`). That is the same check as
+`check-griffel-styles.js`, held at the one place every upload passes, so a page that skipped the earlier gate still cannot
+ship a key it added without its border. Fix the page and run the upload again; no flag skips it, and
+`--overwrite-deployed` does not. The upload sends `pac` a copy of the bytes it checked, so a change saved to the file after
+the upload started is not sent — run the upload again to send it. It does not take `--compiled-code-file`: `pac` compiles the
+checked file itself.
+
+An update is held to what it **adds**. A page deployed before this check existed can already carry such a key — the old
+`borderWidth` grep never caught `borderColor` under `:hover` — and it renders without it today. The script downloads the
+deployed page anyway (for the base check below) and compares: a key the deployed page already had, set to the same value — the same key
+and value in the same slot and selector, or one that a renamed slot or a moved rule only relocated — goes ahead, and the result's `warnings`
+names each one with both ways out: **delete the key** (nothing changes on screen) or **write the longhands** (the style
+starts to render, so the page changes). Only a key the deployed page did not have — or one it had, given another value, because
+Griffel drops the new value just as it dropped the old, so the page would show none of the change — stops the upload. If the deployed page
+cannot be read (possible only with `--overwrite-deployed`), the update goes ahead with that warning. A `makeStyles` call the
+checker cannot read for certain is refused as one it could not read, with what to change in the code, unless the file is the
+deployed page itself.
+
**For mock data pages:** Same but omit `--data-sources`.
#### For updating existing pages (subsequent upload):
@@ -1008,6 +1066,11 @@ Before an update, the script downloads the deployed page and compares it with th
Log the marker, the check result (`code`, `lines`, `deployedCopy`) and that `Choice:` line in `workflow-log.md`. Do not re-run `genpage-base.js record` after a successful upload; the upload records the hash of the file it uploaded. When the readback matches (a BOM or a final CRLF is not a difference), the marker source is `upload`. When the readback differs, or cannot be read, the source is `upload-unverified` and still records that uploaded hash — not the bytes the service returned — and the result warns, so the next update refuses `deployed-changed` until the page is compared with `genpage-base.js check`. A seconds-long gap between the check and the upload is not covered.
+**A pac call that stalls is stopped, not waited on forever.** Every `pac model genpage` call these scripts make is bounded — 3 minutes to list or download, 10 minutes to upload (`POWER_PLATFORM_SKILLS_PAC_TIMEOUT_MS`, 1 second to 60 minutes, allows longer) — and its whole process tree is ended when the time is up. A listing or a download that times out is retried once. An **upload is never sent again by the script**: pac writes the page, records its prompt and agent message, then publishes, so one that was stopped may have done most or all of that, and sending it again can record the prompt a second time or overwrite a change someone saved in the meantime. Follow the message the script prints; do not simply re-run the command.
+
+- **An update that timed out, or failed,** "MAY HAVE LANDED" — pac can fail while publishing, after it wrote the page, so neither is sent again by the script. (A failure pac reports for its own arguments or files is an ordinary error: fix what it names and re-run.) Compare the deployed page with your file first: `node "${PLUGIN_ROOT}/scripts/genpage-base.js" check --env '<org-url>' --app-id '<app-id>' --page-id '<page-id>' --file '<working-dir>/<file>.tsx'`. `"contentSame": true` means the update landed: do not upload it again — run `genpage-base.js record` for that page and file so the marker matches what is deployed, and confirm in Maker that the page shows your change and is published. `"deployed": "unchanged"` means it did not land, and re-running the update is safe. `"deployed": "changed"` with `"contentSame": false` means someone else saved the page: treat it as the `deployed-changed` refusal above, with its choice and its `Choice:` line.
+- **A create that timed out** is an *uncertain* create, and is never run again — by the script, or by you. If the message says the page was **created as `<page-id>`**, it exists but was stopped before it was published, and before it was placed in the app if you asked for that. Add it to the app's navigation (in Maker, or `pac model genpage add --environment '<org-url>' --app-id '<app-id>' --page-id '<page-id>' --publish`), run `genpage-base.js record --app-id '<app-id>' --page-id '<page-id>' --file '<working-dir>/<file>.tsx'` (the file is what was uploaded), then run the update with `--page-id`. Or delete the page and re-run the create. Without a page id in the message, wait a few minutes and list the environment's pages (`pac model genpage list --environment '<org-url>' --include-unpublished`): a new page of yours is handled as above, and the create is re-run only when none appeared. The same goes for a message that says the environment could not be listed after the create, so nothing is known about what it made. An update of a page that is not in the app's navigation is refused, and a second create makes a duplicate — so neither is the way on. A create that **failed** (not timed out) after pac had printed a `Page ID` is in the same state: its error says the page was **created as `<page-id>`** and that the create was not run again, with the same two ways on rather than "re-run it as an update". The build never re-sends such a create by itself either: every one of these errors is marked as one that is not to be retried.
+
### Phase 6.5: Navigation Fix-Up (Multi-Page Only)
Runs only when the plan has 2+ pages AND any built `.tsx` contains a `PAGEREF_`
diff --git a/plugins/model-apps/skills/genpage/edit-flow.md b/plugins/model-apps/skills/genpage/edit-flow.md
index 281f8f534..d9ec3c3fa 100644
--- a/plugins/model-apps/skills/genpage/edit-flow.md
+++ b/plugins/model-apps/skills/genpage/edit-flow.md
@@ -370,11 +370,50 @@ or approved edit plan when the edit touches connector data access.
Do NOT rewrite the entire file. Use the minimum necessary `Edit` operations.
-Before Edit Phase 6, Grep the edited `page.tsx` with
-`['"]?borderWidth['"]?\s*:`. Griffel rejects that shorthand only at runtime;
-the regex also catches quoted keys and whitespace before the colon. Replace every match with
-`borderTopWidth`, `borderRightWidth`, `borderBottomWidth`, and
-`borderLeftWidth`. Do not upload while any match remains.
+Before Edit Phase 6, check the edited page for the Griffel shorthands that
+`makeStyles` drops at runtime:
+
+```powershell
+node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file '<working-dir>/<page-id>/page.tsx'
+```
+
+Griffel does not support ten CSS shorthands, and `makeStyles` drops them at
+runtime: the page type-checks, transpiles and deploys, then renders without the
+border, color or reset. They are `all`, `borderColor`, `borderStyle`,
+`borderWidth`, `borderBlock`, `borderBlockStart`, `borderBlockEnd`,
+`borderInline`, `borderInlineStart` and `borderInlineEnd`. Write longhands
+instead: `borderColor`, `borderStyle` and `borderWidth` become one longhand per
+side, `border` + `Top`, `Right`, `Bottom` or `Left` + `Color`, `Style` or `Width`
+(`borderWidth` → `borderTopWidth`, `borderRightWidth`, `borderBottomWidth`,
+`borderLeftWidth`); `borderBlock`, `borderInline` and their `Start` and `End`
+forms become the `Width`, `Style` and `Color` longhands of the sides they name
+(`borderBlockStart` → `borderBlockStartWidth`, `borderBlockStartStyle`,
+`borderBlockStartColor`; `borderBlock` → those and the three `borderBlockEnd…`
+ones); `all` has no longhands, so set the properties you need one by one. Every
+other shorthand (`padding`, `margin`, `border`, `borderRadius`, `gap`,
+`outline`) is supported, and an inline `style={{ … }}` is not Griffel at all.
+
+`check-griffel-styles.js` prints each problem it finds — a key Griffel drops in a
+`makeStyles` call, at any depth, with its line, column and longhands, or a call
+or a style object it cannot read, with what to change — and exits 3 while any is
+left: fix what it reports and run it again, and do not transpile or upload the page
+until it exits 0. It reads the style objects written inline in the call,
+`makeStyles({ … })`, so write them there: one passed or spread in from elsewhere
+(`makeStyles(styles)`, `...base`) is reported, because the check cannot see its
+keys, and so is a key computed from an expression (`[key]: …`), whose name it cannot
+see (a template that starts with `--`, `&`, `:` or `@` is read); Fluent's
+`...shorthands.*(…)` and `...typographyStyles.*` may be spread as they are.
+
+A page that was deployed before this check existed can already hold such a key, so the
+checker may report one that your edit did not add. The deployed page renders without it
+today, which is why there are two ways out: **delete the key** — nothing changes on
+screen, so it is the edit that preserves the page — or **write the longhands**, which
+makes the style start to render, so the page changes. Delete it unless the user asked for
+that change, and say in the summary which you did. (`genpage-upload.js` refuses only a key
+the deployed page did not already have — or one it had, given another value — and lets one it did have, set
+the same, go ahead with a
+`warnings` entry, but the page then goes on rendering without it — do not rely on that to
+skip this step.)
## Edit Phase 6: Deploy Updated Page
diff --git a/plugins/model-apps/skills/genpage/verify-flow.md b/plugins/model-apps/skills/genpage/verify-flow.md
index 882ca4fae..4fe2b488f 100644
--- a/plugins/model-apps/skills/genpage/verify-flow.md
+++ b/plugins/model-apps/skills/genpage/verify-flow.md
@@ -94,9 +94,24 @@ complete visual record for the deployment summary.
## 7.5 Fix and Re-deploy
-If issues are found: fix the code, re-deploy using the **update form** from
-Phase 6 — `node "${PLUGIN_ROOT}/scripts/genpage-upload.js"` with `--page-id` and
-no `--add-to-sitemap`. Per the "Prompt semantics" rule, the prompt for this
+If issues are found: fix the code, check it, and re-deploy using the **update form**
+from Phase 6 — `node "${PLUGIN_ROOT}/scripts/genpage-upload.js"` with `--page-id` and
+no `--add-to-sitemap`. A fix is new code, and new code can write a CSS shorthand that Griffel
+drops at runtime (the page then deploys without its border, color or reset — the rule is
+`references/rules.md` Common Pitfalls 5, and Phase 5b step 9 runs the same gate), so check the
+fixed page before the re-deploy:
+
+```powershell
+node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file '<working-dir>/<file>.tsx'
+```
+
+Do not upload until it exits 0: fix what it reports (each key's line, column and longhands)
+and run it again. `genpage-upload.js` makes the same check and refuses a page that adds a key the
+deployed page did not already have, or gives one it had another value (`griffel-shorthand`), so skipping this step costs a refused
+upload, not a shipped defect. A key the page already had before your fix, set the same, is reported as well:
+delete it to keep the page looking as it does, or write the longhands to make the style start to
+render (a visible change, so only when it is wanted).
+Per the "Prompt semantics" rule, the prompt for this
re-deploy describes the fix delta only — e.g.
`"Fix sort handler on Name column; correct accidental DataGrid type prop"` —
not a re-statement of the full page description. Write it to a file and pass